Skip to content

Commit a6d780c

Browse files
committed
add generators, list and permutations libs.
1 parent 8522057 commit a6d780c

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

generators.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
def fib(n):
2+
"""
3+
Generator for Fibonacci serie
4+
5+
Each call to fib() returns the next value in the serie
6+
Example: for i in fib(5): print i
7+
@param n fib range upper bound
8+
"""
9+
a, b = 0, 1
10+
i = 0
11+
while i < n:
12+
yield b
13+
a, b = b, a+b
14+
i += 1
15+

list.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def find_max_sub(l):
2+
"""
3+
Find subset with higest sum
4+
5+
Example: [-2, 3, -4, 5, 1, -5] -> (3,4), 6
6+
@param l list
7+
@returns subset bounds and highest sum
8+
"""
9+
# max sum
10+
max = l[0]
11+
# current sum
12+
m = 0
13+
# max sum subset bounds
14+
bounds = (0, 0)
15+
# current subset start
16+
s = 0
17+
for i in range(len(l)):
18+
m += l[i]
19+
if m > max:
20+
max = m
21+
bounds = (s, i)
22+
elif m < 0:
23+
m = 0
24+
s = i+1
25+
return bounds, max

permutations.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def permutations(l):
2+
"""
3+
Generator for list permutations
4+
5+
Example: [1,2,3] = [1,2,3], [1,3,2], [2,1,3] ...
6+
7+
@param l list to generate permutations for
8+
@result yield each permutation
9+
"""
10+
print 'permutations: ',l
11+
if len(l) <= 1:
12+
yield l
13+
else:
14+
a = [l.pop(0)]
15+
for p in permutations(l):
16+
for i in range(len(p)+1):
17+
yield p[:i] + a + p[i:]
18+

0 commit comments

Comments
 (0)