Skip to content

Commit 1bc30cd

Browse files
Add files via upload
1 parent eb55831 commit 1bc30cd

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

partial_function.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Explaining partial function and how to use it
2+
# Importing partial from functools
3+
from functools import partial
4+
5+
# Assigning to x integer number in binary notation
6+
x = int('1101', base=2)
7+
print(x) # Showing result in decimal notation
8+
9+
# Creating function int_2 with partial
10+
int_2 = partial(int, base=2)
11+
x = int_2('1101')
12+
print(x)
13+
14+
15+
# Another examples how to sort lists easier with partial
16+
x = [
17+
('Guido', 'van', 'Rossum'),
18+
('Haskell', 'Curry'),
19+
('John', 'Backus')
20+
]
21+
22+
y = ['abc', 'cba', 'abb']
23+
24+
import operator as op
25+
26+
# Creating function to sort lists by last element
27+
sort_by_last = partial(list.sort, key=op.itemgetter(-1))
28+
29+
print(x) # Showing current list
30+
sort_by_last(x)
31+
print(x) # Showing sorted list
32+
33+
sort_by_last(y)
34+
print(y)

0 commit comments

Comments
 (0)