Python course University of Heidelberg summer 2024

Solutions Day 2 (April 9th)

06.01

In [ ]:
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:

In [9]:
def digit_sum(x):
    ans=0
    for digit in str(x):
        ans=ans+int(digit)
    return ans

or the modulus operator:

In [ ]:
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:

In [ ]:
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

In [6]:
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

In [ ]:
# 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

In [ ]:
# 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

In [ ]:
import math
# math.cos takes radians
print ('cos 60 deg = ',math.cos(math.radians(60)))
print ('sin pi/6 =',math.sin(math.pi/6))

Practice problem temperatures

In [2]:
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))
1995 -13.2778 8.765600054794515 25.9444
1996 -15.5 7.22983359342466 23.8333
1997 -12.8889 8.548421924590162 21.5556
1998 -12.2222 9.245702324861876 25.5
1999 -9.83333 9.110651741758234 25.3333
2000 -16.7778 9.76544640164383 24.7778
2001 -12.1667 9.00713250874317 24.5556
2002 -11.1111 9.881714284084081 25.1111
2003 -14.3333 9.398325638356173 27.6667
2004 -10.7778 8.877015703013702 23.0
2005 -14.1111 8.224754590883188 25.1111
2006 -11.2778 9.163765467582415 25.9444
2007 -8.83333 9.768647250696379 26.2778
2008 -5.11111 9.660867162637365 24.0556
2009 -10.7778 9.37229706465753 23.2778
2010 -9.33333 8.321307882191778 25.7222
2011 -9.27778 9.691631063013695 25.5
2012 -15.4444 9.225267140821925 24.7222
2013 -7.38889 0.6455037752380951 11.1667

The same for the months, here assuming for simplicity months of fixed length:

In [3]:
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))
    
1 -16.7778 -0.8494002017421606 12.2222
2 -15.4444 0.6628654298245613 11.9444
3 -7.66667 4.473989138162547 16.2778
4 -2.11111 9.276253876416819 20.7222
5 5.22222 13.979305660036161 23.1667
6 7.77778 17.20418630597015 25.1111
7 10.5 18.459178853046595 26.2778
8 9.5 18.218715287569577 27.6667
9 3.88889 13.708544866412208 22.7222
10 -1.44444 9.380126712544817 20.5
11 -7.11111 3.7421812866666655 14.1667
12 -15.5 0.22031673032490967 11.2778

There are the calendar and datetime built-in modules which may make things easier/more professional.