Skip to content

Commit 9eafcdc

Browse files
updated exercises lecture 3
1 parent ad5f177 commit 9eafcdc

File tree

1 file changed

+1
-358
lines changed

1 file changed

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

0 commit comments

Comments
 (0)