Skip to content

Commit 2ba5ddd

Browse files
committed
Updated
1 parent 9dcb36e commit 2ba5ddd

File tree

3 files changed

+3231
-3
lines changed

3 files changed

+3231
-3
lines changed

Diff for: EXERCISES/Exercises_Lecture_03.ipynb

+344-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,344 @@
1-
{"cells":[{"cell_type":"markdown","source":["# PYTHON COURSE FOR SCIENTIFIC PROGRAMMING \n","**Contributors:** \\\n","Artur Llabrés Brustenga: Artur.Llabres@e-campus.uab.cat \\\n","Gerard Navarro Pérez: Gerard.NavarroP@e-campus.uab.cat \\\n","Arnau Parrilla Gibert: Arnau.Parrilla@e-campus.uab.cat \\\n","Jan Scarabelli Calopa:Jan.Scarabelli@e-campus.uab.cat \\\n","Xabier Oyanguren Asua: Xabier.Oyanguren@e-campus.uab.cat\n","\n","Course material can be found at: https://llacorp.github.io/Python-Course-for-Scientific-Programming/ "],"metadata":{"id":"P4hDyWJnlkkV"}},{"cell_type":"markdown","metadata":{"id":"-rYMKOqDez5v"},"source":["## <ins>Exercise 1</ins>:"]},{"cell_type":"markdown","metadata":{"id":"0-NaBG9XhgU8"},"source":["Write a Python function to check whether a number is perfect or not. It should return `True` or `False`.\n","\n","***Wikipedia source***: \"*A perfect number is a positive integer that is equal to the sum of its positive divisors excluding the number itself.*\n","\n","*Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).*\" \n","\n","<ins>For example</ins>: \n","\n","The first perfect number is 6, because 1, 2, and 3 are its positive divisors excluding itself, and 1 + 2 + 3 = 6.\n","\n","Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6.\n","\n","\n","The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128."]},{"cell_type":"markdown","metadata":{"id":"tR4v1HGeiApl"},"source":["**SOLUTION**:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"4Iciqs4Sh-ar","outputId":"f423d936-ccad-401d-ef14-e115c40708cb"},"outputs":[{"name":"stdout","output_type":"stream","text":["True\n"]}],"source":["def perfect_number(n):\n"," sum = 0\n"," for x in range(1, n):\n"," if n % x == 0:\n"," sum += x\n"," return sum == n\n"," \n","print(perfect_number(6))"]},{"cell_type":"markdown","metadata":{"id":"0IZIsOxNjbhw"},"source":["## <ins>Exercise 2</ins>:"]},{"cell_type":"markdown","metadata":{"id":"PVlUe6mHjpeU"},"source":["Write two Python functions to find the $F_n$ Fibonacci number, one using an iterative method and the other one using recursion. The only argument is `n` and the $n$-th number in the Fibonacci sequence should be retuned.\n","\n","***Wikipedia source***: In mathematics, the Fibonacci numbers, commonly denoted $F_n$, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,\n","\n","$$F_{0}=0,\\quad F_{1}=1,$$\n","and\n","$$F_{n}=F_{n-1}+F_{n-2}$$\n","for $n > 1$. \n","The beginning of the sequence is thus:\n","$$0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...$$\n","\n","<ins>For example</ins>: The Fibonacci number $F_7$ equals $13$, so the functions should return this value."]},{"cell_type":"markdown","metadata":{"id":"XKhg1tVkjkto"},"source":["**SOLUTION**:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"pKC9NZDYjnkg"},"outputs":[],"source":["def F_iter(n):\n"," if (n == 0):\n"," return 0\n"," elif (n == 1):\n"," return 1\n"," elif (n > 1):\n"," fn = 0\n"," fn1 = 1\n"," fn2 = 2\n"," for i in range(3, n):\n"," fn = fn1 + fn2\n"," fn1 = fn2\n"," fn2 = fn\n"," return fn\n","\n","def F(n):\n"," if (n == 0):\n"," return 0\n"," elif (n == 1):\n"," return 1\n"," elif (n > 1):\n"," return (F(n-1) + F(n-2))"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"vmuuU6Qb4tHO","outputId":"bc611b30-0594-4b6c-9efb-f6ff2c8507f0"},"outputs":[{"name":"stdout","output_type":"stream","text":["13\n","13\n"]}],"source":["print(F_iter(7))\n","print(F(7))"]},{"cell_type":"markdown","metadata":{"id":"bcsyVRrLjeNA"},"source":["## <ins>Exercise 3</ins>:"]},{"cell_type":"markdown","metadata":{"id":"mq5VNFVZjqdm"},"source":["Write a Python program to create a dictionary from a string. The dictionary should contain as keys the characters of the string and as values the number of times the character is repeated.\n","\n","***Note 1***: Track the count of the letters from the string. \n","***Note 2***: To check if a character is in a string just type `\"char\" in str1` \n","<ins>For example</ins>: The string 'scn2python' should output: `{'s': 1, 'c': 1, 'n': 2, '2': 1, 'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1}`"]},{"cell_type":"markdown","metadata":{"id":"w0UpFVuBjlXc"},"source":["**SOLUTION**:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"enTtP8kljoZa","outputId":"3dfbcf73-0805-4853-a8c6-1c5949ea70a3"},"outputs":[{"name":"stdout","output_type":"stream","text":["{'s': 1, 'c': 1, 'n': 2, '2': 1, 'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1}\n"]}],"source":["str1 = 'scn2python' \n","my_dict = {}\n","for letter in str1:\n"," if (my_dict.get(letter) == None): #or letter not in my_dict.keys()\n"," my_dict[letter] = 1\n"," else:\n"," my_dict[letter] += 1\n","print(my_dict)"]},{"cell_type":"markdown","metadata":{"id":"ngPDJ-pSjgGb"},"source":["## <ins>Exercise 4</ins>:"]},{"cell_type":"markdown","metadata":{"id":"oMSJ_bvjjrNC"},"source":["Write a Python program to perform numerical integration using rectangles.\n","\n","To test the program use the function\n","\n","$$f(x)=\\frac{x^4(1-x^4)}{1+x^2}dx$$\n","\n","and integrate it between $1$ and $2$. The result should be about $0.522...$ for $n=10000$.\n","\n","***Note 1***: Remember that we can approximate an integral using tiny rectangles given a step $\\Delta x$ with\n","$$\\int_{a}^{b} f(x)dx = \\sum_{i=0}^{n} \\Delta xf(a+i\\Delta x)$$\n","\n","We will define our $\\Delta x=\\frac{b-a}{n}$. For higher values of $n$ (*i.e.* smaller $\\Delta x$), the approximation is more precise\n","\n","<img src=\"https://i.stack.imgur.com/BJPUl.png\" alt=\"Drawing\" style=\"width: 500px;\"/>\n","\n","Define two functions, one for $f(x)$ and the other one must return the integral solution given $a$, $b$ and $n$.\n","\n","***Note 2***: You can call a function inside another function."]},{"cell_type":"markdown","metadata":{"id":"JtjyQi2ujlzw"},"source":["**SOLUTION**:"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"ByVIxIpPjo32","outputId":"e2199d33-3fdd-4b3f-ea8b-b8dbe43f82d8"},"outputs":[{"name":"stdout","output_type":"stream","text":["0.5226816058039061\n"]}],"source":["#the function to be integrated:\n","def f(x):\n"," return x ** 4 * (1 - x) ** 4 / (1 + x ** 2)\n"," \n","#define a function to do integration of f(x) btw. 0 and 1:\n","def trapezium(a, b, n):\n"," h = (b-a) / n\n"," intgr = 0\n"," for i in range(0, n+1):\n"," intgr = intgr + h * f(a + i * h)\n"," return intgr\n"," \n","print(trapezium(1, 2, 10000))"]}],"metadata":{"colab":{"collapsed_sections":[],"name":"Exercises_Lecture_03.ipynb","provenance":[],"toc_visible":true},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.8.5"}},"nbformat":4,"nbformat_minor":0}
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {
6+
"id": "P4hDyWJnlkkV"
7+
},
8+
"source": [
9+
"# Lecture III: EXERCISES\n",
10+
"\n",
11+
"----"
12+
]
13+
},
14+
{
15+
"cell_type": "markdown",
16+
"metadata": {
17+
"id": "-rYMKOqDez5v"
18+
},
19+
"source": [
20+
"## <ins>Exercise 1</ins>:"
21+
]
22+
},
23+
{
24+
"cell_type": "markdown",
25+
"metadata": {
26+
"id": "0-NaBG9XhgU8"
27+
},
28+
"source": [
29+
"Write a Python function to check whether a number is perfect or not. It should return `True` or `False`.\n",
30+
"\n",
31+
"***Wikipedia source***: \"*A perfect number is a positive integer that is equal to the sum of its positive divisors excluding the number itself.*\n",
32+
"\n",
33+
"*Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).*\" \n",
34+
"\n",
35+
"<ins>For example</ins>: \n",
36+
"\n",
37+
"The first perfect number is 6, because 1, 2, and 3 are its positive divisors excluding itself, and 1 + 2 + 3 = 6.\n",
38+
"\n",
39+
"Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6.\n",
40+
"\n",
41+
"\n",
42+
"The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128."
43+
]
44+
},
45+
{
46+
"cell_type": "markdown",
47+
"metadata": {
48+
"id": "tR4v1HGeiApl"
49+
},
50+
"source": [
51+
"**SOLUTION**:"
52+
]
53+
},
54+
{
55+
"cell_type": "code",
56+
"execution_count": null,
57+
"metadata": {
58+
"colab": {
59+
"base_uri": "https://localhost:8080/"
60+
},
61+
"id": "4Iciqs4Sh-ar",
62+
"outputId": "f423d936-ccad-401d-ef14-e115c40708cb"
63+
},
64+
"outputs": [
65+
{
66+
"name": "stdout",
67+
"output_type": "stream",
68+
"text": [
69+
"True\n"
70+
]
71+
}
72+
],
73+
"source": [
74+
"def perfect_number(n):\n",
75+
" sum = 0\n",
76+
" for x in range(1, n):\n",
77+
" if n % x == 0:\n",
78+
" sum += x\n",
79+
" return sum == n\n",
80+
" \n",
81+
"print(perfect_number(6))"
82+
]
83+
},
84+
{
85+
"cell_type": "markdown",
86+
"metadata": {
87+
"id": "0IZIsOxNjbhw"
88+
},
89+
"source": [
90+
"## <ins>Exercise 2</ins>:"
91+
]
92+
},
93+
{
94+
"cell_type": "markdown",
95+
"metadata": {
96+
"id": "PVlUe6mHjpeU"
97+
},
98+
"source": [
99+
"Write two Python functions to find the $F_n$ Fibonacci number, one using an iterative method and the other one using recursion. The only argument is `n` and the $n$-th number in the Fibonacci sequence should be retuned.\n",
100+
"\n",
101+
"***Wikipedia source***: In mathematics, the Fibonacci numbers, commonly denoted $F_n$, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,\n",
102+
"\n",
103+
"$$F_{0}=0,\\quad F_{1}=1,$$\n",
104+
"and\n",
105+
"$$F_{n}=F_{n-1}+F_{n-2}$$\n",
106+
"for $n > 1$. \n",
107+
"The beginning of the sequence is thus:\n",
108+
"$$0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...$$\n",
109+
"\n",
110+
"<ins>For example</ins>: The Fibonacci number $F_7$ equals $13$, so the functions should return this value."
111+
]
112+
},
113+
{
114+
"cell_type": "markdown",
115+
"metadata": {
116+
"id": "XKhg1tVkjkto"
117+
},
118+
"source": [
119+
"**SOLUTION**:"
120+
]
121+
},
122+
{
123+
"cell_type": "code",
124+
"execution_count": null,
125+
"metadata": {
126+
"id": "pKC9NZDYjnkg"
127+
},
128+
"outputs": [],
129+
"source": [
130+
"def F_iter(n):\n",
131+
" if (n == 0):\n",
132+
" return 0\n",
133+
" elif (n == 1):\n",
134+
" return 1\n",
135+
" elif (n > 1):\n",
136+
" fn = 0\n",
137+
" fn1 = 1\n",
138+
" fn2 = 2\n",
139+
" for i in range(3, n):\n",
140+
" fn = fn1 + fn2\n",
141+
" fn1 = fn2\n",
142+
" fn2 = fn\n",
143+
" return fn\n",
144+
"\n",
145+
"def F(n):\n",
146+
" if (n == 0):\n",
147+
" return 0\n",
148+
" elif (n == 1):\n",
149+
" return 1\n",
150+
" elif (n > 1):\n",
151+
" return (F(n-1) + F(n-2))"
152+
]
153+
},
154+
{
155+
"cell_type": "code",
156+
"execution_count": null,
157+
"metadata": {
158+
"colab": {
159+
"base_uri": "https://localhost:8080/"
160+
},
161+
"id": "vmuuU6Qb4tHO",
162+
"outputId": "bc611b30-0594-4b6c-9efb-f6ff2c8507f0"
163+
},
164+
"outputs": [
165+
{
166+
"name": "stdout",
167+
"output_type": "stream",
168+
"text": [
169+
"13\n",
170+
"13\n"
171+
]
172+
}
173+
],
174+
"source": [
175+
"print(F_iter(7))\n",
176+
"print(F(7))"
177+
]
178+
},
179+
{
180+
"cell_type": "markdown",
181+
"metadata": {
182+
"id": "bcsyVRrLjeNA"
183+
},
184+
"source": [
185+
"## <ins>Exercise 3</ins>:"
186+
]
187+
},
188+
{
189+
"cell_type": "markdown",
190+
"metadata": {
191+
"id": "mq5VNFVZjqdm"
192+
},
193+
"source": [
194+
"Write a Python program to create a dictionary from a string. The dictionary should contain as keys the characters of the string and as values the number of times the character is repeated.\n",
195+
"\n",
196+
"***Note 1***: Track the count of the letters from the string. \n",
197+
"***Note 2***: To check if a character is in a string just type `\"char\" in str1` \n",
198+
"<ins>For example</ins>: The string 'scn2python' should output: `{'s': 1, 'c': 1, 'n': 2, '2': 1, 'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1}`"
199+
]
200+
},
201+
{
202+
"cell_type": "markdown",
203+
"metadata": {
204+
"id": "w0UpFVuBjlXc"
205+
},
206+
"source": [
207+
"**SOLUTION**:"
208+
]
209+
},
210+
{
211+
"cell_type": "code",
212+
"execution_count": null,
213+
"metadata": {
214+
"colab": {
215+
"base_uri": "https://localhost:8080/"
216+
},
217+
"id": "enTtP8kljoZa",
218+
"outputId": "3dfbcf73-0805-4853-a8c6-1c5949ea70a3"
219+
},
220+
"outputs": [
221+
{
222+
"name": "stdout",
223+
"output_type": "stream",
224+
"text": [
225+
"{'s': 1, 'c': 1, 'n': 2, '2': 1, 'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1}\n"
226+
]
227+
}
228+
],
229+
"source": [
230+
"str1 = 'scn2python' \n",
231+
"my_dict = {}\n",
232+
"for letter in str1:\n",
233+
" if (my_dict.get(letter) == None): #or letter not in my_dict.keys()\n",
234+
" my_dict[letter] = 1\n",
235+
" else:\n",
236+
" my_dict[letter] += 1\n",
237+
"print(my_dict)"
238+
]
239+
},
240+
{
241+
"cell_type": "markdown",
242+
"metadata": {
243+
"id": "ngPDJ-pSjgGb"
244+
},
245+
"source": [
246+
"## <ins>Exercise 4</ins>:"
247+
]
248+
},
249+
{
250+
"cell_type": "markdown",
251+
"metadata": {
252+
"id": "oMSJ_bvjjrNC"
253+
},
254+
"source": [
255+
"Write a Python program to perform numerical integration using rectangles.\n",
256+
"\n",
257+
"To test the program use the function\n",
258+
"\n",
259+
"$$f(x)=\\frac{x^4(1-x^4)}{1+x^2}dx$$\n",
260+
"\n",
261+
"and integrate it between $1$ and $2$. The result should be about $0.522...$ for $n=10000$.\n",
262+
"\n",
263+
"***Note 1***: Remember that we can approximate an integral using tiny rectangles given a step $\\Delta x$ with\n",
264+
"$$\\int_{a}^{b} f(x)dx = \\sum_{i=0}^{n} \\Delta xf(a+i\\Delta x)$$\n",
265+
"\n",
266+
"We will define our $\\Delta x=\\frac{b-a}{n}$. For higher values of $n$ (*i.e.* smaller $\\Delta x$), the approximation is more precise\n",
267+
"\n",
268+
"<img src=\"https://i.stack.imgur.com/BJPUl.png\" alt=\"Drawing\" style=\"width: 500px;\"/>\n",
269+
"\n",
270+
"Define two functions, one for $f(x)$ and the other one must return the integral solution given $a$, $b$ and $n$.\n",
271+
"\n",
272+
"***Note 2***: You can call a function inside another function."
273+
]
274+
},
275+
{
276+
"cell_type": "markdown",
277+
"metadata": {
278+
"id": "JtjyQi2ujlzw"
279+
},
280+
"source": [
281+
"**SOLUTION**:"
282+
]
283+
},
284+
{
285+
"cell_type": "code",
286+
"execution_count": null,
287+
"metadata": {
288+
"id": "ByVIxIpPjo32",
289+
"outputId": "e2199d33-3fdd-4b3f-ea8b-b8dbe43f82d8"
290+
},
291+
"outputs": [
292+
{
293+
"name": "stdout",
294+
"output_type": "stream",
295+
"text": [
296+
"0.5226816058039061\n"
297+
]
298+
}
299+
],
300+
"source": [
301+
"#the function to be integrated:\n",
302+
"def f(x):\n",
303+
" return x ** 4 * (1 - x) ** 4 / (1 + x ** 2)\n",
304+
" \n",
305+
"#define a function to do integration of f(x) btw. 0 and 1:\n",
306+
"def trapezium(a, b, n):\n",
307+
" h = (b-a) / n\n",
308+
" intgr = 0\n",
309+
" for i in range(0, n+1):\n",
310+
" intgr = intgr + h * f(a + i * h)\n",
311+
" return intgr\n",
312+
" \n",
313+
"print(trapezium(1, 2, 10000))"
314+
]
315+
}
316+
],
317+
"metadata": {
318+
"colab": {
319+
"collapsed_sections": [],
320+
"name": "Exercises_Lecture_03.ipynb",
321+
"provenance": [],
322+
"toc_visible": true
323+
},
324+
"kernelspec": {
325+
"display_name": "Python 3",
326+
"language": "python",
327+
"name": "python3"
328+
},
329+
"language_info": {
330+
"codemirror_mode": {
331+
"name": "ipython",
332+
"version": 3
333+
},
334+
"file_extension": ".py",
335+
"mimetype": "text/x-python",
336+
"name": "python",
337+
"nbconvert_exporter": "python",
338+
"pygments_lexer": "ipython3",
339+
"version": "3.7.3"
340+
}
341+
},
342+
"nbformat": 4,
343+
"nbformat_minor": 1
344+
}

0 commit comments

Comments
 (0)