File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ #!/bin/python
2+
3+ """
4+ Write a function fib() that takes an integer nn and returns the nnth Fibonacci number.
5+ """
6+
7+ # this is O(2^n)
8+ def fib (n ):
9+ if n in [1 , 0 ]:
10+ return n
11+ return fib (n - 1 ) + fib (n - 2 )
12+
13+
14+ print fib (10 )
15+
16+
17+ # this is O(n)
18+ def fib (n ):
19+ if n < 0 :
20+ raise ValueError ('Index was negative. No such thing as a '
21+ 'negative index in a series.' )
22+ elif n in [0 , 1 ]:
23+ return n
24+
25+ prev_prev = 0 # 0th fibonacci
26+ prev = 1 # 1st fibonacci
27+
28+ for _ in range (n - 1 ):
29+ current = prev + prev_prev
30+ prev_prev = prev
31+ prev = current
32+
33+ return current
34+
35+
36+ print fib (10 )
Original file line number Diff line number Diff line change 1+ #!/bin/python
2+
3+ """
4+ Write a recursive function for generating all permutations of an input string. Return them as a set.
5+ """
6+
7+ def get_permutations (string ):
8+
9+ if len (string ) < 2 :
10+ return set ([string ])
11+
12+ all_chars_except_last = string [:- 1 ]
13+ last_char = string [- 1 ]
14+
15+ permutations_of_all_chars_except_last = get_permutations (all_chars_except_last )
16+
17+ permutations = set ()
18+ for permutation_of_all_chars_except_last in permutations_of_all_chars_except_last :
19+ for position in range (len (all_chars_except_last ) + 1 ):
20+ permutation = (
21+ permutation_of_all_chars_except_last [:position ]
22+ + last_char
23+ + permutation_of_all_chars_except_last [position :]
24+ )
25+ permutations .add (permutation )
26+
27+
28+ return permutations
29+
30+
31+ str = "abcd"
32+ print get_permutations (str )
You can’t perform that action at this time.
0 commit comments