Edit this page Backlinks This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== 1. Introduction to Python ====== Python3 is a multi-paradigm language, that combines the **imperative** style with the **functional** style. It also supports Object-Oriented programming, albeit in a limited way. Python3 offers a few programming constructs that: * make life real easy for the programmer, * yield efficient programs, * sum-up to a programming **style** called **pythonic** (a blend of imperative and functional features). This lab will introduce some of these constructs. ==== List traversal ==== 1.1. Write a function ''f(l)'' which determines the maximum of a list ''l'' of integers. <hidden The pythonic way> Traversing a list using a ''for'' is done as follows: <code python> for elem in collection: # do something </code> This idiom can be used for any collection not just lists, as you will discover during the lab. </hidden> 1.2. Modify the previous function to ''f(l,start,stop)'' and determine the maximum between positions ''start'' and ''stop''. <hidden The pythonic way> When we care about the indices of a list, we can use the function ''range(x,y)'' which returns **a list of integers** starting from ''x'' until ''y-1''. <code python> for i in range(0,len(collection)): # do something with collection[i] </code> </hidden> ==== Slicing lists ==== 1.3. Find the **longest** sequence of positive integers from a list. E.g. for the list ''[1,3,-1,2,0,1,5,4,-2,4,5,-3,0,1,2]'' the answer is ''[2,0,1,5,4]''. <hidden The pythonic way> Python supports various list slicing operations, as well as "overloaded" indexing: <code python> # the sublist from positions 0 to x of l: l[0:x] # the very same list: l[:x] # the last element of a list: l[:-1] # the last three elements of a list: l[:-3] # the slice from n-3 to n-1, where n is the number of elements from the list l[-3:-1] </code> </hidden> 1.4. Write a pythonic function to check if a list is palindrome. ===== Other datatypes ===== Inner functions List comprehensions, filters Stacks Dictionaries Pairs Classes and inheritance, instance-of toString Higher-order functions and lambdas Unpacking (for tuples, lists) <hidden The Pythonic way> This text will be hidden <code python> solution </code> </hidden> Python is an interpreted, dynamically typed language which is easy to use for scripting and prototyping applications. C and Java programmers quickly adjust to the Python syntax. Unlike C, in Python, lists are predefined and usually more used than arrays: <code python> # Comments begin with a '#' and end at the end of the line l = [] # comment l.append("1") l.append(0) l.append([]) print(l) </code> <code python> def func(l1, l2): l1.append(3) return l1 + l2 x = [1] y = [2] print(func(x,y)) print(x) </code> **Remarks** * although it is possible to add type annotations, in Python a function's signature only consists of the number of parameters and their names * objects are generally passed as reference (hence, when printing ''x'', we see the list ''[1,3]'') (for details see: [[https://docs.python.org/3/reference/datamodel.html | Python data model]]) * ''+'' denotes list concatenation **Exercise 1** Write a function which prints EACH repeating character from a string. (Hint: strings are lists of characters). ==== Useful data structures: dictionaries and sets ==== Dictionaries are another useful data structure. A dictionary is a ''<key> : <value>'' mapping. Unlike lists, keys may be of any type (integers, strings, or any other datatype). <code python> d = {} d["X"] = ["X"] if "X" in d: print("d[X] is defined in the dictionary") if not "Y" in d: print("d[Y] is not defined in the dictionary") </code> **Exercise 2** Write a function returns the number of repetitions of each character from a text. (Hint: use dictionaries to store the number of repetitions.) **Exercise 3** Write a function returns the number of unique characters from a list. Remark: * a simpler way to ensure uniqueness is to use sets. * a set may be created from a list: ''s = set([1,2,3,1])'' * and in turn, a list may be created from a set: ''l = list(s)'' Remark: * in Python we can use arbitrarily nested functions **Exercise 6** Write a function which searches for a list of patterns in a text. <code python> def find_patterns (pattern_list, text): # checks if pattern is found at position index in text def inner_search (pattern,index): </code> Remark: * Python supports functional-style programming to some extent. <code python> def plus1(x): return x + 1 print(map(plus1,[1,2,3])) print(map(lambda x:x+1, [1,2,3])) </code> **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 ==== We discuss a few basics on classes and inheritance starting from the following example: <code python> class Tree: def size(self): pass def contains(self, key): pass class Void(Tree): def __init__(self): pass def __str__(self): return "Nil" def size(self): return 0 def contains(self,key): return False </code> In the previous example, the class ''Tree'' acts as an interface. Python does not natively support interfaces, but class inheritance is supported. The instruction ''pass'' does nothing, and it helps us defer the method implementation. The definition: <code python> class Void(Tree) </code> tells us that class ''Void'' inherits ''Tree''. Note that this //contract// is not binding in Python. The program will be interpreted even if ''Void'' does not correctly implement the methods in ''Tree''. The function <code python> def __init__(self): </code> is the class constructor. We cannot explicitly define multiple constructors (but workarounds exist). Also note the mandatory presence of ''self'', which is the Python equivalent of ''this''. Each member class must mark as first argument ''self'', otherwise it is not a proper member of the class, and just a nested function. The function <code python> def __str__(self): </code> is the Python equivalent for ''toString()''. An object can be displayed using the function ''str'' **Exercise 9** Create the class ''Node'' which models non-empty trees. Implement methods ''size'' and ''contains''. ==== List of exercises ==== * Write a function which prints EACH repeating character from a string. (Hint: strings are lists of characters). * Write a function returns the number of repetitions of each character from a text. (Hint: use dictionaries to store the number of repetitions). * Write a function returns the number of unique characters from a list. Use Python sets. * Write a function which takes a pattern and a text and prints all indexes where an occurrence of pattern in text are found. Use Python list slicing. * Write a function which searches for a list of patterns in a text, by extending the stub below. Whenever possible, use ''map'' instead of ''for''. <code python> def find_patterns (pattern_list, text): # checks if pattern is found at position index in text def inner_search (pattern,index): </code> * Extend the class example shown previously to include class ''Node'' which models non-empty trees. Implement methods ''size'' and ''contains''.