Summary exercises - SOLVED
Contents
Summary exercises - SOLVED#
Exercise 1#
Write a function containing a for loop and a conditional such that it prints the even numbers up to 100.
def find_evens(N):
for n in range(1,N+1):
if n % 2 == 0:
print(n)
a = find_evens(100)
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100
Exercise 2#
Write a function which sums the numbers up to n, and returns the result. Test it.
def my_sum(n):
current_sum = 0
for i in range(1,n+1):
current_sum += i
return(current_sum)
print(my_sum(10))
55
Exercise 3#
Using some of the stuff defined above, find
$\( \sum_{k=0}^{100} \frac{4(-1)^k}{2k+1},\)$
write your code in the cell (you may add more cells) below. We showed two examples for computing sums here, one using a for loop and a running count, one using the sum function, try using both. Which is more appropriate here? Discuss!
#a better version of the sum function, for when we don't want to sum
#up from zero
def better_sum(start,stop,func):
"""
Function for summing a function evaluated at a range of values.
Takes three inputs:
start: the first value to use in the calculation
stop: the final value to use in the calculation
my_func: the function to sum over
"""
total = 0
for k in range(start,stop+1):
total += func(k)
return total
#The mathematical function we need to put into the sum
def my_func2(k):
return (4*(-1)**k)/(2*k+1)
#call the function to carry out the sum
print(better_sum(0,100,my_func2))
3.1514934010709914
Exercise 4#
Create a list of the first 100 natural numbers. A natural number is a non-negative integer, though some definitions omit 0.
Square (multiply the number by itself) all the numbers in the list which are not divisible by 7. Remember that ‘divide and give remainder’ is the % operator.
new_list = []
#loop over the numbers and identify those that are not divisible by 7
for n in range(1,101):
if n % 7 != 0:
new_list.append(n**2)
print(new_list)
[1, 4, 9, 16, 25, 36, 64, 81, 100, 121, 144, 169, 225, 256, 289, 324, 361, 400, 484, 529, 576, 625, 676, 729, 841, 900, 961, 1024, 1089, 1156, 1296, 1369, 1444, 1521, 1600, 1681, 1849, 1936, 2025, 2116, 2209, 2304, 2500, 2601, 2704, 2809, 2916, 3025, 3249, 3364, 3481, 3600, 3721, 3844, 4096, 4225, 4356, 4489, 4624, 4761, 5041, 5184, 5329, 5476, 5625, 5776, 6084, 6241, 6400, 6561, 6724, 6889, 7225, 7396, 7569, 7744, 7921, 8100, 8464, 8649, 8836, 9025, 9216, 9409, 9801, 10000]
Exercise 5#
Find $\( \sum_{k=0}^{100} \frac{4}{(4k+1)(4k+3)},\)$ write your code in the cell (you may add more cells) below.
#I'm going to reuse my sum function from above
#code up the mathematical function
def my_func3(k):
return 4/((4*k+1)*(4*k+3))
answer = better_sum(0,100,my_func3)
print(answer)
1.5683210944351496
Exercise 6#
Create a function consec_integers that has two inputs:
a, an integer
b, an integer
and it returns a list of all integers between \(a\) and \(b\) (including them).
Test your function with a few inputs.
def consec_integers(a,b):
return_list = []
for n in range(a,b+1):
return_list.append(n)
return return_list
consec_integers(1,5)
[1, 2, 3, 4, 5]
Exercise 7#
To check if \(x\) is an element of a list mylist you may use: $\(\verb|x in mylist |\)$
To check if \(x\) is not an element of a list mylist you may use: $\(\verb|x not in mylist |\)$ Create a function common_element that has two inputs:
listA, a list of some elements,
listB, a list of some elements.
It should return all elements that are both in listA and listB, so common elements of these two lists.
Test your function with the following lists:
\([1, 4, 5, 6, 8, 9, 13, 16, 18, 23]\),
\([5, 8, 11, 12, 13, 15, 17, 18]\)
def common_element(listA, listB):
common_list = []
for item in listA:
if item in listB:
common_list.append(item)
return common_list
list_A = [1,4,5,6,8,9,13,16,18,23]
list_B = [5,8,11,12,13,15,17,18]
common_element(list_A, list_B)
[5, 8, 13, 18]
Exercise 8#
Write a nested for loop (one loop inside another) that prints a truth table for the ‘and’ operator. Use two variables a and b that take all combinations of True and False, and show the value of (a and b). For example, you should have
a b => (a and b)
True True => True
True False => False
False True => False
False False => False
#We need to finc all the possible combos of True and False
#This can be done using two lists
a = [True,False]
b = [True,False]
print("a b => (a and b)")
#Use a nested loop to cycle through all element combos
for x in a:
for y in b:
res = x and y
print(f"{x} {y} => {res}")
a b => (a and b)
True True => True
True False => False
False True => False
False False => False
Exercise 9#
In the cell below, by using the for loop, calculate and print the following sum $\( \sum_{k=m}^n \frac{(k+1)^2}{k^3},\)\( where \)m=10\(, \)n=100$.
#I'm going to use my big sum again
#The mathematical function
def my_func4(k):
return ((k+1)**2) / k**3
new_result = better_sum(10,100,my_func4)
print(new_result)
2.554317016693555
Exercise 10#
Compute the first 15 numbers in the Fibonacci series (we’ve described this in previous classes …. or Google it) that are greater than 10 and are multiples of 3. The 15th number should be 10610209857723.
f1 = 1
f2 = 1
counter = 0
flist = []
while counter < 15:
fnext = f1+f2
f1 = f2
f2 = fnext
if fnext > 10 and fnext % 3 == 0:
flist.append(fnext)
counter += 1
#print each element of the list on a new line
print(*flist, sep="\n")
21
144
987
6765
46368
317811
2178309
14930352
102334155
701408733
4807526976
32951280099
225851433717
1548008755920
10610209857723
Exercise 11 - The factorial function#
Let us, again, consider a factorial of a natural number \(n\) where n is a positive integer. It is defined as follows $\( n! = 1 \cdot 2 \cdot 3 \cdots (n-1)\cdot n,\)\( and \)0! = 1$.
We can write this in shorthand using the big pi operator.
So big pi is a similar operator to \(\Sigma\) but represents a product rather than a sum.
Write a factorial function using a similar approach to our summation function (except using multiplication instead of addition!)
def big_pi(start,stop,func):
big_product = 1
for k in range(start,stop+1):
big_product *= func(k)
return big_product
def my_func5(k):
return k
big_pi(1,3,my_func5)
6
Exercise 12#
Calculate $\( \prod_{k=1}^{10} \frac{1}{k^2}\)$
(The answer should be very small!)
def my_func6(k):
return 1/k**2
big_pi(1,10,my_func6)
7.594058428126622e-14
Exercise 13#
The \(n\)-th term of the arithmetic sequence $\( a_1, a_2, \ldots, a_n \ldots \)\( is given by \)\( a_n = a_1 + (n-1)d,\)\( where \)a_1\( is the first term of the sequence, and \)d$ is the common difference of successive members.
Write a function arithm_seq with three inputs:
a1 (any numerical)
n (positive int)
d (any numerical)
so that it returns the n-th element of the arithmetic sequence with these parameters.
Given that \(a_1 = 3\), \(n = 17\) and \(d = \frac{4}{3}\) use your function geo_seq to print \(a_{17}\).
Then find the sum $\(\sum_{k=1}^{100}a_k\)\( of first \)100\( terms of the arithmetic progression, with \)a_1 = 5\(, \)d = \frac{3}{2}$.
def arithm_seq(a1,n,d):
return a1 + (n-1)*d
arithm_seq(3,17,4/3)
#sum this
ans = 0
for k in range(1,101):
ans += arithm_seq(5,k,3/2)
print(ans)
7925.0
Exercise 14#
Write a function which determines if an integer is prime (meaning it has no number other than one that divides it without a remainder). Remember the remainder operator is x % y. This function will need a loop and a conditional.
You can check if two things are not equal either with
if x != y:
or
if not x == y:
def is_prime(n):
if n == 1 or n == 2:
return f"{n} is not a prime number."
for i in range(2,n):
if n % i == 0:
return f"{n} is not a prime number."
return f"{n} is a prime number."
is_prime(999331)
'999331 is a prime number.'
Exercise 15 - Challenging#
In 14th century an Indian mathematician and astronomer, Madhava of Sangamagrama, gave a method for computing the value of \(\pi\) with precision to \(11\) decimal places.
He showed that $\( \pi \approx \sqrt{12}\sum_{k=0}^{21} \frac{(-3)^{-k}}{2k+1} = \sqrt{12}\sum_{k=0}^{21} \frac{(-\frac{1}{3})^k}{2k+1} = \sum_{k=0}^{21} \sqrt{12} \frac{(-\frac{1}{3})^k}{2k+1}\)$ is correct to 11 decimal places
Use this expression to compute \(\pi\) and check it’s accuracy against math.pi
import math
def my_func7(k):
return(12**(1/2)*((-1/3)**k/(2*k+1)))
a = better_sum(0,21,my_func7)
#check this is close to the true value of pi
print(a/math.pi)
0.9999999999994081
Exercise 16 - Challenging#
In 1656 English mathematician, John Wallis, approximated \(\pi\) with products, that is, $\(\pi = 2 \prod_{n=1}^{M} \frac{ 4n^2 }{ 4n^2 - 1 } \)\( when \)M$ becomes large (converges to infinity).
As you increase \(M\) the product will get closer to \(\pi\).
Compute this with the largest value of \(M\) that you can (NOTE: using M = 210938120983723897546823764 will not work as the code will never finish!) How accurate can you make this?
def my_func8(n):
return (4*n**2)/(4*n**2 - 1)
pi_calc = 2*big_pi(1,100000,my_func8)
print(pi_calc, math.pi)
3.141584799657247 3.141592653589793
Exercise 17#
Write a function to return the first 10 even prime numbers.
NOTE Sometimes as mathematicians/physicists if you understand the question being asked you can solve it much quicker than someone without your background! Think carefully about this one!
print(f"2 is the only even prime number. So this question makes no sense.")
2 is the only even prime number. So this question makes no sense.
Exercise 18 Caesar Shift - Challenge#
Write functions to impliment (code and decode) a Caesar Shift cipher.
Use your functions to decode “KYV ERKZFERC TZGYVI TYRCCVEXV JKRIKJ FE KYV JZOKY FW FTKFSVI. ZK JKRIKJ HLZKV VRJP SLK JFFE XVKJ UZWWZTLCK. ZK ZJ WIVV KF VEKVI.”
There are several ways to do this. One way that uses only skills we have covered so far, and the fact that Python has a function ‘ord’ that returns 65 for ‘A’ and 90 for ‘Z’, is outlined below:
Define a string that contains the alphabet in upper case letters.
Write a function that slices the alphabet, making a new string with letters shifted n places, and wrapped so all letters are present. I’ll call this the key.
Write a new function that creates a new string containing the coded/decoded text, by examining each letter in the text in turn and adding the equivalent letter from the key to the new string.
Write a short function that prints all 26 possible Caesar shift versions of the text. One of them should make sense.
Things to consider: How to cope with a character that is not in the alphabet. Ciphertext is conventionally in upper case, with plaintext in lower case. The method described above is a brute force approach. You could use frequency analysis on a long text, or look for single-letter words.
A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#demonstrate that ord gives us a number associated with each letter
for char in range(0,len(A)):
print(A[char],ord(A[char]))
def shift(A,n):
#slice the list. Take the first n elements and put them on the end.
key = (A[n:]+A[:n])
return key
shift(A,3)
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
K 75
L 76
M 77
N 78
O 79
P 80
Q 81
R 82
S 83
T 84
U 85
V 86
W 87
X 88
Y 89
Z 90
'DEFGHIJKLMNOPQRSTUVWXYZABC'
def caesar(text,n):
A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#shift all the characters along by n
key = shift(A,n)
code = ""
for char in range (len(text)):
#keeps characters that are not in the alphabet
if text[char]<"A" or text[char]>"Z":
code = code+text[char]
else:
#shifts the character back to its original position
c = ord(text[char])-65
code = code+key[c]
return code
codestring="KYV ERKZFERC TZGYVI TYRCCVEXV JKRIKJ FE KYV JZOKY FW FTKFSVI. ZK JKRIKJ HLZKV VRJP SLK JFFE XVKJ UZWWZTLCK. ZK ZJ WIVV KF VEKVI."
for n in range(0,26):
print(n, caesar(codestring,n))
0 KYV ERKZFERC TZGYVI TYRCCVEXV JKRIKJ FE KYV JZOKY FW FTKFSVI. ZK JKRIKJ HLZKV VRJP SLK JFFE XVKJ UZWWZTLCK. ZK ZJ WIVV KF VEKVI.
1 LZW FSLAGFSD UAHZWJ UZSDDWFYW KLSJLK GF LZW KAPLZ GX GULGTWJ. AL KLSJLK IMALW WSKQ TML KGGF YWLK VAXXAUMDL. AL AK XJWW LG WFLWJ.
2 MAX GTMBHGTE VBIAXK VATEEXGZX LMTKML HG MAX LBQMA HY HVMHUXK. BM LMTKML JNBMX XTLR UNM LHHG ZXML WBYYBVNEM. BM BL YKXX MH XGMXK.
3 NBY HUNCIHUF WCJBYL WBUFFYHAY MNULNM IH NBY MCRNB IZ IWNIVYL. CN MNULNM KOCNY YUMS VON MIIH AYNM XCZZCWOFN. CN CM ZLYY NI YHNYL.
4 OCZ IVODJIVG XDKCZM XCVGGZIBZ NOVMON JI OCZ NDSOC JA JXOJWZM. DO NOVMON LPDOZ ZVNT WPO NJJI BZON YDAADXPGO. DO DN AMZZ OJ ZIOZM.
5 PDA JWPEKJWH YELDAN YDWHHAJCA OPWNPO KJ PDA OETPD KB KYPKXAN. EP OPWNPO MQEPA AWOU XQP OKKJ CAPO ZEBBEYQHP. EP EO BNAA PK AJPAN.
6 QEB KXQFLKXI ZFMEBO ZEXIIBKDB PQXOQP LK QEB PFUQE LC LZQLYBO. FQ PQXOQP NRFQB BXPV YRQ PLLK DBQP AFCCFZRIQ. FQ FP COBB QL BKQBO.
7 RFC LYRGMLYJ AGNFCP AFYJJCLEC QRYPRQ ML RFC QGVRF MD MARMZCP. GR QRYPRQ OSGRC CYQW ZSR QMML ECRQ BGDDGASJR. GR GQ DPCC RM CLRCP.
8 SGD MZSHNMZK BHOGDQ BGZKKDMFD RSZQSR NM SGD RHWSG NE NBSNADQ. HS RSZQSR PTHSD DZRX ATS RNNM FDSR CHEEHBTKS. HS HR EQDD SN DMSDQ.
9 THE NATIONAL CIPHER CHALLENGE STARTS ON THE SIXTH OF OCTOBER. IT STARTS QUITE EASY BUT SOON GETS DIFFICULT. IT IS FREE TO ENTER.
10 UIF OBUJPOBM DJQIFS DIBMMFOHF TUBSUT PO UIF TJYUI PG PDUPCFS. JU TUBSUT RVJUF FBTZ CVU TPPO HFUT EJGGJDVMU. JU JT GSFF UP FOUFS.
11 VJG PCVKQPCN EKRJGT EJCNNGPIG UVCTVU QP VJG UKZVJ QH QEVQDGT. KV UVCTVU SWKVG GCUA DWV UQQP IGVU FKHHKEWNV. KV KU HTGG VQ GPVGT.
12 WKH QDWLRQDO FLSKHU FKDOOHQJH VWDUWV RQ WKH VLAWK RI RFWREHU. LW VWDUWV TXLWH HDVB EXW VRRQ JHWV GLIILFXOW. LW LV IUHH WR HQWHU.
13 XLI REXMSREP GMTLIV GLEPPIRKI WXEVXW SR XLI WMBXL SJ SGXSFIV. MX WXEVXW UYMXI IEWC FYX WSSR KIXW HMJJMGYPX. MX MW JVII XS IRXIV.
14 YMJ SFYNTSFQ HNUMJW HMFQQJSLJ XYFWYX TS YMJ XNCYM TK THYTGJW. NY XYFWYX VZNYJ JFXD GZY XTTS LJYX INKKNHZQY. NY NX KWJJ YT JSYJW.
15 ZNK TGZOUTGR IOVNKX INGRRKTMK YZGXZY UT ZNK YODZN UL UIZUHKX. OZ YZGXZY WAOZK KGYE HAZ YUUT MKZY JOLLOIARZ. OZ OY LXKK ZU KTZKX.
16 AOL UHAPVUHS JPWOLY JOHSSLUNL ZAHYAZ VU AOL ZPEAO VM VJAVILY. PA ZAHYAZ XBPAL LHZF IBA ZVVU NLAZ KPMMPJBSA. PA PZ MYLL AV LUALY.
17 BPM VIBQWVIT KQXPMZ KPITTMVOM ABIZBA WV BPM AQFBP WN WKBWJMZ. QB ABIZBA YCQBM MIAG JCB AWWV OMBA LQNNQKCTB. QB QA NZMM BW MVBMZ.
18 CQN WJCRXWJU LRYQNA LQJUUNWPN BCJACB XW CQN BRGCQ XO XLCXKNA. RC BCJACB ZDRCN NJBH KDC BXXW PNCB MROORLDUC. RC RB OANN CX NWCNA.
19 DRO XKDSYXKV MSZROB MRKVVOXQO CDKBDC YX DRO CSHDR YP YMDYLOB. SD CDKBDC AESDO OKCI LED CYYX QODC NSPPSMEVD. SD SC PBOO DY OXDOB.
20 ESP YLETZYLW NTASPC NSLWWPYRP DELCED ZY ESP DTIES ZQ ZNEZMPC. TE DELCED BFTEP PLDJ MFE DZZY RPED OTQQTNFWE. TE TD QCPP EZ PYEPC.
21 FTQ ZMFUAZMX OUBTQD OTMXXQZSQ EFMDFE AZ FTQ EUJFT AR AOFANQD. UF EFMDFE CGUFQ QMEK NGF EAAZ SQFE PURRUOGXF. UF UE RDQQ FA QZFQD.
22 GUR ANGVBANY PVCURE PUNYYRATR FGNEGF BA GUR FVKGU BS BPGBORE. VG FGNEGF DHVGR RNFL OHG FBBA TRGF QVSSVPHYG. VG VF SERR GB RAGRE.
23 HVS BOHWCBOZ QWDVSF QVOZZSBUS GHOFHG CB HVS GWLHV CT CQHCPSF. WH GHOFHG EIWHS SOGM PIH GCCB USHG RWTTWQIZH. WH WG TFSS HC SBHSF.
24 IWT CPIXDCPA RXEWTG RWPAATCVT HIPGIH DC IWT HXMIW DU DRIDQTG. XI HIPGIH FJXIT TPHN QJI HDDC VTIH SXUUXRJAI. XI XH UGTT ID TCITG.
25 JXU DQJYEDQB SYFXUH SXQBBUDWU IJQHJI ED JXU IYNJX EV ESJERUH. YJ IJQHJI GKYJU UQIO RKJ IEED WUJI TYVVYSKBJ. YJ YI VHUU JE UDJUH.