Table of Contents

Introduction to Python

Python basics

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:

l = []
l.append("1")
l.append(0)
l.append([])
 
print(l)

Remarks

for i in range(0, len(l)):
	print(l[i])
 
print(list(range(0, len(l))))
 
for elem in l:
	print(elem)

Remarks

Syntax

def func(l1, l2):
	l1.append(3)
	return l1 + l2
x = [1]
y = [2]
print(func(x, y))
print(x)

Remarks

Exercise 1 Write a function which determines the maximum number from a list.

Exercise 2 Write a function which prints EACH repeating character from a string. (Hint: strings are lists of characters).

Useful data structures: dictionaries and tuples

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 3 Write a function which returns the number of repetitions of each character from a text. (Hint: use dictionaries to store the number of repetitions.)

Remarks

stud_info = ("Mihai", "mihai@upb.ro", ["AA", "PA", "SD", "Programare"])
str = stud_info[0] + "'s email is " + stud_info[1]
print(str)

Exercise 4 Write a function which takes a list of tuples containing student info and returns only those corresponding to students which have attended at least 3 lectures.

Exercise 5 Write a function which returns the number of unique characters from a list.

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

Remark:

Exercise 7 Modify the previous implementation to use slicing.

Remark:

Exercise 8 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):

For example, find_patterns([“ab”, “cd”], “abcdabcd”) should print out “0,2,4,6”.

Remark:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Exercise 9 Write a function which returns the elements from the principal diagonal of a matrix, as a list. Example: diag(matrix) = [1, 5, 9].

Exercise 10 Write a function which adds two matrices.

Exercise 11 Write a function which implements matrix transposition.

Exercise 12 Write a function which multiplies two matrices.