Eug*_*nko 2 python for-loop set
如果你检查下面的代码我用于循环检查是否在一组单词中,一个单词是另一个单词的后缀.
我的问题是,如何替换双循环?编写任务的人提到有一个使用算法的解决方案(不确定是什么:/)
def checkio(words):
if len(words) == 1: return False
else:
for w1 in words:
for w2 in words:
if w1 == w2:
continue
elif w1.endswith(w2) or w2.endswith(w1): return True
else: return False
print checkio({"abc","cba","ba","a","c"}) # prints True in Komodo
print checkio({"walk", "duckwalk"}) # prints True
Run Code Online (Sandbox Code Playgroud)
第二个问题:似乎当前的功能在每个环境中都不起作用.有人能指出我做错了吗?它适用于我的Komodo IDE,但不适用于chekio网站.
让Python生成要检查的所有组合:
import itertools
def checkio(data):
return any((x.endswith(y) or y.endswith(x)) for x, y in itertools.combinations(data, 2))
Run Code Online (Sandbox Code Playgroud)
让Python测试它:
assert checkio({"abc","cba","ba","a","c"}) == True
assert checkio({"walk", "duckwalk"}) == True
assert checkio({"aaa", "bbb"}) == False
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
472 次 |
| 最近记录: |