This is an old revision of the document!


Introduction to Python

Python basics

The Pythonic way

The Pythonic way

This text will be hidden

 solution 

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:

# Comments begin with a '#' and end at the end of the line
l = []  # comment
l.append("1")
l.append(0)
l.append([])
 
print(l)

Remarks

  • Although Python is strongly-typed (the interpreter keeps track and verifies the type of objects), lists may have different 'types' of elements.
  • There exist two different major versions of Python: Python2 and Python3. Although similar, there are some incompatible differences between them. We will use Python3, so take care when researching documentation.
for i in range(0,len(l)):
    print(l[i])
 
print(range(0,len(l)))
 
for elem in l:
    print(elem)

Remarks

  • List traversal may be achieved using indexing. Indexes are integers taken from a range. range(0,len(l)) is a list in itself.
  • Lists (and other data structures) can be iterated using in

Syntax

  • unlike C or Java where we often use {…} for scoping, in Python we use indentation levels (either a tab or 4 spaces)
  • control instructions such as for, while, if do not require (…) for conditions but they must end with :
def func(l1, l2):
    l1.append(3)
    return l1 + l2
 
x = [1]
y = [2]
print(func(x,y))
print(x)

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: 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).

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")

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)

Exercise 4 Write a function which takes a pattern and a text and prints all indexes where an occurrence of pattern in text are found.

Remark:

  • lists can be sliced in Python using the following syntax: l[start_index:end_index] Test it to see how slicing is performed.

Exercise 5 Modify the previous implementation to use slicing.

Remark:

  • in Python we can use arbitrarily nested functions

Exercise 6 Write a function which searches for a list of patterns in a text.

def find_patterns (pattern_list, text):
    # checks if pattern is found at position index in text
    def inner_search (pattern,index):

Remark:

  • Python supports functional-style programming to some extent.
def plus1(x):
    return x + 1
 
print(map(plus1,[1,2,3]))
print(map(lambda x:x+1, [1,2,3]))

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:

def plus1(x):
    return x + 1
 
print([plus1(x) for x in [1,2,3]])
print([(x + 1) for x in [1,2,3]]))

List comprehensions also support the functionality of filter:

print([(x+1) for x in [1,2,3,4,5,6] if (x % 2 == 0)])

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:

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

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:

class Void(Tree)

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

def __init__(self):

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

def __str__(self):

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.
def find_patterns (pattern_list, text):
    # checks if pattern is found at position index in text
    def inner_search (pattern,index):
  • Extend the class example shown previously to include class Node which models non-empty trees. Implement methods size and contains.