06.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)
06.02
One can do this using strings:
def digit_sum(x):
ans=0
for digit in str(x):
ans=ans+int(digit)
return ans
or the modulus operator:
def digit_sum(x):
ans=0
while (x>=1):
digit=x%10 # first decimal position
ans=ans+digit
x=(x-digit)//10 # remaining digits
return ans
It is also possible to use recursion to work this out:
def digit_sum(x):
digit=x%10 # first decimal position
if x>=1:
return digit + digit_sum((x-digit)//10)
else:
return 0
06.03
def mean(x):
return sum(x)/float(len(x))
def stddev(x):
ans=0
m=mean(x)
for el in x:
ans+=(el-m)**2
return (ans/(len(x)-1))**0.5
07.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])
07.02
# Open file
f = open('data/autofahrt.txt', 'r')
f2 = open('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()
08.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))
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 fixed length:
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 12 intervals
# (approximation)
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))