递归 - 为什么Python打印此值?
我是初学者Python粉丝。
注意 - 我知道,一个“返回”缺少。 功能的目的:给出具有重复启动的序列。我们不知道这些“前缀”有多长时间,但是我们确实知道有7种不同的前缀(相同的长度)。我们需要找到这些前缀。
但是,我很好奇该程序如何在没有这个词的情况下运作。 为什么函数打印集(最后一行) - 不应该停止:搜索(...),回到顶部,然后在设置足够长时间就扔掉了?
我还注意到,如果我在“其他:”和“搜索(...)'之间进行打印,则设置按照正常顺序打印,如果在“搜索(...)”下以相反的顺序(即从最长的单词来看)。
如果有人能解释为什么它完全以相反的顺序打印:),我会很感激。
def search(seq_list, length, position=1):
seq_set = set()
for a in seq_list:
seq_set.add(a[:position])
if len(seq_set) == length:
return seq_set
else:
search(seq_list, length, position + 1)
print(seq_set)
I'm beginner python fan.
Note - I know, one "return" is missing.
Purpose of function: sequences with a repeating beginning are given. We don't know how long these "prefixes" are, but we do know there are 7 different ones (the same length). We need to find these prefixes.
However, I am curious how the program works without that word. Why does the function print sets (last line) - shouldn't it still stop at else: search (...), go back to the top, and throw out just None when set is long enough?
I also noticed that if I put print between 'else:' and 'search(...)', the sets are printed in the normal order, and if under 'search(...)'- in the reverse order (ie from where the words are longest).
I would be grateful if someone could explain why it prints at all and in reverse order :)
def search(seq_list, length, position=1):
seq_set = set()
for a in seq_list:
seq_set.add(a[:position])
if len(seq_set) == length:
return seq_set
else:
search(seq_list, length, position + 1)
print(seq_set)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,它不会停止。函数不仅返回,因为递归调用返回。
搜索
完成,返回其值,然后呼叫者忽略该值,然后继续进行print(seq_set)
。目前尚不清楚它“有效”,因为您要打印
seq_set
的本地值,而不是递归呼叫返回而忽略的递归呼叫。No, it won't stop. A function doesn't return just because a recursive call returns.
search
finishes, returns its value, then the caller ignores that value and continues on toprint(seq_set)
.It's not clear that it "works", since you are printing the local value of
seq_set
, not the one the recursive call returns and you ignore.