how to replace all values equal to 1 with letters from a text ?
And if the text doesn't fit entirely in the array, how to generate automatically new arrays identical to the first one to aim at containing all characters ?
Thanks in advance.
text = "helloworldddd"
my_array = [ [0,1,1],[1,1,0],[1,0,0] ]
result expecting: generated arrays which contains all characters
my_array2 = [ [0,h,e],[l,l,0],[o,0,0] ]
my_array3 = [ [0,w,o],[r,l,0],[d,0,0] ]
my_array4 = [ [0,d,d],[d,1,0],[1,0,0] ]
With lists and copying you should read about the difference of shallow and deepcopy, else you just copy the lists refs - not the values. Read more here: Deep copy a list in Python
Calculating how many repeats you need is easy, compute the number of 1s in the patters, divide length of string by that and add 1 for good measure (integer division is floor_division) if it would divide with rest (use mod to check that).
Deepcopy yourself a resultlist thats long enough and start replacing 1 by characters:
from itertools import chain # chaining multiple lists together
import copy # deepcopying the array to decouple copies
def createArr(t:str,arr:list):
"""Puts each character of t on the 1s of arr, extends arr with itself as pattern"""
ones = sum(1 if q==1 else 0 for n in arr for q in n) # how many 1 in pattern
mult = len(t)//ones # how many reps needed for our text?
if len(t)%ones != 0:
mult += 1
# create sufficient space by deepcopying the pattern into a longer list
rv = list(chain(*(copy.deepcopy(arr) for _ in range(mult))))
# start in sublinst on index 0
subidx = 0
# replace the 1s
for c in t: # walk all characters
# maybe advance sublist index - if no 1s left
while 1 not in rv[subidx] and subidx<len(rv):
subidx+=1
sub = rv[subidx] # get sublist
sub[sub.index(1)] = c # replace first 1 with act. char
return rv
text = "helloworldddd"
my_array = [ [0,1,1],[1,1,0],[1,0,0] ]
print(createArr(text,my_array))
Output:
[[0, 'h', 'e'], ['l', 'l', 0], ['o', 0, 0],
[0, 'w', 'o'], ['r', 'l', 0], ['d', 0, 0],
[0, 'd', 'd'], ['d', 1, 0], [1, 0, 0]]
You could partition that if need be, using the length of arr into equal parts, this high ranked questions and it's answers tell you how: How do you split a list into evenly sized chunks?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With