Python programming exam

profilesvenkata
Assigment061.docx

SHIVAKIRAN RAO PAMULAPARTHI VENKATA

ID: 244705

Assignment - 6

Exercise 6.1

import matplotlib.pyplot as plt

import numpy as np

x = []

y = []

infile = open('write_cml_function.txt', 'r')

for line in infile:

coords = line.split()

x.append(float(coords[0]))

y.append(float(coords[1]))

infile.close()

x, y = np.array(x), np.array(y)

print 'Minimum x value = %f' % x.min()

print 'Maximum x value = %f' % x.max()

print 'Minimum y value = %f' % y.min()

print 'Maximum y value = %f' % y.max()

plt.plot(x, y, color='#053061', linewidth=1.5)

plt.xlabel('x')

plt.ylabel('y')

plt.show()

Console:

Exercise 6.2

Code :

import numpy as np

import matplotlib.pyplot as plt

import datetime as dt

def get_city_codes(citylist_filename):

infile = open(citylist_filename, 'r')

for i in range(260):

infile.readline() # skip everything before content

city_filenames = {}

while True:

line = infile.readline()

if not line: # exit loop at end of file

break

if line.find('mso-list') != -1: # check line contains country name

city = line.split('<b>')[1][:-7]

infile.readline() # skip a line

line = infile.readline() # read in next line

city_filename = line.split(

'>')[1][:line.split('>')[1].find('.txt') + 4]

city_filenames[city] = city_filename

infile.close()

return city_filenames

def load_city_data(city, city_filenames, subfolder='city_temp'):

filepath = subfolder + '/' + city_filenames[city]

# load data and create datetime object array to store dates

month, day, year, temperature = np.loadtxt(filepath, unpack=True)

temperature = np.loadtxt(filepath, usecols=(3,), dtype=float)

date = [dt.datetime(y, m, d) for y, m, d in

zip(year.astype(int), month.astype(int), day.astype(int))]

date = np.asarray(date)

# store in dictionary (filtering out entries with missing data)

valid = temperature != -99

city_data = {'name': city,

'date': date[valid],

'temperature': temperature[valid]}

return city_data

def plot_city_data(*city_data_dicts):

cities = []

for city_data in city_data_dicts:

cities.append(city_data['name'])

plt.plot_date(city_data['date'], city_data['temperature'], '.')

plt.ylabel('Temperature (C)')

plt.xlabel('Date')

plt.ylim([0, 110])

plt.legend(cities)

plt.show()

city_filenames = get_city_codes('city_temp/citylistWorld.htm')

Buenos_Aires_data = load_city_data('Buenos Aires', city_filenames)

London_data = load_city_data('London', city_filenames)

Reykjavik_data = load_city_data('Reykjavik', city_filenames)

Beirut_data = load_city_data('Beirut', city_filenames)

plot_city_data(Buenos_Aires_data, London_data, Reykjavik_data, Beirut_data)

Console:

Exercise 6.8.

Code :

def load_constants(constantsfile):

constants = {}

infile = open(constantsfile, 'r')

lines = infile.readlines()[2:]

for line in lines:

title = line[:27].strip()

value = float(line[27:].split()[0])

constants[title] = value

infile.close()

return constants

fundamental_constants = load_constants('constants.txt')

print '------------------------------------'

for constant, value in fundamental_constants.iteritems():

print '%-24s %g' % (constant, value)

print '------------------------------------'

Exercise 6.10

def read_densities_v1(filename):

infile = open(filename, 'r')

densities = {}

for line in infile:

words = line.split()

density = float(words[-1])

if len(words[:-1]) == 2:

substance = words[0] + ' ' + words[1]

else:

substance = words[0]

densities[substance] = density

infile.close()

return densities

def read_densities_v2(filename):

infile = open(filename, 'r')

densities = {}

for line in infile:

words = line.split()

density = float(words[-1])

substance = ' '.join(words[:-1])

densities[substance] = density

infile.close()

return densities

def read_densities_v3(filename):

infile = open(filename, 'r')

densities = {}

for line in infile:

words = line.split()

density = float(words[-1])

substance = line[:12].strip()

densities[substance] = density

infile.close()

return densities

f = 'densities.dat'

print read_densities_v1(f) == read_densities_v2(f) == read_densities_v3(f)

Exercise 6.12.

Code

infile = open('stars.dat', 'r')

data = {}

for line in infile.readlines()[1:]:

words = line.split()

name = ' '.join(words[:-3])

luminosity = float(words[-1])

data[name] = luminosity

print '='*31

print '%-20s %10s' % ('Star', 'Luminosity')

print '-'*31

for star, luminosity in data.iteritems():

print '%-20s %10.5f' % (star, luminosity)

print '='*31

Console :

===============================

Star Luminosity

-------------------------------

Wolf 359 0.00002

Sun 1.00000

Alpha Centauri C 0.00006

Alpha Centauri B 0.45000

Alpha Centauri A 1.56000

Luyten 726-8 A 0.00006

Sirius B 0.00300

Sirius A 23.60000

Luyten 726-8 B 0.00004

BD +36 degrees 2147 0.00600

Barnard's Star 0.00050

Ross 154 0.00050

===============================

Exercise 6.13

Code:

infile = open('stars.dat', 'r')

data = {}

for line in infile.readlines()[1:]:

words = line.split()

name = ' '.join(words[:-3])

if words[-3] == '-':

distance = '-'

apparent_brightness = '-'

else:

distance = float(words[-3])

apparent_brightness = float(words[-2])

luminosity = float(words[-1])

data[name] = {'distance': distance,

'apparent brightness': apparent_brightness,

'luminosity': luminosity}

print '='*68

print '%-20s %12s %18s %15s' % ('Star', 'Distance',

'App. brightness', 'Luminosity')

print '-'*68

for star in data:

if star == 'Sun':

print '%-20s %12s %18s %15.5f' % (star,

data[star]['distance'],

data[star]['apparent brightness'],

data[star]['luminosity'])

else:

print '%-20s %12f %18f %15.5f' % (star,

data[star]['distance'],

data[star]['apparent brightness'],

data[star]['luminosity'])

print '='*68

console :

====================================================================

Star Distance App. brightness Luminosity

--------------------------------------------------------------------

Wolf 359 7.700000 0.000001 0.00002

Sun - - 1.00000

Alpha Centauri C 4.200000 0.000010 0.00006

Alpha Centauri B 4.300000 0.077000 0.45000

Alpha Centauri A 4.300000 0.260000 1.56000

Luyten 726-8 A 8.400000 0.000003 0.00006

Sirius B 8.600000 0.001000 0.00300

Sirius A 8.600000 1.000000 23.60000

Luyten 726-8 B 8.400000 0.000002 0.00004

BD +36 degrees 2147 8.200000 0.000300 0.00600

Barnard's Star 6.000000 0.000040 0.00050

Ross 154 9.400000 0.000020 0.00050

====================================================================

Exercise 6.18

Code :

def read_file(filename):

infile = open(filename, 'r')

infile.readline() # read column headings

dates = []

prices = []

for line in infile:

columns = line.split(',')

date = columns[0]

date = date[:-3] # skip day of month

price = columns[-1]

dates.append(date)

prices.append(float(price))

infile.close()

dates.reverse()

prices.reverse()

return dates, prices

def load_files(filelist):

dates = {}

prices = {}

for filename in filelist:

name = filename[:-4] # read company name from 'name.csv' string

d, p = read_file(filename)

dates[name] = d

prices[name] = p

data = {'prices': prices, 'dates': dates}

return data

def normalise_prices(prices):

norm_prices = {}

for company in prices:

norm_price = prices[company][0]

norm_prices[company] = \

[p / norm_price for p in prices[company]]

return norm_prices

filelist = ['Apple.csv', 'Google.csv', 'Microsoft.csv',

'Nokia.csv', 'Sony.csv']

data = load_files(filelist)

data['norm prices'] = normalise_prices(data['prices'])

# Let the "x" values in the plot just be the indices

companies = []

for company in data['norm prices']:

plt.plot(data['norm prices'][company], linewidth=1.5)

companies.append(company)

plt.legend(companies, loc=2)

plt.ylabel('Stock price')

plt.xlabel('Time (months from Jan 1 2005)')

plt.title('Major corporation stock price variation - 2005-2014')

plt.show()

console:

Exercise 6.22

import numpy as np

import matplotlib.pyplot as plt

import datetime as dt

def get_city_codes(citylist_filename):

infile = open(citylist_filename, 'r')

for i in range(260):

infile.readline() # skip everything before content

city_filenames = {}

while True:

line = infile.readline()

if not line: # exit loop at end of file

break

if line.find('mso-list') != -1: # check line contains country name

city = line.split('<b>')[1][:-7]

infile.readline() # skip a line

line = infile.readline() # read in next line

city_filename = line.split(

'>')[1][:line.split('>')[1].find('.txt') + 4]

city_filenames[city] = city_filename

infile.close()

return city_filenames

def load_city_data(city, city_filenames, subfolder='city_temp'):

filepath = subfolder + '/' + city_filenames[city]

# load data and create datetime object array to store dates

month, day, year, temperature = np.loadtxt(filepath, unpack=True)

temperature = np.loadtxt(filepath, usecols=(3,), dtype=float)

date = [dt.datetime(y, m, d) for y, m, d in

zip(year.astype(int), month.astype(int), day.astype(int))]

date = np.asarray(date)

# store in dictionary (filtering out entries with missing data)

valid = temperature != -99

city_data = {'name': city,

'date': date[valid],

'temperature': temperature[valid]}

return city_data

def plot_city_data(*city_data_dicts):

cities = []

for city_data in city_data_dicts:

cities.append(city_data['name'])

plt.plot_date(city_data['date'], city_data['temperature'],

plt.ylabel('Temperature (C)')

plt.xlabel('Date')

plt.ylim([0, 110])

plt.legend(cities)

plt.show()

city_filenames = get_city_codes('city_temp/citylistWorld.htm')

Buenos_Aires_data = load_city_data('Buenos Aires', city_filenames)

London_data = load_city_data('London', city_filenames)

Reykjavik_data = load_city_data('Reykjavik', city_filenames)

Beirut_data = load_city_data('Beirut', city_filenames)

plot_city_data(Buenos_Aires_data, London_data, Reykjavik_data, Beirut_data)

Exercise 6.23

print ÔHello, World!Õ