Votes

The listeners of a radio station vote on the three songs they have most liked. Votes are stored in a file where each line contains the name of a maximum of three songs, separated by a comma and a single whitespace. An example of this kind of file is file votes_radio.txt with the following content:

Cargol treu banya, El gripau blau, En Pinxo i en Panxo
La lluna la pruna, En Pinxo i en Panxo, La pastoreta
Cargol treu banya
La lluna la pruna, El Ball de Sant Ferriol
Plou i fa sol, La lluna la pruna
La lluna la pruna, Plou i fa sol, En Jan petit

Note that there are listeners who have only voted one or two songs while others have voted three songs.

We want to know how many votes got each song. Write the function votes() that takes two file names (strings). The first one corresponds to a file as described above and the second one is created by this function. This second file will contain at each line the following data corresponding to a song, separated by a star ('*'): number of votes got by this song and name.

The file that will be created with the example above will have the following content:

2*Cargol treu banya
1*El gripau blau
2*En Pinxo i en Panxo
4*La lluna la pruna
1*La pastoreta
1*El Ball de Sant Ferriol
2*Plou i fa sol
1*En Jan petit

To solve this exercise we suggest to built first a dictionary from the first file where the key is the title of a song and the value its number of votes, and then built the second file using this dictionary.

Save this function into file votes.py. The function must pass the following doctest:

>>> lvotes = ['Cargol treu banya, El gripau blau, En Pinxo i en Panxo', 
...          'La lluna la pruna, En Pinxo i en Panxo, La pastoreta',
...          'Cargol treu banya',
...          'La lluna la pruna, El Ball de Sant Ferriol',
...          'Plou i fa sol, La lluna la pruna',
...          'La lluna la pruna, Plou i fa sol, En Jan petit']
>>> with open('votes_radio.txt', 'w') as f:
...    for e in lvotes:
...        a = f.write (e+'\n')
>>> votes('votes_radio.txt', 'results.txt')
>>> with open('results.txt', 'r') as f:
...    lv = []
...    for line in f:
...         line = line.strip().split('*')
...         lv.append((int(line[0]), line[1]))
>>> lv.sort()
>>> lv
[(1, 'El Ball de Sant Ferriol'), (1, 'El gripau blau'), (1, 'En Jan petit'), (1, 'La pastoreta'), (2, 'Cargol treu banya'), (2, 'En Pinxo i en Panxo'), (2, 'Plou i fa sol'), (4, 'La lluna la pruna')]

Note

These tests can be found in file votes.txt

Solution

A solution of this function is provided in file votes.py