Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit3b799c0

Browse files
committed
more itertools
1 parentce58ba8 commit3b799c0

File tree

7 files changed

+117
-83
lines changed

7 files changed

+117
-83
lines changed

‎python_algorithms/.DS_Store‎

0 Bytes
Binary file not shown.

‎python_algorithms/collections/arrays/array.py‎renamed to ‎python_algorithms/collections/arrays/arrays.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
# One extremely notable aspect of NumPy is the manner in which it extends
1919
# Python’s list indexing functionality—especially with multidimensional arrays.
20-
# To illustrate, make a simple two-dimensional array and try some experiments:
20+
# To illustrate, make a simple two-dimensional array and try some experiments:\
2121
a=np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
2222
print(a)
2323
#=> array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]])
@@ -49,8 +49,8 @@
4949
#=> array([[ 1, 2, 3, 4],
5050

5151
# python array
52-
#import array as arr
53-
#a = arr.array("I",[1,2,3])
52+
importarrayasarr
53+
a=arr.array("I",[1,2,3])
5454

5555
# Type codeC TypePython TypeMinimum size in bytes
5656
# 'b'signed charint1

‎python_algorithms/collections/collections.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
# ChainMap
99
# deque
1010

11-
1211
# sequence types:
1312
# tuple, list, string, range
1413

‎python_algorithms/collections/functions/closure.py‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,31 @@
22
# when need to monkey patch a function
33
# dynamically build behavior by 'stacking functions'
44

5-
# For creating generators
6-
# yield is both exit and entry point
7-
defstep(start=0,step=1):
5+
#### For creating generators
6+
7+
defstep(start=0,step=1,end=50):
88
_start=start
9-
whileTrue:
10-
yield_start
11-
_start+=step
9+
while_start<end:# if infinite loop, list(stepper) will exhaust memory
10+
yield_start# yield is both exit and entry point
11+
_start+=step# this gets called after every entry
1212

1313
stepper=step(10,2)
1414

15-
print(stepper.next())#=> 10
16-
print(stepper.next())#=> 12
17-
print(stepper.next())#=> 14
18-
15+
print(next(stepper))#=> 10
16+
print(next(stepper))#=> 12
17+
print(next(stepper))#=> 14
1918

19+
# Generator Expression
20+
stepper= (x*5forxinrange(0,10))
21+
print(list(stepper))
22+
#=> (0,5,10,15,...)
2023

2124

2225
#### As Function Factory
2326
defdivide_numbers(x,y):
2427
returnx/y
2528
# divide_numbers(2, 1) #=> 2
2629

27-
# closure
2830
defdivide_closure(x):
2931
defwrapped(y):# wrap closes over y
3032
returnx/y

‎python_algorithms/collections/lists/list.py‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
frompprintimportpprint
2-
importitertools
32

43
data= ['OCN',50,91.1, (2012,12,21) ]
54
name,shares,price,date=data
@@ -38,11 +37,3 @@
3837

3938
list.reverse(list_num)
4039
print(list_num)
41-
42-
# flattening
43-
a_list= [[1,2], [3,4], [5,6]]
44-
print(list(itertools.chain.from_iterable(a_list)))
45-
# Output: [1, 2, 3, 4, 5, 6]
46-
# or
47-
print(list(itertools.chain(*a_list)))
48-
# Output: [1, 2, 3, 4, 5, 6]
Lines changed: 2 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
# Defined using generator functions
12
# Examples of iterators: range(), reversed()
2-
# defined using generator functions
33

44
classNode:
55
def__init__(self,value):
@@ -15,7 +15,6 @@ def add_child(self, node):
1515
def__iter__(self):
1616
returniter(self._children)
1717

18-
# Example
1918
if__name__=='__main__':
2019
root=Node(0)
2120
child1=Node(1)
@@ -25,47 +24,7 @@ def __iter__(self):
2524
forchinroot:
2625
print(ch)# Outputs Node(1), Node(2)
2726

28-
defcountdown(n):
29-
print('Starting to count from',n)
30-
whilen>0:
31-
yieldn
32-
n-=1
33-
print('Done!')
34-
35-
# Create the generator, notice no output appears
36-
c=countdown(3)
37-
38-
print(next(c))
39-
print(next(c))
40-
print(next(c))
41-
print(next(c))# for loop takes care of except: StopIteration
42-
43-
44-
## SLICING AND DICING
45-
# take slice of an iterator
46-
importitertools
47-
forxinitertools.islice(c,10,20):
48-
print(x)
49-
50-
# Drop comments only at beginning of file, keep rest
51-
fromitertoolsimportdropwhile
52-
withopen('/etc/passwd')asf:
53-
forlineindropwhile(lambdaline:line.startswith('#'),f):
54-
print(line,end='')
55-
56-
# however, if knowing the exact amount to drop
57-
fromitertoolsimportislice
58-
items= ['a','b','c',1,4,10,15]
59-
forxinislice(items,3,None):
60-
print(x)
61-
62-
# finally, this will discard all comment lines
63-
withopen('/etc/passwd')asf:
64-
lines= (lineforlineinfifnotline.startswith('#'))
65-
forlineinlines:
66-
print(line,end='')
67-
68-
## ENUMERATION
27+
## Iteration
6928
my_list= ['a','b','c']
7029
foridx,valinenumerate(my_list,1):
7130
print(idx,val)
@@ -78,19 +37,3 @@ def countdown(n):
7837
count=int(fields[1])
7938
exceptValueErrorase:
8039
print('Line {}: Parse error: {}'.format(lineno,e))
81-
82-
# iterate over multiple sequences simultaneously
83-
# length of iteration is length of shortest input
84-
# replace with itertools.zip_longest() to avoid this
85-
xpts= [1,5,4,2,10,7]
86-
ypts= [101,78,37,15,62,99]
87-
forx,yinzip(xpts,ypts):
88-
print(x,y)
89-
90-
# iterating multiple containers efficiently
91-
# Inefficent
92-
forxina+b:
93-
print(x)
94-
# Better
95-
forxinchain(a,b):
96-
print(x)
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
fromitertoolsimportchain
2+
fromitertoolsimportcombinations
3+
fromitertoolsimportpermutations
4+
5+
6+
fromitertoolsimportgroupby
7+
mylist='aaaaabbbbbccdd'#sorted
8+
# group returns a generator
9+
print(list(groupby(mylist)))
10+
11+
# to extract from the generator groups
12+
print({k:list(v)fork,vingroupby(mylist)})
13+
14+
15+
mylist= [
16+
{'i':1,'name':'ray'},
17+
{'i':1,'name':'jeremy'},
18+
{'i':3,'name':'grant'},
19+
]
20+
print({k:list(v)fork,vingroupby(mylist,
21+
key=lambdax:x['i'])})
22+
23+
24+
## SLICING AND DICING
25+
# take slice of an iterator
26+
importitertools
27+
forxinitertools.islice(range(1,20),1,2):
28+
print(x)
29+
30+
fromitertoolsimportcycle
31+
# like a circulary linked list
32+
# if list large, memory intensive
33+
orbit=cycle('12345678')
34+
print([next(orbit)foriinrange(0,10)])
35+
36+
## Chain
37+
a= [1,2,3]
38+
b=range(9,4)
39+
print(list(chain(a,b)))
40+
41+
# flattening a matrix
42+
a_list= [[1,2], [3,4], [5,6]]
43+
print(list(chain.from_iterable(a_list)))
44+
# Output: [1, 2, 3, 4, 5, 6]
45+
# or
46+
print(list(chain(*a_list)))
47+
# Output: [1, 2, 3, 4, 5, 6]
48+
49+
## compress
50+
fromitertoolsimportcompress
51+
mylist='abcdef'
52+
myselectors= [1,0,1,1,0,1]
53+
print(list(compress(mylist,myselectors)))
54+
#=> ['a', 'c', 'd', 'f']
55+
56+
print([vforv,sinzip(mylist,myselectors)ifs])
57+
#=> ['a', 'c', 'd', 'f']
58+
59+
# count
60+
fromitertoolsimportcount
61+
# do not call len or list on this
62+
counter=count(1,5)# like stepper in closures.py
63+
forcin'abc':
64+
print(''.join(c))
65+
66+
67+
# islice knowing the exact amount to drop
68+
fromitertoolsimportislice
69+
items= ['a','b','c',1,4,10,15]
70+
forxinislice(items,3,None):
71+
print(x)
72+
73+
# iterate over multiple sequences simultaneously
74+
# length of iteration is length of shortest input
75+
# replace with itertools.zip_longest() to avoid this
76+
xpts= [1,5,4,2,10,7]
77+
ypts= [101,78,37,15,62,99]
78+
forx,yinzip(xpts,ypts):
79+
print(x,y)
80+
81+
# iterating multiple containers efficiently
82+
# Inefficent
83+
forxina+b:
84+
print(x)
85+
# Better
86+
forxinchain(a,b):
87+
print(x)
88+
89+
# Drop comments only at beginning of file, keep rest
90+
# from itertools import dropwhile
91+
# with open('/etc/passwd') as f:
92+
# for line in dropwhile(lambda line: line.startswith('#'), f):
93+
# print(line)
94+
95+
# finally, this will discard all comment lines
96+
# with open('/etc/passwd') as f:
97+
# lines = (line for line in f if not line.startswith('#'))
98+
# for line in lines:
99+
# print(line)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp