1
+ #!/usr/bin/env python
2
+
3
+ # Sebastian Raschka 2014
4
+ # Functions to calculate factorial, combinations, and permutations
5
+ # bundled in an simple command line interface.
6
+
7
+ def factorial (n ):
8
+ if n == 0 :
9
+ return 1
10
+ else :
11
+ return n * factorial (n - 1 )
12
+
13
+ def combinations (n , r ):
14
+ numerator = factorial (n )
15
+ denominator = factorial (r ) * factorial (n - r )
16
+ return int (numerator / denominator )
17
+
18
+ def permutations (n , r ):
19
+ numerator = factorial (n )
20
+ denominator = factorial (n - r )
21
+ return int (numerator / denominator )
22
+
23
+ assert (factorial (3 ) == 6 )
24
+ assert (combinations (20 , 8 ) == 125970 )
25
+ assert (permutations (30 , 3 ) == 24360 )
26
+
27
+
28
+
29
+
30
+ if __name__ == '__main__' :
31
+
32
+ import argparse
33
+ parser = argparse .ArgumentParser (
34
+ description = 'Script to calculate the number of combinations or permutations ("n choose r")' ,
35
+ formatter_class = argparse .RawTextHelpFormatter ,
36
+
37
+ prog = 'Combinations' ,
38
+ epilog = 'Example: ./combinations.py -c 20 3'
39
+ )
40
+
41
+ parser .add_argument ('-c' , '--combinations' , type = int , metavar = 'NUMBER' , nargs = 2 ,
42
+ help = 'Combinations: Number of ways to combine n items with sequence length r where the item order does not matter.' )
43
+
44
+ parser .add_argument ('-p' , '--permutations' , type = int , metavar = 'NUMBER' , nargs = 2 ,
45
+ help = 'Permutations: Number of ways to combine n items with sequence length r where the item order does not matter.' )
46
+
47
+ parser .add_argument ('-f' , '--factorial' , type = int , metavar = 'NUMBER' , help = 'n! e.g., 5! = 5*4*3*2*1 = 120.' )
48
+
49
+ parser .add_argument ('--version' , action = 'version' , version = '%(prog)s 1.0' )
50
+
51
+ args = parser .parse_args ()
52
+
53
+ if not any ((args .combinations , args .permutations , args .factorial )):
54
+ parser .print_help ()
55
+ quit ()
56
+
57
+ if args .factorial :
58
+ print (factorial (args .factorial ))
59
+
60
+ if args .combinations :
61
+ print (combinations (args .combinations [0 ], args .combinations [1 ]))
62
+
63
+ if args .permutations :
64
+ print (permutations (args .permutations [0 ], args .permutations [1 ]))
65
+
66
+ if args .factorial :
67
+ print (factorial (args .factorial ))
68
+
69
+
70
+
71
+
0 commit comments