python - 为不同大小制作循环定义
问题描述
所以我正在制作一个基本的真值表函数。在这个例子中,公式有 4 个值,因此需要 4 个循环。我有什么办法可以制作一个 def 来获取公式中的值的数量并为其创建一个循环?
def Formula1(a,b,c,d):
return ((a & c) | (b & c) | (d & c))
for a in range(0,2):
for b in range(0,2):
for c in range(0, 2):
for d in range(0, 2):
#printtable(a,b,c,d)
print(a,b,c,d,"=",Formula1(a,b,c,d))
例如这里的公式有 5 个值,需要 5 个循环。
def Formula2(a,b,c,d,e):
return ((not a & b) | (c & b) | (d & (not e)))
解决方案
使用itertools
:
import itertools
def Formula1(a, b, c, d):
return ((a & c) | (b & c) | (d & c))
if __name__ == '__main__':
table = list(itertools.product([False, True], repeat=4))
for a,b,c,d in table:
print("{}, {}, {}, {} = {}".format(a, b, c, d, Formula1(a, b, c, d))
结果(table
是所有组合):
False, False, False, False = False
False, False, False, True = False
False, False, True, False = False
False, False, True, True = True
False, True, False, False = False
False, True, False, True = False
False, True, True, False = True
False, True, True, True = True
True, False, False, False = False
True, False, False, True = False
True, False, True, False = True
True, False, True, True = True
True, True, False, False = False
True, True, False, True = False
True, True, True, False = True
True, True, True, True = True
推荐阅读
- java - 通用 memoize 函数抛出 ConcurrentModificationException
- php - 如何在 PHP 中的子类继承方法中定义更严格的类型?
- redis - 如何从java代码执行redis缓存INFO命令
- sql - 按特定顺序对值进行排序 Oracle SQL
- python - 尝试使用 pip 安装“请求”包时出现 Python 错误
- reactjs - 材料 ui 未安装在 React Js 项目中
- javascript - handleSubmit [React] 处理程序的正确实现
- python - Twitter API 发布请求——错误代码 215 错误的身份验证数据
- firebase - Firebase Auth:是否可以同时登录两台设备?
- reactjs - 使用 next.js 时出现服务器错误,错误:找不到 react-redux 上下文值;请确保组件被包裹在一个