This piece of code has given me a serious headache. It's supposed to be a generator that takes a string as an input, and replaces all '{}'s with all possible letter combinations, essentially working in a similiar manner to itertools.permutations() but with the addition of constant values.
I've checked each individual element, and it appears that my increment function turns into an infinite loop. It seems to work if I reduce the number of strings being produced, however. Can someone explain to me why the program fails when trying to return all possible values? Assume you had to do the same without using itertools, how would you accomplish the task?
def string_char_combinations(string, chars=False):
if not chars:
chars = [chr(i) for i in range(ord('a'), ord('z')+1)]
varcount = string.count('{}')
a = [0 for i in range(varcount)]
def increment(lst, n):
if n == 0:
return lst ##ERROR: Infinite loop?
print(n)
lst[n] += 1
print(lst)
if lst[n] > len(chars)-1:
lst[n] = 0
lst = increment(lst, n-1)
return lst
while a[0] < len(chars)-1:
a = increment(a, len(a)-1)
yield string.format(*[chars[i] for i in a])
if __name__ == "__main__":
print(list(string_char_combinations("a{}{}a")))
解决方案
You don't incremente the n here
def increment(lst, n):
if n == 0:
return lst ##ERROR: Infinite loop?
So the value of n is always 0