Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- permutations ([])
- []
- permutations ([1,])
- [1]
- permutations ([1,2])
- [1, 2]
- [2, 1]
- permutations ([1,2,3])
- [1, 2, 3]
- [1, 3, 2]
- [2, 1, 3]
- [2, 3, 1]
- [3, 1, 2]
- [3, 2, 1]
- import itertools
- itertools.permutations([1,2,3])
- def all_perms(str):
- if len(str) <=1:
- yield str
- else:
- for perm in all_perms(str[1:]):
- for i in range(len(perm)+1):
- #nb str[0:1] works in both string and list contexts
- yield perm[:i] + str[0:1] + perm[i:]
- import itertools
- itertools.permutations([1,2,3])
- import itertools
- print list(itertools.permutations([1,2,3,4], 2))
- [(1, 2), (1, 3), (1, 4),
- (2, 1), (2, 3), (2, 4),
- (3, 1), (3, 2), (3, 4),
- (4, 1), (4, 2), (4, 3)]
- print list(itertools.combinations('123', 2))
- [('1', '2'), ('1', '3'), ('2', '3')]
- print list(itertools.product([1,2,3], [4,5,6]))
- [(1, 4), (1, 5), (1, 6),
- (2, 4), (2, 5), (2, 6),
- (3, 4), (3, 5), (3, 6)]
- print list(itertools.product([1,2], repeat=3))
- [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
- (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
- myset = set((1,2,3))
- print myset
- set([1, 2, 3])
- myiterable = tuple(myset)
- print myiterable
- (1, 2, 3)
- def permutations (orig_list):
- if not isinstance(orig_list, list):
- orig_list = list(orig_list)
- yield orig_list
- if len(orig_list) == 1:
- return
- for n in sorted(orig_list):
- new_list = orig_list[:]
- pos = new_list.index(n)
- del(new_list[pos])
- new_list.insert(0, n)
- for resto in permutations(new_list[1:]):
- if new_list[:1] + resto <> orig_list:
- yield new_list[:1] + resto
- def permute_in_place(a):
- a.sort()
- yield list(a)
- if len(a) <= 1:
- return
- first = 0
- last = len(a)
- while 1:
- i = last - 1
- while 1:
- i = i - 1
- if a[i] < a[i+1]:
- j = last - 1
- while not (a[i] < a[j]):
- j = j - 1
- a[i], a[j] = a[j], a[i] # swap the values
- r = a[i+1:last]
- r.reverse()
- a[i+1:last] = r
- yield list(a)
- break
- if i == first:
- a.reverse()
- return
- if __name__ == '__main__':
- for n in range(5):
- for a in permute_in_place(range(1, n+1)):
- print a
- print
- for a in permute_in_place([0, 0, 1, 1, 1]):
- print a
- print
- def permutations(head, tail=''):
- if len(head) == 0: print tail
- else:
- for i in range(len(head)):
- permutations(head[0:i] + head[i+1:], tail+head[i])
- permutations('abc')
- def permutList(l):
- if not l:
- return [[]]
- res = []
- for e in l:
- temp = l[:]
- temp.remove(e)
- res.extend([[e] + r for r in permutList(temp)])
- return res
- list2Perm = [1, 2.0, 'three']
- listPerm = [[a, b, c]
- for a in list2Perm
- for b in list2Perm
- for c in list2Perm
- if ( a != b and b != c and a != c )
- ]
- print listPerm
- [
- [1, 2.0, 'three'],
- [1, 'three', 2.0],
- [2.0, 1, 'three'],
- [2.0, 'three', 1],
- ['three', 1, 2.0],
- ['three', 2.0, 1]
- ]
Add Comment
Please, Sign In to add comment