03.01
In [ ]:
[4**3,2+3.4**2,(1+1j)**2]
03.02
In [ ]:
a = "... but a giant leap for mankind."
num=a.index('leap')
print(a[0:num]+a[num+4:])
03.03
In [ ]:
s = "CAGTACCAAGTGAAAGAT"
s.count('A')
or maybe more cumbersome:
In [ ]:
len(s.split(sep='A'))-1
In [ ]:
a=[1,2,3]
b=[4,5,6]
c=a+b
# or
d=a
d.extend(b)
print (c,d)
04.01
In [ ]:
x=3.7
(x>3.4 and x<=6.6) or (x==2)
04.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()])
05.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)
05.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)
05.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)
.... the same as a function: (functions are introduced on Tuesday)
In [ ]:
def caesar_encrypt(message,shift):
base=ord('a')
res=''
for character in message.lower():
if character==' ':
tt=ord(' ')
else:
ascii=ord(character)
tt=ascii+shift
if tt>=base+26:
tt-=26
elif tt<base:
tt+=26
res+=chr(tt)
return res
caesar_encrypt(s,-13)
Determine the unkown cipher shift trying out all
In [ ]:
s='wxkxmh ngynlcb cqn byjwrbq rwzdrbrcrxw'
In [ ]:
for shift in range(-10,20):
print (shift,caesar_encrypt(s,shift))
Note solution -9 and 17 are equivalent.