String and text manipulation - part 3

Algorithms and Data Structure

IFE, TUL, 2014

Marek Kociński & Andrzej Materka


Exercise 1 - Voting (based on Enthought tutorial)

You have the string below, which is a set of "yes/no" votes, where "y" or "Y" means yes and "n" or "N" means no. Determine the percentages of yes and no votes.

votes = "y y n N Y Y n n N y Y n Y"

Exercise 2 - Filter words (based on Enthought tutorial)

Print out only words that start with "o", ignoring case::

lyrics =   """My Bonnie lies over the ocean.
              My Bonnie lies over the sea.
              My Bonnie lies over the ocean.
              Oh bring back my Bonnie to me."""

Bonus points: print out words only once.

Exercise 3 - Sort words (based on Enthought tutorial)

Given a (partial) sentence from a speech, print out a list of the words in the sentence in alphabetical order. Also print out just the first two words and the last two words in the sorted list.

    speech = """Four score and seven years ago our fathers brought forth 
              on this continent a new nation, conceived in Liberty, and 
              dedicated to the proposition that all men are created equal."""
             

Exercise 4 - load/save data from/to file

Load and plot data from file data.txt. The file structure is as follows:

#time   #sin    #cos
    0   0.000   1.000
    1   0.063   0.998
    2   0.125   0.992
    3   0.187   0.982
    4   0.249   0.969
    5   0.309   0.951
    6   0.368   0.930
    ...   ...     ...
In [30]:
# save to file
import numpy as np

t = np.arange(100)
y1 = np.sin(t*np.pi/50)
y2 = np.cos(t*np.pi/50)

f = open('data.txt', 'w')
print >> f, '%s\t%s\t%s' %("#time", "#sin", "#cos")
for i in range(t.size):
    print >> f, "{0}\t{1:.3f}\t{2:.3f}".format(t[i],y1[i],y2[i])
f.close()
In [31]:
import matplotlib.pyplot as plt

t = []
s1 = []
c1 = []
# load from file
f = open('data.txt', 'r')
f.readline()
for line in f:
    l = line.split()
    t.append(l[0])
    s1.append(l[1])
    c1.append(l[2])
f.close()            

plt.plot(t,s1,t,c1)
plt.legend(['sin','cos'])
plt.title('Plots')
plt.ylabel('sin and cos')
plt.xlabel('time')
plt.show()

Exercise 5 - Dictionary

Create a data structure to deal with students at the University (or patients in a hospital). Use "dictionary" data structure.


Dictionaries store key/value pairs. Indexing a dictionary by a key returns the value associated with it. The key must be immutable.

In [33]:
# Create an empty dictionary using curly brackets 
my_dict = {}

# Each indexed assignment vreates a new key/value pair.
my_dict['first'] = 'Jan'
my_dict['second'] = 'Jakub'
my_dict['surname']= 'Nowak'
my_dict['born'] = 1990
my_dict['index_nr'] = 199210
In [34]:
my_dict
Out[34]:
{'born': 1990,
 'first': 'Jan',
 'index_nr': 199210,
 'second': 'Jakub',
 'surname': 'Nowak'}