python代码编程教学无限循环,Python程序陷入无限循环

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值