python - Cannot understand why IDLE gui is not returning the values that the author is saying it should return
问题描述
I am reading the book Learning Python and the author provides these two snippets of code, he then runs "abc" like so permute1("abc") and this returns all the permutations of abc, when I do it in IDLE. It returns ['abc']. I don't understand how the author is saying that it should return ['abc', 'acb' -- etc ] What am I missing here?
def permute1(seq):
if not seq:
return [seq]
else:
res = []
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:]
for x in permute1(rest):
res.append(seq[i:i+1] + x)
return res
def permute2(seq):
if not seq:
yield seq
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:]
for x in permute2(rest):
yield seq[i:i+1] + x
解决方案
Looks like you added an extra indentation to the return res
line in your first for loop.
This is making your function terminate early. After we unindent that permute1("abc")
works as expected.
推荐阅读
- python - 我的 python 代码没有执行我编写的函数(程序)
- c - 标识符 wchar_t 未定义
- rxjs - RXJS 在事件触发时发出数组项
- json - 如何使用 jq 从 terraform 状态文件中提取特定字段?
- python - Jupyter 没有执行暂存器单元
- apache-spark - 运行依赖于另一个任务的 Luigi 任务
- java - 将 Firebase Auth 从 Android SDK 切换到 Firebase Admin SDK
- django-rest-framework - 如何根据 Django Rest Framework 中的 JWT 有效负载覆盖 GET 方法?
- c# - C#元组不保留名称,只使用'itemx'
- javascript - 获取 div 的边界框,按 chromium/puppeteer 中的列数拆分