如果你有方程和变量使用 Python 求解变量
Solving for variables if you have the equation and variables using Python
如果我有一个等式 (a + (b - c) d - e) f = 75
,我如何通过改变变量 a 到 f 来迭代?如果 a 到 f 是唯一的数字 [1,6],那么就会有 6!放置数字的方式,对吗?所以我想我必须以某种方式增加我的变量。
Assumptions/Limitations:
a-f 是唯一的整数 [1,6]
我正在使用 python 并尝试 在不使用内置函数或库的情况下求解
用6个嵌套的for循环枚举a,b,c,d,e,f分别设置为1-6的所有方法(我在理解如何组织时遇到问题)
显然只有一个排列可以求解这个特定的方程
可以使用itertools.permutations
(如果不想直接使用,文档中有代码示例):
>>> def func(a, b, c, d, e, f):
... return (a + (b - c) * d - e) * f == 75
>>> from itertools import permutations
>>> next(filter(lambda x: func(*x), permutations(range(1, 7), 6)))
(4, 6, 2, 3, 1, 5)
这似乎是使用集合的好时机:
In [17]: set1 = set([1,2,3,4,5,6])
In [18]: for a in set1:
...: for b in set1 - set([a]):
...: for c in set1 - set([a,b]):
...: for d in set1 - set([a,b,c]):
...: for e in set1 - set([a,b,c,d]):
...: for f in set1 - set([a,b,c,d,e]):
...: if (a + (b - c)*d - e)*f == 75:
...: print('found:', a, b, c, d, e, f)
...: break
...:
found: 4 6 2 3 1 5
In [19]: (4+(6-2)*3-1)*5
Out[19]: 75
通过使用集合之间的差异,您可以确保不会两次使用相同的值。例如:
In [20]: set([1,2,3,4,5,6]) - set([1,5])
Out[20]: {2, 3, 4, 6}
如果我有一个等式 (a + (b - c) d - e) f = 75
,我如何通过改变变量 a 到 f 来迭代?如果 a 到 f 是唯一的数字 [1,6],那么就会有 6!放置数字的方式,对吗?所以我想我必须以某种方式增加我的变量。
Assumptions/Limitations:
a-f 是唯一的整数 [1,6]
我正在使用 python 并尝试 在不使用内置函数或库的情况下求解
用6个嵌套的for循环枚举a,b,c,d,e,f分别设置为1-6的所有方法(我在理解如何组织时遇到问题)
显然只有一个排列可以求解这个特定的方程
可以使用itertools.permutations
(如果不想直接使用,文档中有代码示例):
>>> def func(a, b, c, d, e, f):
... return (a + (b - c) * d - e) * f == 75
>>> from itertools import permutations
>>> next(filter(lambda x: func(*x), permutations(range(1, 7), 6)))
(4, 6, 2, 3, 1, 5)
这似乎是使用集合的好时机:
In [17]: set1 = set([1,2,3,4,5,6])
In [18]: for a in set1:
...: for b in set1 - set([a]):
...: for c in set1 - set([a,b]):
...: for d in set1 - set([a,b,c]):
...: for e in set1 - set([a,b,c,d]):
...: for f in set1 - set([a,b,c,d,e]):
...: if (a + (b - c)*d - e)*f == 75:
...: print('found:', a, b, c, d, e, f)
...: break
...:
found: 4 6 2 3 1 5
In [19]: (4+(6-2)*3-1)*5
Out[19]: 75
通过使用集合之间的差异,您可以确保不会两次使用相同的值。例如:
In [20]: set([1,2,3,4,5,6]) - set([1,5])
Out[20]: {2, 3, 4, 6}