Solutions to exercises

04.01

In [ ]:
[4**3,2+3.4**2,(1+1j)**2]

04.02

In [ ]:
a = "Hello, egg world"
num=a.index('egg')
print(a[0:num]+a[num+4:])

04.03

In [ ]:
s = "CAGTACCAAGTGAAAGAT"
s.count('A')
In [ ]:
a=[1,2,3]
b=[4,5,6]
c=a+b

# or

d=a
d.extend(b)
print (c,d)

05.01

In [ ]:
x=3.7
(x>3.4 and x<=6.6) or (x==2)

05.02

In [ ]:
dict={'snake':'Schlange','jungle':'Dschungel','lives':'lebt','in':'in','the':'der'}

s="The snake lives in the jungle"
for word in s.split():
    print (dict[word.lower()])

06.01

In [ ]:
for i in range(2,1000):
    is_prime=True
    for j in range(2,i):
        if (i%j==0):
            is_prime=False
    if is_prime:
        print (i)
        

06.02: Simply break the loop since it is not necessary to search further if one divisor is found.

In [ ]:
for i in range(2,1000):
    is_prime=True
    for j in range(2,i):
        if (i%j==0):
            is_prime=False
            break
    if is_prime:
        print (i)

06.03

In [ ]:
# very terse:
a, b = 0, 1
while a < 100000:
    print(a)
    a, b = b, a + b
In [ ]:
#Fibonacci sequence with index
#
l=[0]
i=0
x=1

while x<100000:
    l.append(x)     # add x_i
    x=l[i]+l[i+1]   # work out x_i+1
    i=i+1
    
print (len(l))

And the square Fibonaccis:

In [ ]:
# determine square Fibonaccis
l=[0]
x=1

while x<100000:
    l.append(x)
    x=l[-2]+l[-1]

# print square Fibonacci numbers
for fibonacci in l:
    is_square=False
    for j in range(fibonacci):
        if j*j==fibonacci:
            is_square=True
            break
    if is_square:
        print ("square number =",fibonacci)

Solution Cryptography

In [ ]:
s='pbatenghyngvbaf lbh unir fhpprrqrq va qrpelcgvat gur fgevat'

base=ord('a') # ascii code for 'a'
decode=-13
res=''
for character in s.lower():
    if character==' ':
        t=character
    else:
        ascii=ord(character)
        t=chr(((ascii+decode)-base)%26+base) # (ascii-97)%26 in range 0 ... 25
    res+=t
print (decode,res)   

The translation of ascii can also be done explicitly:

In [ ]:
s='pbatenghyngvbaf lbh unir fhpprrqrq va qrpelcgvat gur fgevat'

base=ord('a') # ascii code for 'a'
decode=-13

res=''
for character in s.lower():
    if character==' ':
        tt=ord(' ')
    else:
        ascii=ord(character)
        tt=ascii+decode
        if tt>=base+26:
            tt-=26
        elif tt<base:
            tt+=26
    res+=chr(tt)
print (decode,res)

Determine the unkown cipher shift trying out all

In [ ]:
s='gwc uivioml bw nqvl bpm zqopb apqnb'
In [ ]:
base=ord('a') # ascii code for 'a'
for decode in range(-10,20):
    #decode=-13
    res=''
    for character in s.lower():
        if character==' ':
            t=character
        else:
            ascii=ord(character)
            t=chr(((ascii+decode)-base)%26+base)
        res+=t
    print (decode,res)   

Note solution -8 and 18 are equivalent.

In [ ]: