07.01
def check_prime(x):
is_prime=True
for j in range(2,x):
if (x%j==0):
is_prime=False
break
return is_prime
check_prime(43)
07.02
# here the multiplication is done explicitly
#
# note for x<0 it also returns 1
#
def factorial_1(x):
ans=1
for i in range(1,x+1): #multiply by all numbers up to x
ans*=i
return ans
# using recursive function calls
# factorial_2 stops once the returned value is 1
def factorial_2(x):
if x<=1:
return 1
else:
return x*factorial_2(x-1)
07.03
def mean(x):
return sum(x)/float(len(x))
08.01
# open file
f = open('data/data.txt', 'r')
# read and ignore header lines
header1 = f.readline()
header2 = f.readline()
header3 = f.readline()
# loop over the lines in the iterable f
d = {}
for line in f:
table = line.strip().split()
name=table[2]
d[name] = float(table[3]) # all individual objects
f.close()
#unsorted
for key in d:
print (key,d[key])
#sorted
for key in sorted(d):
print (key,d[key])
08.02
# Open file
f = open('data/autofahrt.txt', 'r')
f2 = open('data/autofahrt_new.txt', 'w')
# read and ignore header lines
header1 = f.readline()
header2 = f.readline()
# loop over the lines in the iterable f
for line in f:
line = line.strip()
columns = line.split()
time = columns[0]
a = columns[2]
f2.write(time+' '+a+'\n') # time and a are already strings
# close the file handles
f.close()
f2.close()
09.01
import math
# math.cos takes radians
print ('cos 60 deg = ',math.cos(math.radians(60)))
print ('sin pi/6 =',math.sin(math.pi/6))
%ls data/
d={}
with open('data/munich_temperatures_average.txt','r') as f:
for line in f:
year,temp = line.strip().split()
s=year[0:4] # the years are the first four characters
if s not in d: # if year not found yet, add entry in dictionary
d[s]=[]
d[s].append(float(temp)) # note here the keys are strings
for key in sorted(d):
li=d[key]
print (key,min(li),sum(li)/float(len(li)),max(li))
The same for the months, here assuming for simplicity months of 30 days:
d={}
with open('data/munich_temperatures_average.txt','r') as f:
for line in f:
year,temp = line.strip().split()
frac=float(year)-float(year[0:4]) # subtract number of year
month=int(12*frac)+1 # split in 30-day intervals
if month not in d: # new month in dictionary
d[month]=[]
d[month].append(float(temp))
for key in sorted(d):
li=d[key]
print (key,min(li),sum(li)/float(len(li)),max(li))