python - 在 Python 中编写多个条件是否有不同的方法?
问题描述
我是 python 新手,我正在做 TWO + TWO = FOUR,其中每个字母代表 1-10 的不同数字。我需要找到所有组合。我想知道是否有更好的写法,尤其是'if'和'for'
for t in range (1,10):
for f in range (1,10):
for w in range(10):
for o in range(10):
for u in range(10):
for r in range(10):
if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*10 + r and t is not f and t is not w and t is not o and t is not u and t is not r and f is not w and f is not o and f is not o and f is not u and f is not r and w is not o and w is not u and w is not r and o is not u and o is not r and u is not r:
print(t,w,o, "and", f,o,u,r)
我试过这样写,但它给了我超过 7 个结果
if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*10 + r and t != f != w != o != u != r
解决方案
您可以使用这样的简单技巧:
for t in range (1,10):
for f in range (1,10):
for w in range(10):
for o in range(10):
for u in range(10):
for r in range(10):
if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*10 + r and len(set([t,f,w,o,u,r])) == 6:
print(t,w,o, "and", f,o,u,r)
这个想法set
只是存储不同的数字,所以如果它们是成对不同的,那么集合的长度应该等于变量的数量
推荐阅读
- linux-kernel - 如果默认时间片为 100 毫秒,Linux 进程如何每秒产生 60 次图形输出?
- powerbi - PowerBI,堆叠图中一列中的更改顺序
- jquery - 使用jQuery将空值设置为禁用的文本框
- github - github 用户名不区分大小写会产生自冲突的用户名变体
- c - 创建由`calloc`分配的多维数组指针或嵌套双指针
- rust - 基于通过该列表的循环在列表中设置值
- python - != 符号被忽略?
- .htaccess - 有没有办法使用htaccess从url文件名中删除#?
- python - 正则表达式用前一天替换一天
- c# - 如何解析 XMLDocument InnerText/InnerXML 字符串