猪猪侠那里弄的python递归脚本

和collections库一样,还有一个库叫itertools,对某些问题真能高效地解决。其中一个用例是查找所有组合,他能告诉你在一个组中元素的所有可能的组合方式

from itertools import combinations
teams = ["a", "b", "c", "d"]
for game in combinations(teams, 2):
    print game
>>> ('a', 'b')
>>> ('a', 'c')
>>> ('a', 'd')
>>> ('b', 'c')
>>> ('b', 'd')
>>> ('c', 'd')


>>> import itertools
>>> list(itertools.combinations('abc', 2))
[('a', 'b'), ('a', 'c'), ('b', 'c')]
>>> list(itertools.permutations('abc',2))
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

>>>



z2 = []

def perm( teams, k, m ):
  global z2
  if k > m:
    z2.append( tuple(teams) )
    return
  else:
    for i in xrange( k, m+1 ):
      teams[k], teams[i] = teams[i], teams[k]
      perm( teams, k+1, m )
      teams[k], teams[i] = teams[i], teams[k]
  return

if __name__ == '__main__':
  teams = list( 'abc' )
  m = len( teams )
  perm( teams, 0, m-1 )
  print z2


你可能感兴趣的:(猪猪侠那里弄的python递归脚本)