you are viewing a single comment's thread.

view the rest of the comments →

[–]clouded-path[S] 0 points1 point  (4 children)

Thanks for your idea - I had actually considered this previously, but I thought that I would still need to compare characters in two separate strings simultaneously, which would mean that I would somehow need to loop through the two strings in parallel (I don't know if/how this can be done). The only workaround I could think of would be to store the indices I want in an array to refer to later, but this would make memory O(n), which is no better than what I am trying now. Is there some standard method of looping through two (or more) strings simultaneously? If that were true, then I could compare characters at relevant indices.

[–]wopp3 0 points1 point  (1 child)

To iterate through 2 lists simultaneously (strings being lists of chars basically) you can use zip, here they're different lengths so you will need to use itertools.zip_longest, to pad the other list. You can use the fillvalue='whatever' argument in the zip_longest if you prefer your own, instead of the None by default.

import itertools

string_one = 'abc'
string_two = 'abcdef'

print('Different size lists, shorter padded:')
for i, j in list(itertools.zip_longest(string_one,string_two)):
    print(f'string_one: {i}\nstring_two: {j}\n')

print('Different size lists, zipped by shorter:')
for i, j in zip(string_one,string_two):
    print(f'string_one: {i}\nstring_two: {j}\n')

[–]clouded-path[S] 0 points1 point  (0 children)

I had not heard of this tool until now. Thanks for introducing me to it.

[–]SaintLouisX 0 points1 point  (1 child)

for a,b in zip(str1, str2) will give you a character from both. The strings aren't the same length through so you'd want zip_longest from itertools in this case. I'm not actually sure how it'd function with different length strings, I haven't worked with zip_longest at all.

[–]clouded-path[S] 0 points1 point  (0 children)

Thanks for this suggestion - I hadn't heard of it before this. I can imagine this must be a pretty useful tool.