[英]How to break this recursive loop once I reach the last letter in my python code?
I would like to break the recursive loop once I reach the last letter of new.一旦到达 new 的最后一个字母,我想打破递归循环。 How can I do this?
我怎样才能做到这一点?
Diction is a dictionary. Diction是字典。 The idea here is that I get a word there is an example below and I shrink it by matching the [i:i+1] positions of the word string with the dictionary until it gets down to one letter.
这里的想法是我得到一个词,下面有一个例子,我通过将词串的 [i:i+1] 位置与字典匹配来缩小它,直到它缩小到一个字母。
def eval(word):
diction = {
'br': 'y',
'rb': 'y',
'by': 'r',
'yb': 'r',
'yr': 'b',
'ry': 'b',
'bb': 'b',
'yy': 'y',
'rr': 'r',
}
new = ''
i = 0
while i < len(word) - 1:
key1 = word[i:i + 2]
i += 1
new += diction[key1]
return eval(new)
word = 'brybbr'
print(eval(word))
You need to provide the end condition.您需要提供结束条件。
In this code, I added a condition if len(new)==1:
to finish the unlimited resursive calls.在这段代码中,我添加了一个条件
if len(new)==1:
来完成无限的递归调用。
In addition, I also added print(new)
inside the eval()
instead print(eval(word))
so that it can print new
with each calling of eval()
.此外,我还在
eval()
中添加了print(new)
而不是print(eval(word))
,以便它可以在每次调用eval()
时打印new
。
def eval(word):
diction = {
'br': 'y',
'rb': 'y',
'by': 'r',
'yb': 'r',
'yr': 'b',
'ry': 'b',
'bb': 'b',
'yy': 'y',
'rr': 'r',
}
new = ''
i = 0
while i < (len(word) - 1):
key1 = word[i:i + 2]
i += 1
new += diction[key1]
print(new) # to print new for every `eval()` calling.
if len(new)==1: # to stop endless resursive calling.
return None
else:
return eval(new)
word = 'brybbr'
eval(word)
# ybrby
# ryyr
# byb
# rr
# r
#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.