Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
lfa:lab01-python-intro [2021/09/08 16:14] pdmatei |
lfa:lab01-python-intro [2021/10/07 11:32] (current) ioana.georgescu [List comprehensions] |
||
---|---|---|---|
Line 45: | Line 45: | ||
l[:x] | l[:x] | ||
# the last element of a list: | # the last element of a list: | ||
- | l[:-1] | + | l[-1] |
# the last three elements of a list: | # the last three elements of a list: | ||
- | l[:-3] | + | l[-3:] |
# the slice from n-3 to n-1, where n is the number of elements from the list | # the slice from n-3 to n-1, where n is the number of elements from the list | ||
l[-3:-1] | l[-3:-1] | ||
Line 140: | Line 140: | ||
from functools import reduce | from functools import reduce | ||
+ | # adds 1 to each element of a list | ||
def allplus1(l): | def allplus1(l): | ||
return map(lambda x:x+1,l) | return map(lambda x:x+1,l) | ||
+ | # computes the sum of elements of a list | ||
def sum_l (l): | def sum_l (l): | ||
# inner functions are very useful for defining local, reusable functionality | # inner functions are very useful for defining local, reusable functionality | ||
Line 155: | Line 157: | ||
==== List comprehensions ==== | ==== List comprehensions ==== | ||
- | **Exercise 1.8.** Write a function which takes a list of records //first name, last name, CNP// (encoded as tuples), and returns a list of **the last names** and **ages** of all females which are younger than the average of the entire list. E.g. ''[ ("Mary", "Smith", "2030602123456"), ("Anne", "Doe", "2121092123456"), ("Matei", "Dan", "1121202123456"), ("Maggie", "Byrne", "2121078123456")]'' yields ''[("Smith",19), ("Doe",29)]''. Maggie was born in '78, whereas Mary, Anne and Matei were born in '94, '92 and 2002, respectively. | + | List comprehensions are widely used programming tools in Python. Usage examples: |
- | <hidden The pythonic way> | ||
<code python> | <code python> | ||
- | from functools import reduce | + | # adding 1 to each element of a list |
+ | l1 = [x+1 for x in [1,2,3]] | ||
+ | # [2,3,4] | ||
- | def getYouth(l): | + | # packing elements into pairs |
- | def age(entry): | + | l2 = [(x,x+1) for x in [1,2,3]] |
- | if int(entry[5:8]) <= 21: | + | # [(1,2), (2,3), (3,4)] |
- | return 2021 - int("20"+entry[5:8]) | + | |
- | else | + | |
- | return 2021 - int("19"+entry[5:8]) | + | |
- | + | ||
- | avg = reduce(lambda a,b:a+b, map(age,l)) / len(l) | + | |
- | [(ln,age(cnp)) for (fn,ln,cnp) in l if cnp[0]=='2'] | + | |
- | </code> | + | |
- | </hidden> | + | |
+ | # unpacking pairs in the for notation | ||
+ | l3 = [x+y for (x,y) in [(1,2), (2,3), (3,4)]] | ||
+ | # [3,5,7] | ||
- | Inner functions | + | # combined list comprehensions |
- | List comprehensions, filters | + | l4 = [(x,y) for x in [1,2,3] for y in [4,5,6]] |
- | Classes and inheritance, instance-of | + | # [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)] |
- | toString | + | |
- | Higher-order functions and lambdas | + | |
- | Unpacking (for tuples, lists) | + | |
+ | # filters | ||
+ | l5 = [x for x in [1,2,3,4] if x>2] | ||
+ | # [3,4] | ||
+ | </code> | ||
- | <hidden The Pythonic way> This text will be hidden <code python> solution </code> </hidden> | + | **Exercise 1.8.** Write a function which takes a list of records //first name, last name, CNP// (encoded as tuples), and returns a list of **the last names** and **ages** of all females which are younger than the average of the entire list. E.g. ''[ ("Mary", "Smith", "2030602123456"), ("Anne", "Doe", "2121092123456"), ("Matei", "Dan", "1121202123456"), ("Maggie", "Byrne", "2121078123456")]'' yields ''[("Smith",19), ("Doe",29)]''. Maggie was born in '78, whereas Mary, Anne and Matei were born in '94, '92 and 2002, respectively. |
- | + | <hidden The pythonic way> | |
- | + | ||
- | **Exercise 6** Write a function which searches for a list of patterns in a text. | + | |
<code python> | <code python> | ||
- | def find_patterns (pattern_list, text): | + | from functools import reduce |
- | # checks if pattern is found at position index in text | + | |
- | def inner_search (pattern,index): | + | |
- | </code> | + | |
- | Remark: | + | def getYouth(l): |
- | * Python supports functional-style programming to some extent. | + | # this function computes the age of a given CNP |
- | <code python> | + | def age(cnp): |
- | def plus1(x): | + | # conversion to integer of the two-character year code |
- | return x + 1 | + | if int(cnp[5:8]) <= 21: |
+ | return 2021 - int("20"+cnp[5:7]) | ||
+ | else: | ||
+ | return 2021 - int("19"+cnp[5:7]) | ||
+ | |||
+ | # computing the average ages (a map could have also been used) | ||
+ | avg = reduce(lambda a,b:a+b, [age(x[-1]) for x in l]) / len(l) | ||
| | ||
- | print(map(plus1,[1,2,3])) | + | # we return the last name and the age of the filtered list l |
- | print(map(lambda x:x+1, [1,2,3])) | + | return [(ln,age(cnp)) for (fn,ln,cnp) in l if cnp[0]=='2' and age(cnp) <= avg] |
</code> | </code> | ||
+ | </hidden> | ||
- | **Exercise 8** Modify the previous implementation and instead of ''for'', use ''map'' (cast the return of ''map'' to ''list'': ''list(map(...))'') | ||
- | However, it is more common in Python to employ //list comprehensions// instead of ''map'': | ||
- | <code python> | ||
- | def plus1(x): | ||
- | return x + 1 | ||
- | | ||
- | print([plus1(x) for x in [1,2,3]]) | ||
- | print([(x + 1) for x in [1,2,3]])) | ||
- | </code> | ||
- | List comprehensions also support the functionality of ''filter'': | ||
- | <code python> | ||
- | print([(x+1) for x in [1,2,3,4,5,6] if (x % 2 == 0)]) | ||
- | </code> | ||
- | **Exercise 9** Modify the previous implementation and instead of ''for'', use list comprehensions. | + | |
+ | |||
+ | |||
+ | /* | ||
==== Classes and inheritance ==== | ==== Classes and inheritance ==== | ||
Line 288: | Line 279: | ||
* Extend the class example shown previously to include class ''Node'' which models non-empty trees. Implement methods ''size'' and ''contains''. | * Extend the class example shown previously to include class ''Node'' which models non-empty trees. Implement methods ''size'' and ''contains''. | ||
+ | |||
+ | */ | ||
+ | |||
+ | ===== Practice ===== | ||
+ | |||
+ | A labelled graph is encoded as a file where: | ||
+ | * **the first line** consists of the number of nodes | ||
+ | * **each subsequent line** is an edge ''<from> <label> <to>'' | ||
+ | Example: | ||
+ | <code> | ||
+ | 5 | ||
+ | 0 X 1 | ||
+ | 1 O 2 | ||
+ | 1 X 3 | ||
+ | 1 O 4 | ||
+ | 4 X 1 | ||
+ | 3 O 2 | ||
+ | </code> | ||
+ | |||
+ | * Suppose we encode streets as labelled graphs, where each label 'X' or 'O' denotes if a street is closed or open. | ||
+ | * Compute the set of accessible nodes from a given **source**, via open streets. | ||
+ | * (Hint1: google //Python read lines// to see how to read from a file; also, google ''split'' in Python) | ||
+ | * (Hint2: you will need a dictionary to store, for each node and label l, the list of its l-successors) | ||
+ | |||
+ | |||
+ | ===== Haskell practice ===== | ||
+ | |||
+ | Solve the same exercise, only build your own input as a string, instead of a file. |