forked from mtarbit/Rosalind-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
e006-perm.py
executable file
·70 lines (53 loc) · 1.16 KB
/
e006-perm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python
# coding=utf-8
# Enumerating Gene Orders
# =======================
#
# A permutation of length n is some ordering of the positive integers {1,2,…,n}.
# For example, π=(5,3,2,1,4) is a permutation of length 5.
#
# Given: A positive integer n≤7.
#
# Return: The total number of permutations of length n, followed by a list of
# all such permutations (in any order).
#
# Sample Dataset
# --------------
# 3
#
# Sample Output
# -------------
# 6
# 1 2 3
# 1 3 2
# 2 1 3
# 2 3 1
# 3 1 2
# 3 2 1
def fac(n):
if n <= 2:
return n
else:
return n * fac(n-1)
def permutations(n):
a = range(1, n+1)
while True:
yield a[:]
k = l = None
for i in range(0, len(a) - 1):
if a[i] < a[i+1]:
k = i
if k == None:
break
for i in range(k + 1, len(a)):
if a[k] < a[i]:
l = i
a[k], a[l] = a[l], a[k]
a[k+1:] = reversed(a[k+1:])
if __name__ == "__main__":
small_dataset = 3
large_dataset = 7
n = large_dataset
print fac(n)
for p in permutations(n):
print ' '.join(map(str, p))