Python
Instructions
The following exercises require you to use functions, types and classes from the Python standard library.
Exercise 1
Given a string str, we define its ciao (characters in alphabetical
order) as the string having the same length of str and containing all
the characters of str in lower case and alphabetical order. A ciao
string is a string that is equal to its ciao.
- Write a function
ciao_wordthat given a string returns its ciao. For example,
ciao_word("Hello") = "ehllo"
Implement the function
add_ciao_dictthat takes as arguments a dictionaryciao_dictand a stringword. The dictionaryciao_dictis assumed to have ciao strings as keys and sets of strings as values: it maps a ciao stringstrinto a set of strings all havingstras their ciao. The functionadd_ciao_dictmust add stringwordto theciao_dictdictionary.Note: You have to correctly handle the case when the ciao of
worddoes not exist as key inciao_dict. Note that obviously all strings having same ciao are anagrams of each other.Write the function
create_dictthat takes as argument the path of a text filefcontaining a list of words (you can assume that each line contains a single word). The function returns a dictionary mapping a ciao stringstrto the set of words offhavingstras ciao.Note: You may use file anagram.txt to test your function. You have to correctly handle white spaces characters like new lines and tabs. Refer to the documentation for information about reading and writing files.
- Finally, write the function
replace_anagramsthat takes as arguments a dictionarydictcomputed throughcreate_dictand a stringlinerepresenting a line of text (i.e. a sequence of words separated by spaces). This function returns a text line where each wordw1oflineis replaced by a different wordw2having the same ciao ofw1if this ciao exists indict; otherwise,w1is left unchanged.
Goals: Fun with Python and warming up!
Expected output: Properly commented Python scripts along with the required implementations.
Exercise 2
This exercise consists in writing a decorator in Python. For a very good introduction to decorators, read the Primer on Python Decorators.
- Write a generator
fib_genthat returns the Fibonacci sequence.
- Implement a higher-order function (decorator)
block_ten_decthat given a generatorg1as argument returns a new generatorg2. The generatorg2returns the same elements ofg1but in blocks of10elements collected in a list.
- Decorate generator
fib_genwithblock_ten_dec. Use the just defined generator to print the first100fibonacci numbers, 10 per line.
- Following the schema of
block_ten_decimplement a decoratorblock_decthat does the same but it is parametric on the size of the block. Decoratefib_genwithblock_decto get blocks of 5 numbers, and print the first100fibonacci numbers, 5 per line.
Expected output: Properly commented Python scripts along with the required implementations.