我检查了每个单独的元素,看来我的增量函数变成了无限循环.但是,如果我减少了产生的字符串数量,这似乎是可行的. 有人可以向我解释为什么尝试返回所有可能的值时程序会失败吗?假设您必须在不使用itertools的情况下执行相同的操作,那么您将如何完成任务? 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")))解决方案您不要在此处增加n def增量(lst,n): 如果n == 0: 返回lst ## ERROR:无限循环?因此n的值始终为0 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 这篇关于Python程序陷入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-12 07:33