What's the most effective way to Iterate, while manipulating a list or string?

Tracy :

My goal is to create a code breaker in python. So far I have jumbled up the letters and as a result have a list of individual characters.

#Result of inputting the string 'hello world'
['C', 'V', 'N', 'N', 'H', 'X', 'H', 'K', 'N', 'O']

My aim is output this as a string with a space 'CVNNH XHKNO'

Now I have several options but I'm unsure which one would the best: Do I convert it to a string first before manipulating it or manipulate the list before converting to a string.

I have the following helpers available from the process so far (automatically)

length = [5,5] #list
total_chars = 10 #int
no_of_words = 2 #int

I have converted it to a string CVNNHXHKNO and thought about inserting the space after the 5th letter by calculating a start point[0], mid point[5] and end point[11].

start = 0
mid_point = total_chars - length[0]

print(mid_point)
first_word = message[start:mid_point]
print(first_word)

second_word = message[mid_point:total_chars]
print(second_word)

completed_word = first_word + ' ' + second_word
print(completed_word)

Unfortunately this is just manually and doesn't take into account if there a 5 or more words. I have attempted to iterate over the original list of individual characters in nested for loops using the list length but seem to confuse myself and overthink.

adnanmuttaleb :

If you have this as inputs:

l = ['C', 'V', 'N', 'N', 'H', 'X', 'H', 'K', 'N', 'O']
length = [5,5] #list
total_chars = 10 #int
no_of_words = 2 #int

Then you can compute your output as follow:

words = []
pos = 0
for i in length:
  words.append("".join(l[pos:pos+i]))
  pos += i

result = " ".join(words)

print(words)
print(result)

Output:

['CVNNH', 'XHKNO']
CVNNH XHKNO

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397738&siteId=1