+ 2

optimize code in Python

I created and solved a problem using Python and I would like to know if it can be done in any way better. We have a string where one letter needs to be replaced with a substitute, on every position in the string from it's own possible values. The generated strings have only one letter different from the original. s = "aaaaa" e = ["bcdefgh", "ijklmn", "opqrs", "tuvw", "xyz"] i = 0 for a in e: j = 0 for c in range(len(a)): print(s[:i] + a[j] + s[i+1:]) j += 1 i += 1 Thank you.

18th Mar 2021, 5:12 AM
Eddy M
4 Answers
+ 1
You could also iterate over the characters of a as a list instead of iterating c over the indexes into the string like this: s = "aaaaa" e = ["bcdefgh", "ijklmn", "opqrs", "tuvw", "xyz"] for i, a in enumerate(e): for c in list(a): print(s[:i] + c + s[i+1:]) Yes, there are lots of ways to do this even if none will significantly improve performance. Since s is all 'a', you could also do this to get the same behaviour without having an s variable: e = ["bcdefgh", "ijklmn", "opqrs", "tuvw", "xyz"] for i, a in enumerate(e): for c in list(a): print('a' * i + c + 'a' * (4 - i))
18th Mar 2021, 7:14 AM
Josh Greig
Josh Greig - avatar
+ 2
The code you shared can't be made much faster without changing how it behaves. I found a couple changes that may make the code cleaner, though. A small improvement to clean up the code would be to remove the variable j. j is the same as c in your nested loop so you can get the same behaviour from this code: s = "aaaaa" e = ["bcdefgh", "ijklmn", "opqrs", "tuvw", "xyz"] i = 0 for a in e: for c in range(len(a)): print(s[:i] + a[c] + s[i+1:]) i += 1 Another minor change that just might make things cleaner is the enumerate function. Using enumerate, you can stop calling "i = 0" and "i += 1". Below uses enumerate and the above suggestion to remove j. s = "aaaaa" e = ["bcdefgh", "ijklmn", "opqrs", "tuvw", "xyz"] for i, a in enumerate(e): for c in range(len(a)): print(s[:i] + a[c] + s[i+1:])
18th Mar 2021, 5:43 AM
Josh Greig
Josh Greig - avatar
0
Thank you very much. Somehow I felt bad about using those counters in parallel with the loops.
18th Mar 2021, 7:06 AM
Eddy M
0
@Josh Greig Using list(a) you managed to further shorten the code length but I used only 'a' in s just to make the problem look better. In the past when I had this kind of problem s was not known beforehand and also the list of values didn't look so predictable. To keep the code reusable I wouldn't look for improvements in how s and e are defined.
18th Mar 2021, 7:51 AM
Eddy M