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_word
that given a string returns its ciao. For example,
ciao_word("Hello") = "ehllo"
Implement the function
add_ciao_dict
that takes as arguments a dictionaryciao_dict
and a stringword
. The dictionaryciao_dict
is assumed to have ciao strings as keys and sets of strings as values: it maps a ciao stringstr
into a set of strings all havingstr
as their ciao. The functionadd_ciao_dict
must add stringword
to theciao_dict
dictionary.Note: You have to correctly handle the case when the ciao of
word
does not exist as key inciao_dict
.Question: What is the relationship among the strings having the same ciao?
Write the function
create_dict
that takes as argument the path of a text filef
containing a list of words (you can assume that each line contains a single word). The function returns a dictionary mapping a ciao stringstr
to the set of words off
havingstr
as 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_anagrams
that takes as arguments a dictionarydict
computed throughcreate_dict
and a stringline
representing a line of text (i.e. a sequence of words separated by spaces). This function returns a text line where each wordw1
ofline
is replaced by a different wordw2
having the same ciao ofw1
if this ciao exists indict
; otherwise,w1
is 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_gen
that returns the Fibonacci sequence.
- Implement a higher-order function (decorator)
block_ten_dec
that given a generatorg1
as argument returns a new generatorg2
. The generatorg2
returns the same elements ofg1
but in blocks of10
elements collected in a list.
- Decorate generator
fib_gen
withblock_ten_dec
. Use the just defined generator to print the first100
fibonacci numbers, 10 per line.
- Following the schema of
block_ten_dec
implement a decoratorblock_dec
that does the same but it is parametric on the size of the block. Decoratefib_gen
withblock_dec
to get blocks of 5 numbers, and print the first100
fibonacci numbers, 5 per line.