itertools.combinations在解方程时的一个妙用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jerry_1126/article/details/85087363

有时候在解方程时,比如说,x,y,z互不相等, x< y < z,且都在[1-6]之间,满足x + y + z == 6,要求x, y, z

使用itertools.combinations能起到很好的效果,先看下,itertools会产生什么数据。 

>>> import itertools
>>> help(itertools.combinations)
Help on class combinations in module itertools:

class combinations(__builtin__.object)
  |  combinations(iterable, r) --> combinations object
  |
  |  Return successive r-length combinations of elements in the iterable.
  |
  |  combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)
 

从上面来看,它会产生用于迭代的三个数据,比如说: combinations(range(4), 3),就会产生(0,1,2),(0,1,3),(0,2,3),(1,2,3)四个数据用于。可以先看下combinations(range(1,6), 3)产生什么数据。

>>> from itertools import combinations
>>> list(combinations(range(1,7), 3))
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 4), (1, 3, 5), (1, 3, 6), 
(1, 4, 5), (1, 4, 6), (1, 5, 6), (2, 3, 4), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6), 
(2, 5, 6), (3, 4, 5), (3, 4, 6), (3, 5, 6), (4, 5, 6)]
>>>

这样的话,要满足上面的条件的方程就好做了。 

>>> from itertools import combinations
>>> list(filter(lambda T: T[0] + T[1] + T[2] == 6, combinations(range(1, 7), 3)))
[(1, 2, 3)]

上面的答案基本上就满足了。 如果要求x, y, z三个不等的整数,满足所有x + y + z = 6的所有组合,这个时候就不能这样求了。

列表推导就少不了了。 

>>> [(x,y,z) for x in range(1,7) for y in range(1,7) for z in range(1,7) if x+y+z == 6 and x != y != z]
[(1, 2, 3), (1, 3, 2), (1, 4, 1), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

>>>

猜你喜欢

转载自blog.csdn.net/Jerry_1126/article/details/85087363