From a2a803cb40932fa99c52d0e2d008f3b9fa2bc1ee Mon Sep 17 00:00:00 2001 From: Med Hicham RAHIMI Date: Sun, 6 Nov 2022 03:13:34 +0100 Subject: [PATCH] Formatting improved; Use f-string; Correcting some typo, assert synthaxe, and exercices correction From your student (Thank you) --- day01/Python Data Types.ipynb | 39 +- day01/Python_basics.ipynb | 2 +- day01/tasks_for_datatypes.ipynb | 21 +- day01/tasks_for_datatypes_correc.ipynb | 1580 +++++++++---------- day01/tasks_for_day_01.ipynb | 2 +- day01/tasks_for_day_01_correc.ipynb | 1967 +++++++++++------------- 6 files changed, 1761 insertions(+), 1850 deletions(-) diff --git a/day01/Python Data Types.ipynb b/day01/Python Data Types.ipynb index 80d8310..9b23e53 100644 --- a/day01/Python Data Types.ipynb +++ b/day01/Python Data Types.ipynb @@ -246,8 +246,7 @@ "cell_type": "code", "execution_count": 27, "metadata": { - "id": "8fYoL4aLwpVi", - "scrolled": false + "id": "8fYoL4aLwpVi" }, "outputs": [], "source": [ @@ -338,11 +337,33 @@ }, { "cell_type": "code", - "execution_count": 29, + "execution_count": 13, "metadata": { "id": "gs4lLKoKwpVp" }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "t[0]: 12345\n", + "t: (12345, 54321, 'hello!')\n", + "(12345, 54321)\n", + "v: ([1, 2, 3], [3, 2, 1])\n", + "v=([1, 2, 3], [3, 2, 1])\n" + ] + }, + { + "data": { + "text/plain": [ + "([1, 2, 3, 100], [3, 2, 1])" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# You can leave the parentheses off, if you like.\n", "t = (12345, 54321, 'hello!')\n", @@ -351,7 +372,7 @@ "print(t[:2])\n", "# they can contain mutable objects:\n", "v = ([1, 2, 3], [3, 2, 1])\n", - "print('v: ', v)\n", + "print('v: ', v) \n", "v[0].append(100)\n", "v" ] @@ -371,7 +392,7 @@ }, { "cell_type": "code", - "execution_count": 30, + "execution_count": null, "metadata": { "id": "sue6pbeDwpVu" }, @@ -566,7 +587,7 @@ "\n", "# Iterate over pairs of (i, name) which have both index and name.\n", "for (i, name) in enumerate(a):\n", - " print('Foo: {} {}'.format(i, name))" + " print(f'Foo: {i} {name}')" ] }, { @@ -660,9 +681,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.10" + "version": "3.9.13" } }, "nbformat": 4, - "nbformat_minor": 1 + "nbformat_minor": 4 } diff --git a/day01/Python_basics.ipynb b/day01/Python_basics.ipynb index 716dc14..bfb2472 100644 --- a/day01/Python_basics.ipynb +++ b/day01/Python_basics.ipynb @@ -697,7 +697,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.10" + "version": "3.9.13" } }, "nbformat": 4, diff --git a/day01/tasks_for_datatypes.ipynb b/day01/tasks_for_datatypes.ipynb index bbb83dc..03b60c2 100644 --- a/day01/tasks_for_datatypes.ipynb +++ b/day01/tasks_for_datatypes.ipynb @@ -168,7 +168,7 @@ "outputs": [], "source": [ "def wwmrl(s):\n", - " #Code Here\n", + " # Code Here\n", "assert wwmrl(['this', 'is', 'an', 'elementary', 'test', 'example', 'aabbccddeeff']) == 6" ] }, @@ -238,9 +238,9 @@ "outputs": [], "source": [ "\"\"\"Sample Dictionary\"\"\"\n", - "dic1={1:10, 2:20}\n", - "dic2={3:30, 4:40}\n", - "dic3={5:50,6:60}\n", + "dic1 = {1:10, 2:20}\n", + "dic2 = {3:30, 4:40}\n", + "dic3 = {5:50,6:60}\n", "\"\"\"\"Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}\"\"\"" ] }, @@ -289,8 +289,8 @@ "metadata": {}, "outputs": [], "source": [ - "assert (convert_to_palindrome('AAAACACBA') == 'AACABACAA')\n", - "assert (convert_to_palindrome('AAAACACBA') == 'IMPOSSIBLE')" + "assert (convert_to_palindrome('AAAACACBA') == convert_to_palindrome('AAAACACBA')[::-1])\n", + "assert (convert_to_palindrome('AAAACADBA') == 'IMPOSSIBLE')" ] }, { @@ -313,7 +313,7 @@ "metadata": {}, "outputs": [], "source": [ - "assert (get_unique_elements([1, 2, 2, 'a', 'a', 'a', 'g', 5]) == [1, 2, 'a', 'g', 5])" + "assert (set(get_unique_elements([1, 2, 2, 'a', 'a', 'a', 'g', 5])) == set([1, 2, 'a', 'g', 5]))" ] }, { @@ -428,7 +428,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3.10.4 64-bit", + "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, @@ -442,9 +442,8 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.4" + "version": "3.9.13" }, - "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1" @@ -452,5 +451,5 @@ } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/day01/tasks_for_datatypes_correc.ipynb b/day01/tasks_for_datatypes_correc.ipynb index 3b1c8f9..b369498 100644 --- a/day01/tasks_for_datatypes_correc.ipynb +++ b/day01/tasks_for_datatypes_correc.ipynb @@ -1,784 +1,812 @@ { - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "id": "GSkbRHlGws10" - }, - "source": [ - "# Datatypes exercises" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "cyciiVDiws12" - }, - "source": [ - "## Exercise 1" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "XuKy9qOYws13" - }, - "source": [ - "Write the following mathematical formula in Python:\n", - "\n", - "\\begin{align}\n", - " result = 6a^3 - \\frac{8b^2 }{4c} + 11\n", - "\\end{align}\n", - "\n", - "```python\n", - "a = 2\n", - "b = 3\n", - "c = 2\n", - "```\n", - "\n", - "> write your formula as \n", - "```python\n", - "result = \n", - "```\n", - "\n", - "It must verify\n", - "```python\n", - ">>> assert result == 50" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "id": "yGLAcZZ4ws14" - }, - "outputs": [], - "source": [ - "a = 2\n", - "b = 3\n", - "c = 2\n", - "result = 6 * a**3 - (8*b**2/(4*c)) +11\n", - "assert result == 50" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "KYseNonCws14" - }, - "source": [ - "## Exercise 2" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "3IOAPCc8ws14" - }, - "source": [ - "Explain why the folowing assertion fails" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "id": "5IupRUFqws15" - }, - "outputs": [], - "source": [ - "assert (0.1 + 0.2 - 0.3 < 10**-6) # will cause assertion error" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "JVwcmH6tws15" - }, - "source": [ - "## Exercise 3" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "Ttxpe883ws15" - }, - "source": [ - "Write a function `sum_list` to sum all the items in a list" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "id": "ix899nWbws15", - "outputId": "e8582883-6298-435c-edf9-b67a63886c03", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "29\n" - ] - } - ], - "source": [ - "def sum_list(x):\n", - " total = 0\n", - " for val in x:\n", - " total += val\n", - " return total\n", - "\n", - "print(sum([10, 20, -1]))\n", - "assert sum_list([10, 20, -1]) == 29" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "wqGFGN_kws15" - }, - "source": [ - "## Exercise 4" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "FX-cL1w2ws15" - }, - "source": [ - "Write a program that asks how long it took to run 10 km today. The program continues to ask how long (in minutes) it took for additional runs, until the user enters q. At that point, the program exits — but only after calculating and displaying the average time that the 10 km run took. \n", - "\n", - "\n", - "Example:\n", - "```\n", - "Enter 10 km run time: 15\n", - "Enter 10 km run time: 20\n", - "Enter 10 km run time: 10\n", - "Enter 10 km run time: q\n", - "\n", - "Average of 15.0, over 3 runs\n", - "```" - ] - }, - { - "cell_type": "code", - "source": [ - "lst = []\n", - "while True:\n", - " s = input('Enter 10 km run time:')\n", - " if s == 'q':\n", - " break\n", - " lst.append(int(s))\n", - "\n", - "print(f'Average of {sum(lst)/len(lst)}, over {len(lst)} runs')\n", - " " - ], - "metadata": { - "id": "rnJKF4VlyOxt", - "outputId": "1966f11f-cccd-4acc-b410-eaadfb2941f3", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "execution_count": 12, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Enter 10 km run time:15\n", - "Enter 10 km run time:20\n", - "Enter 10 km run time:10\n", - "Enter 10 km run time:q\n", - "Average of 15.0, over 3 runs\n" - ] - } - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "4nzlcSPkws2B" - }, - "source": [ - "## Exercise 5" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "1hxfDLBCws2B" - }, - "source": [ - "Write a function that takes a string and returns the sorted string." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": { - "id": "SOIRP4Tmws2C" - }, - "outputs": [], - "source": [ - "def sort_string(s):\n", - " x = sorted(\"cabaeb\")\n", - " return ''.join(x)\n", - "assert sort_string(\"cabaeb\") == \"aabbce\"" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "J6fGHElgws2C" - }, - "source": [ - "## Exercise 6" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "5iWp909Vws2C" - }, - "source": [ - "Write a function that take a string of multiple words and returns the position of the word with most repeated letters" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": { - "id": "zOVdEy_wws2C" - }, - "outputs": [], - "source": [ - "def wwmrl(s):\n", - " best = 0\n", - " pos = 0\n", - " for idx, word in enumerate(s):\n", - " dist = len(set(list(word)))\n", - " doub = len(word) - dist\n", - " if doub > best:\n", - " best = doub\n", - " pos = idx\n", - " return pos \n", - " \n", - "assert wwmrl(['this', 'is', 'an', 'elementary', 'aaaaaaaaaaaaaaaaaaaaaaaaaa', 'example', 'aabbccddeeff']) == 4" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "0GPdBP4Kws2D" - }, - "source": [ - "## Exercise 7" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "4ZT7-DK4ws2D" - }, - "source": [ - "1. Create a tuple\n", - "2. Unpack the tuple in multiple variables" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "metadata": { - "id": "x-OT3tN2ws2D", - "outputId": "915a85ee-eff5-4fac-f412-73321f951c83", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "('12.20', 7)\n" - ] - } - ], - "source": [ - "t = ('item1', '12.20', 7, True, False, 1)\n", - "s = t[1:3]\n", - "print(s)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "Q8Nc4IQVws2D" - }, - "source": [ - "## Exercise 8" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "Trk7ohlrws2D" - }, - "source": [ - "Write a Python program to sort a tuple by its float element. \n", - "Sample data: `[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]` \n", - "Expected Output: `[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]`" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "metadata": { - "id": "0lQHSpdQws2E", - "outputId": "31552ed1-0577-468f-d556-15d27f888502", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - "[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]" - ] - }, - "metadata": {}, - "execution_count": 44 - } - ], - "source": [ - "y = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]\n", - "# Methode 1\n", - "def s(x):\n", - " return float(x[1])\n", - "sorted(y,key=s, reverse=True)\n", - "# Methode 2\n", - "sorted(y,key=lambda x : float(x[1]), reverse=True)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "z141YpVSws2E" - }, - "source": [ - "## Exercise 9" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "ZXP_FuCvws2E" - }, - "source": [ - "Write a Python script to concatenate dictionaries to create a new one." - ] - }, - { - "cell_type": "code", - "execution_count": 55, - "metadata": { - "id": "-U142XmPws2F", - "outputId": "3df9bd17-a38d-4599-fac7-f86754011e1a", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "{1: 10, 6: 60, 3: 30, 4: 40, 2: 20}\n" - ] - } - ], - "source": [ - "\"\"\"Sample Dictionary\"\"\"\n", - "dic1={1:10, 2:20}\n", - "dic2={3:30, 4:40}\n", - "dic3={1:50,6:60}\n", - "#Method 1\n", - "dic = {**dic1, **dic2, **dic3}\n", - "print(dic)\n", - "#Method 2\n", - "for d in [dic1, dic2,dic3]:\n", - " dic.update(d)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "dC0o9SF-ws2F" - }, - "source": [ - "## Exercise 10" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "c2nYvOtUws2F" - }, - "source": [ - "Write a Python program to combine two dictionary adding values for common keys." - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "metadata": { - "id": "rp8Zm-GNws2F", - "outputId": "befebcb1-ef5d-458e-e2c1-a9ee274af6ad", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "{'a': 300, 'b': 200, 'c': 300, 'd': 400}\n", - "{'a': 400, 'b': 400, 'c': 300, 'd': 400}\n" - ] - } - ], - "source": [ - "d1 = {'a': 100, 'b': 200, 'c':300}\n", - "d2 = {'a': 300, 'b': 200, 'd':400}\n", - "d = {**d1, **d2}\n", - "print(d)\n", - "for key in d:\n", - " if key in d1 and key in d2:\n", - " d[key] = d1[key] + d2[key]\n", - "print(d)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "qK_IEkq5ws2G" - }, - "source": [ - "## Exercise 11" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "OmHvsY0hws2G" - }, - "source": [ - "Write a function `convert_to_palindrome` that takes a string and reorders its letters in such a way that it becomes a palindrome (i.e., it reads the same forwards and backwards). If this is not possible return `IMPOSSIBLE`" - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "metadata": { - "id": "u9KSyLU5ws2G", - "outputId": "25531617-7bfe-4063-93bc-435099891fae", - "colab": { - "base_uri": "https://localhost:8080/", - "height": 36 - } - }, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - "'CAAABAAAC'" - ], - "application/vnd.google.colaboratory.intrinsic+json": { - "type": "string" - } - }, - "metadata": {}, - "execution_count": 61 - } - ], - "source": [ - "def convert_to_palindrome(s):\n", - " d = {}\n", - " for c in set(s):\n", - " d[c] = s.count(c)\n", - " odd_cnt = 0\n", - " t = ('',0)\n", - " for key, val in d.items():\n", - " if val % 2 == 1:\n", - " odd_cnt += 1\n", - " t = (key, val)\n", - " if odd_cnt > 1:\n", - " return \"IMPOSSIBLE\"\n", - " part1 = ''\n", - " for key, val in d.items():\n", - " if val % 2 == 0:\n", - " part1 += key * (val//2) \n", - " return part1 + t[0] * t[1] + part1[::-1]\n", - "convert_to_palindrome('AAAACACBA')\n", - "#assert (convert_to_palindrome('AAAACACBA') == 'AACABACAA')\n", - "#assert (convert_to_palindrome('AAAACACBA') == 'IMPOSSIBLE')" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "mYferucOws2G" - }, - "source": [ - "# Exercise 12" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "kLKxJJ38ws2G" - }, - "source": [ - "Write a function `get_unique_elements` that takes a list and returns another list with only the distinct elements. For example, if you are given the list `[1, 3, 'a', 3, 'cd', 1, 'a']` you should return `[1, 3, 'a', 'cd']`" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "metadata": { - "id": "yipM4AoEws2G", - "outputId": "0572e2fb-c8ba-4291-ae08-528c384d9418", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - "[1, 2, 5, 'a', 'g']" - ] - }, - "metadata": {}, - "execution_count": 64 - } - ], - "source": [ - "def get_unique_elements(s):\n", - " return list(set(s))\n", - "get_unique_elements([1, 2, 2, 'a', 'a', 'a', 'g', 5])" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "aUOLI_61ws2H" - }, - "source": [ - "# Exercise 13" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "gcZ6nIh3ws2H" - }, - "source": [ - "Complete the dictionary `str_to_func` so that the following program will work correctly" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "-UVpe7Sows2H" - }, - "outputs": [], - "source": [ - "def sum(a, b):\n", - " return a + b\n", - "def sub(a, b):\n", - " return a - b\n", - "def mul(a, b):\n", - " return a * b\n", - "def div(a, b):\n", - " return a / b\n", - "def pow(a, b):\n", - " return a ** b\n", - "\n", - "str_to_func = {\n", - " '+' : sum,\n", - " '-' : sub,\n", - " '*' : mul,\n", - " '/' : div,\n", - " '**': pow\n", - "}\n", - "n1 = int(input('Enter first int'))\n", - "n2 = int(input('Enter Second int'))\n", - "op = input('Enter symbol') #possible symbols are +, -, *, /, **\n", - "print(str_to_func[op](n1, n2))" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "SVSSsOxZws2I" - }, - "source": [ - "# Exercise 14" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "lVBx52_9ws2I" - }, - "source": [ - "Using list comprehension, create a list containing only the words longer than `11` characters from the string `s`" - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "metadata": { - "id": "ZsXfI8oews2I" - }, - "outputs": [], - "source": [ - "s = \"\"\"Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,\n", - "molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum\n", - "numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium\n", - "optio, eaque rerum! Provident similique accusantium nemo autem. Veritatis\n", - "obcaecati tenetur iure eius earum ut molestias architecto voluptate aliquam\n", - "nihil, eveniet aliquid culpa officia aut! Impedit sit sunt quaerat, odit,\n", - "tenetur error, harum nesciunt ipsum debitis quas aliquid. Reprehenderit,\n", - "quia. Quo neque error repudiandae fuga? Ipsa laudantium molestias eos \n", - "sapiente officiis modi at sunt excepturi expedita sint? Sed quibusdam\n", - "recusandae alias error harum maxime adipisci amet laborum. Perspiciatis \n", - "minima nesciunt dolorem! Officiis iure rerum voluptates a cumque velit \n", - "quibusdam sed amet tempora. Sit laborum ab, eius fugit doloribus tenetur \n", - "fugiat, temporibus enim commodi iusto libero magni deleniti quod quam \n", - "consequuntur! Commodi minima excepturi repudiandae velit hic maxime\n", - "doloremque. Quaerat provident commodi consectetur veniam similique ad \n", - "earum omnis ipsum saepe, voluptas, hic voluptates pariatur est explicabo \n", - "fugiat, dolorum eligendi quam cupiditate excepturi mollitia maiores labore \n", - "suscipit quas? Nulla, placeat. Voluptatem quaerat non architecto ab laudantium\n", - "modi minima sunt esse temporibus sint culpa, recusandae aliquam numquam \n", - "totam ratione voluptas quod exercitationem fuga. Possimus quis earum veniam \n", - "quasi aliquam eligendi, placeat qui corporis!\n", - "\"\"\"\n", - "0,1,4,9,16,49\n", - "lst = []\n", - "for x in range(8):\n", - " lst.append(x**2)\n", - "#list comprehension\n", - "lst = [x**2 for x in range(8)]\n", - "res = [word for word in s.split() if len(word) > 11]\n", - "res = []\n", - "for word in s.split():\n", - " if len(word) > 11:\n", - " res.append(word)\n", - "# store your answer in the variable res\n", - "assert(res == ['consequuntur', 'Reprehenderit,', 'Perspiciatis', 'consequuntur!', 'exercitationem'])" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "QQdDjHEGws2I" - }, - "source": [ - "# Exercise 15" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "eUOqABU2ws2J" - }, - "source": [ - "The number `1655172` is actually equal to `a * 7 + b * 11`. Can you find `a` and `b`?" - ] + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "GSkbRHlGws10" + }, + "source": [ + "# Datatypes exercises" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "cyciiVDiws12" + }, + "source": [ + "## Exercise 1" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "XuKy9qOYws13" + }, + "source": [ + "Write the following mathematical formula in Python:\n", + "\n", + "\\begin{align}\n", + " result = 6a^3 - \\frac{8b^2 }{4c} + 11\n", + "\\end{align}\n", + "\n", + "```python\n", + "a = 2\n", + "b = 3\n", + "c = 2\n", + "```\n", + "\n", + "> write your formula as \n", + "```python\n", + "result = \n", + "```\n", + "\n", + "It must verify\n", + "```python\n", + ">>> assert result == 50" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "id": "yGLAcZZ4ws14" + }, + "outputs": [], + "source": [ + "a = 2\n", + "b = 3\n", + "c = 2\n", + "result = 6 * a**3 - (8*b**2/(4*c)) +11\n", + "assert result == 50" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "KYseNonCws14" + }, + "source": [ + "## Exercise 2" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "3IOAPCc8ws14" + }, + "source": [ + "Explain why the folowing assertion fails" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "id": "5IupRUFqws15" + }, + "outputs": [], + "source": [ + "assert (0.1 + 0.2 - 0.3 < 10**-6) # will cause assertion error" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "JVwcmH6tws15" + }, + "source": [ + "## Exercise 3" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Ttxpe883ws15" + }, + "source": [ + "Write a function `sum_list` to sum all the items in a list" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "ix899nWbws15", + "outputId": "e8582883-6298-435c-edf9-b67a63886c03" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "29\n" + ] + } + ], + "source": [ + "def sum_list(x):\n", + " total = 0\n", + " for val in x:\n", + " total += val\n", + " return total\n", + "\n", + "print(sum([10, 20, -1]))\n", + "assert sum_list([10, 20, -1]) == 29" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "wqGFGN_kws15" + }, + "source": [ + "## Exercise 4" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "FX-cL1w2ws15" + }, + "source": [ + "Write a program that asks how long it took to run 10 km today. The program continues to ask how long (in minutes) it took for additional runs, until the user enters q. At that point, the program exits — but only after calculating and displaying the average time that the 10 km run took. \n", + "\n", + "\n", + "Example:\n", + "```\n", + "Enter 10 km run time: 15\n", + "Enter 10 km run time: 20\n", + "Enter 10 km run time: 10\n", + "Enter 10 km run time: q\n", + "\n", + "Average of 15.0, over 3 runs\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "rnJKF4VlyOxt", + "outputId": "1966f11f-cccd-4acc-b410-eaadfb2941f3" + }, + "outputs": [ + { + "name": "stdin", + "output_type": "stream", + "text": [ + "Enter 10 km run time: 15\n", + "Enter 10 km run time: 20\n", + "Enter 10 km run time: 10\n", + "Enter 10 km run time: q\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Average of 15.0, over 3 runs\n" + ] + } + ], + "source": [ + "lst = []\n", + "while True:\n", + " s = input('Enter 10 km run time:')\n", + " if s == 'q':\n", + " break\n", + " lst.append(int(s))\n", + "\n", + "print(f'Average of {sum(lst)/len(lst)}, over {len(lst)} runs')\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "4nzlcSPkws2B" + }, + "source": [ + "## Exercise 5" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1hxfDLBCws2B" + }, + "source": [ + "Write a function that takes a string and returns the sorted string." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "id": "SOIRP4Tmws2C" + }, + "outputs": [], + "source": [ + "def sort_string(s):\n", + " x = sorted(\"cabaeb\")\n", + " return ''.join(x)\n", + "assert sort_string(\"cabaeb\") == \"aabbce\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "J6fGHElgws2C" + }, + "source": [ + "## Exercise 6" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "5iWp909Vws2C" + }, + "source": [ + "Write a function that take a string of multiple words and returns the position of the word with most repeated letters" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "id": "zOVdEy_wws2C" + }, + "outputs": [], + "source": [ + "def wwmrl(s):\n", + " best = 0\n", + " pos = 0\n", + " for idx, word in enumerate(s):\n", + " dist = len(set(list(word)))\n", + " doub = len(word) - dist\n", + " if doub > best:\n", + " best = doub\n", + " pos = idx\n", + " return pos \n", + " \n", + "assert wwmrl(['this', 'is', 'an', 'elementary', 'test', 'example', 'aabbccddeeff']) == 6" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0GPdBP4Kws2D" + }, + "source": [ + "## Exercise 7" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "4ZT7-DK4ws2D" + }, + "source": [ + "1. Create a tuple\n", + "2. Unpack the tuple in multiple variables" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "x-OT3tN2ws2D", + "outputId": "915a85ee-eff5-4fac-f412-73321f951c83" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "7\n" + ] + } + ], + "source": [ + "t = ('item1', '12.20', 7, True, False, 1)\n", + "a, b, c, d, e, f = t\n", + "print(c)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Q8Nc4IQVws2D" + }, + "source": [ + "## Exercise 8" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Trk7ohlrws2D" + }, + "source": [ + "Write a Python program to sort a tuple by its float element. \n", + "Sample data: `[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]` \n", + "Expected Output: `[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]`" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" }, + "id": "0lQHSpdQws2E", + "outputId": "31552ed1-0577-468f-d556-15d27f888502" + }, + "outputs": [ { - "cell_type": "code", - "execution_count": 73, - "metadata": { - "id": "OYcNKxE1ws2J", - "outputId": "f552294a-000f-4bb7-8191-bdb7e3e853c1", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "5 150467\n" - ] - } - ], - "source": [ - "# your code here\n", - "n = 1655172\n", - "for a in range(n//7): \n", - " if (n - a * 7) % 11 == 0:\n", - " print(a, (n -a *7) //11)\n", - " break\n" + "data": { + "text/plain": [ + "[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]" ] - }, - { - "cell_type": "code", - "source": [], - "metadata": { - "id": "JGp4FhsTHIum" - }, - "execution_count": null, - "outputs": [] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.10.4 64-bit", - "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.10.4" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1" - } - }, + ], + "source": [ + "y = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]\n", + "# Methode 1\n", + "def s(x):\n", + " return float(x[1])\n", + "sorted(y,key=s, reverse=True)\n", + "\n", + "# Methode 2: using lambda notation\n", + "sorted(y,key=lambda x : float(x[1]), reverse=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "z141YpVSws2E" + }, + "source": [ + "## Exercise 9" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ZXP_FuCvws2E" + }, + "source": [ + "Write a Python script to concatenate dictionaries to create a new one." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "-U142XmPws2F", + "outputId": "3df9bd17-a38d-4599-fac7-f86754011e1a" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{1: 50, 2: 20, 3: 30, 4: 40, 6: 60}\n", + "{1: 50, 2: 20, 3: 30, 4: 40, 6: 60}\n" + ] + } + ], + "source": [ + "\"\"\"Sample Dictionary\"\"\"\n", + "dic1 = {1:10, 2:20}\n", + "dic2 = {3:30, 4:40}\n", + "dic3 = {1:50,6:60}\n", + "#Method 1\n", + "dic = {**dic1, **dic2, **dic3}\n", + "print(dic)\n", + "\n", + "#Method 2\n", + "dic = {}\n", + "for d in [dic1, dic2,dic3]:\n", + " dic.update(d)\n", + "print(dic)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "dC0o9SF-ws2F" + }, + "source": [ + "## Exercise 10" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "c2nYvOtUws2F" + }, + "source": [ + "Write a Python program to combine two dictionary adding values for common keys." + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { "colab": { - "provenance": [] + "base_uri": "https://localhost:8080/" + }, + "id": "rp8Zm-GNws2F", + "outputId": "befebcb1-ef5d-458e-e2c1-a9ee274af6ad" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'a': 300, 'b': 200, 'c': 300, 'd': 400}\n", + "{'a': 400, 'b': 400, 'c': 300, 'd': 400}\n" + ] } + ], + "source": [ + "d1 = {'a': 100, 'b': 200, 'c':300}\n", + "d2 = {'a': 300, 'b': 200, 'd':400}\n", + "d = {**d1, **d2}\n", + "print(d)\n", + "for key in d:\n", + " if key in d1 and key in d2:\n", + " d[key] = d1[key] + d2[key]\n", + "print(d)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# method 2\n", + "d1 = {'a': 100, 'b': 200, 'c':300}\n", + "d2 = {'a': 300, 'b': 200, 'd':400}\n", + "d = {}\n", + "keys = set(d1.keys()) | set(d2.keys()) # get all unique keys\n", + "for k in keys:\n", + " d[k] = d1.get(k, 0) + d2.get(k, 0) # get method return second params if key not found in dictionary\n", + "print(d)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "qK_IEkq5ws2G" + }, + "source": [ + "## Exercise 11" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "OmHvsY0hws2G" + }, + "source": [ + "Write a function `convert_to_palindrome` that takes a string and reorders its letters in such a way that it becomes a palindrome (i.e., it reads the same forwards and backwards). If this is not possible return `IMPOSSIBLE`" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 36 + }, + "id": "u9KSyLU5ws2G", + "outputId": "25531617-7bfe-4063-93bc-435099891fae" + }, + "outputs": [], + "source": [ + "def convert_to_palindrome(s):\n", + " d = {}\n", + " for c in set(s):\n", + " d[c] = s.count(c)\n", + " odd_cnt = 0\n", + " t = ('',0)\n", + " for key, val in d.items():\n", + " if val % 2 == 1:\n", + " odd_cnt += 1\n", + " t = (key, val)\n", + " if odd_cnt > 1:\n", + " return \"IMPOSSIBLE\"\n", + " part1 = ''\n", + " for key, val in d.items():\n", + " if val % 2 == 0:\n", + " part1 += key * (val//2) \n", + " return part1 + t[0] * t[1] + part1[::-1]\n", + "convert_to_palindrome('AAAACACBA')\n", + "\n", + "assert (convert_to_palindrome('AAAACACBA') == convert_to_palindrome('AAAACACBA')[::-1])\n", + "assert (convert_to_palindrome('AAAACADBA') == 'IMPOSSIBLE')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "mYferucOws2G" + }, + "source": [ + "# Exercise 12" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "kLKxJJ38ws2G" + }, + "source": [ + "Write a function `get_unique_elements` that takes a list and returns another list with only the distinct elements. For example, if you are given the list `[1, 3, 'a', 3, 'cd', 1, 'a']` you should return `[1, 3, 'a', 'cd']`" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "yipM4AoEws2G", + "outputId": "0572e2fb-c8ba-4291-ae08-528c384d9418" + }, + "outputs": [], + "source": [ + "def get_unique_elements(s):\n", + " return list(set(s))\n", + "get_unique_elements([1, 2, 2, 'a', 'a', 'a', 'g', 5])\n", + "\n", + "assert (set(get_unique_elements([1, 2, 2, 'a', 'a', 'a', 'g', 5])) == set([1, 2, 'a', 'g', 5]))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "aUOLI_61ws2H" + }, + "source": [ + "# Exercise 13" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "gcZ6nIh3ws2H" + }, + "source": [ + "Complete the dictionary `str_to_func` so that the following program will work correctly" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "-UVpe7Sows2H" + }, + "outputs": [], + "source": [ + "def sum(a, b):\n", + " return a + b\n", + "def sub(a, b):\n", + " return a - b\n", + "def mul(a, b):\n", + " return a * b\n", + "def div(a, b):\n", + " return a / b\n", + "def pow(a, b):\n", + " return a ** b\n", + "\n", + "str_to_func = {\n", + " '+' : sum,\n", + " '-' : sub,\n", + " '*' : mul,\n", + " '/' : div,\n", + " '**': pow\n", + "}\n", + "n1 = int(input('Enter first int'))\n", + "n2 = int(input('Enter Second int'))\n", + "op = input('Enter symbol') #possible symbols are +, -, *, /, **\n", + "print(str_to_func[op](n1, n2))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "SVSSsOxZws2I" + }, + "source": [ + "# Exercise 14" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "lVBx52_9ws2I" + }, + "source": [ + "Using list comprehension, create a list containing only the words longer than `11` characters from the string `s`" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "id": "ZsXfI8oews2I" + }, + "outputs": [], + "source": [ + "s = \"\"\"Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,\n", + "molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum\n", + "numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium\n", + "optio, eaque rerum! Provident similique accusantium nemo autem. Veritatis\n", + "obcaecati tenetur iure eius earum ut molestias architecto voluptate aliquam\n", + "nihil, eveniet aliquid culpa officia aut! Impedit sit sunt quaerat, odit,\n", + "tenetur error, harum nesciunt ipsum debitis quas aliquid. Reprehenderit,\n", + "quia. Quo neque error repudiandae fuga? Ipsa laudantium molestias eos \n", + "sapiente officiis modi at sunt excepturi expedita sint? Sed quibusdam\n", + "recusandae alias error harum maxime adipisci amet laborum. Perspiciatis \n", + "minima nesciunt dolorem! Officiis iure rerum voluptates a cumque velit \n", + "quibusdam sed amet tempora. Sit laborum ab, eius fugit doloribus tenetur \n", + "fugiat, temporibus enim commodi iusto libero magni deleniti quod quam \n", + "consequuntur! Commodi minima excepturi repudiandae velit hic maxime\n", + "doloremque. Quaerat provident commodi consectetur veniam similique ad \n", + "earum omnis ipsum saepe, voluptas, hic voluptates pariatur est explicabo \n", + "fugiat, dolorum eligendi quam cupiditate excepturi mollitia maiores labore \n", + "suscipit quas? Nulla, placeat. Voluptatem quaerat non architecto ab laudantium\n", + "modi minima sunt esse temporibus sint culpa, recusandae aliquam numquam \n", + "totam ratione voluptas quod exercitationem fuga. Possimus quis earum veniam \n", + "quasi aliquam eligendi, placeat qui corporis!\n", + "\"\"\"\n", + "# store your answer in the variable res\n", + "# Using for loop method\n", + "for word in s.split():\n", + " if len(word) > 11:\n", + " res.append(word)\n", + " \n", + "# Using list comprehension\n", + "res = []\n", + "res = [word for word in s.split() if len(word) > 11]\n", + "\n", + "assert(res == ['consequuntur', 'Reprehenderit,', 'Perspiciatis', 'consequuntur!', 'exercitationem'])" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "QQdDjHEGws2I" + }, + "source": [ + "# Exercise 15" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "eUOqABU2ws2J" + }, + "source": [ + "The number `1655172` is actually equal to `a * 7 + b * 11`. Can you find `a` and `b`?" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "OYcNKxE1ws2J", + "outputId": "f552294a-000f-4bb7-8191-bdb7e3e853c1" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "We get: a=5 , b=150467, after 6 tries\n" + ] + } + ], + "source": [ + "# your code here\n", + "n = 1655172\n", + "n_itr = 0\n", + "for a in range(n // 7):\n", + " n_itr += 1\n", + " if (n - a * 7) % 11 == 0:\n", + " b = (n - 7 * a) // 11\n", + " break\n", + " \n", + "print(f\"We get: {a=} , {b=}, after {n_itr} tries\")\n", + "assert (a * 7 + b * 11 == 1655172), \"Nope! 'a' and 'b' are incorrect. Change your algorithm!\"" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "id": "JGp4FhsTHIum" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "We get: a=236450 , b=2, after 2 tries\n" + ] + } + ], + "source": [ + "# Second technic\n", + "n = 1_655_172\n", + "a, b = 0, 0\n", + "n_itr = 0\n", + "\n", + "while 7 * a + b * 11 != n:\n", + " n_itr += 1\n", + " b += 1\n", + " a = (n - (b * 11)) // 7\n", + " \n", + "print(f\"We get: {a=} , {b=}, after {n_itr} tries\")\n", + "assert (a * 7 + b * 11 == 1655172), \"Nope! 'a' and 'b' are incorrect. Change your algorithm!\"" + ] + } + ], + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.9.13" }, - "nbformat": 4, - "nbformat_minor": 0 -} \ No newline at end of file + "vscode": { + "interpreter": { + "hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1" + } + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/day01/tasks_for_day_01.ipynb b/day01/tasks_for_day_01.ipynb index df2f88a..feb97fe 100644 --- a/day01/tasks_for_day_01.ipynb +++ b/day01/tasks_for_day_01.ipynb @@ -615,7 +615,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.2" + "version": "3.9.13" } }, "nbformat": 4, diff --git a/day01/tasks_for_day_01_correc.ipynb b/day01/tasks_for_day_01_correc.ipynb index f59dbaa..89d6c3a 100644 --- a/day01/tasks_for_day_01_correc.ipynb +++ b/day01/tasks_for_day_01_correc.ipynb @@ -1,1055 +1,918 @@ { - "cells": [ - { - "cell_type": "markdown", - "id": "c58884ae", - "metadata": { - "id": "c58884ae" - }, - "source": [ - "# Exercise 01: Standard output" - ] - }, - { - "cell_type": "markdown", - "id": "98a55ba6", - "metadata": { - "id": "98a55ba6" - }, - "source": [ - "1. Print your name on the standard Output using the function `print`.\n", - "2. Print your name, age and city each in a separate line.\n", - "3. Print your name, age and city In a single line\n", - "4. In a meaningful sentence Print your name, age and city in a single line" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "7ec3cd3f", - "metadata": { - "id": "7ec3cd3f", - "outputId": "9c15173c-4c2f-4500-ccf9-65088c3aa6b7", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Ahmed-Ahmed\n", - "25\n", - "Casablanca\n", - "Ahmed*25*Casablanca\n", - "my name is Casablanca, I am 25, and I am from Ahmed\n" - ] - } - ], - "source": [ - "name = 'Ahmed'\n", - "age = 25\n", - "city = 'Casablanca'\n", - "print(name, end='-')\n", - "print(name)\n", - "print(age)\n", - "print(city)\n", - "print(name, age, city, sep='*')\n", - "print('my name is {2}, I am {1}, and I am from {0}'.format(name, age, city))" - ] - }, - { - "cell_type": "markdown", - "id": "4eb25b0a", - "metadata": { - "id": "4eb25b0a" - }, - "source": [ - "# Exercise 02: Variables" - ] - }, - { - "cell_type": "markdown", - "id": "75b5ed2c", - "metadata": { - "id": "75b5ed2c" - }, - "source": [ - "Consider the following statements (remember a statement is a line of code the interpreter can execute. `x = 1` is an expression that stores the value `1` into `x`):\n", - "1. Print the summation, subtruction, multiplication and division of `x` and `y` each in a separate line without using any other variables.\n", - "2. Store the summation, subtruction, multiplication and division of `x` and `y` each in a separate variable, print those variables each in a separate line." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "3c382322", - "metadata": { - "id": "3c382322", - "outputId": "52128027-fc92-4243-a067-9e73a7004a2c", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "3\n", - "-1\n", - "2\n", - "0.5\n", - "0\n", - "3\n", - "-1\n", - "2\n", - "0.5\n", - "3\n", - "-1\n", - "2\n", - "0.5\n" - ] - } - ], - "source": [ - "x = 1\n", - "y = 2\n", - "print(x+y)\n", - "print(x-y)\n", - "print(x * y)\n", - "print(x/y)\n", - "print(x//y)\n", - "sum = x + y\n", - "diff = x - y\n", - "prod = x * y\n", - "div = x / y\n", - "print(sum)\n", - "print(diff)\n", - "print(prod)\n", - "print(div)\n", - "print(sum, diff, prod, div, sep='\\n')" - ] - }, - { - "cell_type": "markdown", - "id": "fcd700f5", - "metadata": { - "id": "fcd700f5" - }, - "source": [ - "# Exercise 03: Variables" - ] - }, - { - "cell_type": "markdown", - "id": "a608bd37", - "metadata": { - "id": "a608bd37" - }, - "source": [ - "Consider the following statements:\n", - "1. Swap the values of `x` and `y` . *`x` should store the value of `y` and `y` should store the value of `x`*\n", - "2. Store the sum of `x` and `y` into `x` and their subtraction into `y`" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "28aba62a", - "metadata": { - "id": "28aba62a", - "outputId": "59ca51ef-f99a-4391-968f-c4eb6f4a186a", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "55 -11\n" - ] - } - ], - "source": [ - "x = 22\n", - "y = 33\n", - "\n", - "#x, y = y, x\n", - "x, y = x + y, x - y\n", - "print(x, y)" - ] - }, - { - "cell_type": "markdown", - "id": "cdddaca1", - "metadata": { - "id": "cdddaca1" - }, - "source": [ - "# Exercise 04: Conditions" - ] - }, - { - "cell_type": "markdown", - "id": "9fa90c43", - "metadata": { - "id": "9fa90c43" - }, - "source": [ - "Consider the following statements\n", - "1. Write an **if statement** to check if `x` is equal to `y` if so print `\"x and y are equal\"` otherwise print `\"x and y are not equal\"`\n", - "2. Write an **if statement** to check if `x` is equal to `z` if so print `\"x and z are equal\"` otherwise print `\"x and z are not equal\"`\n", - "3. Write an **if statement** to check if either `x` is equal `y` or `x` is equal to `z` if so print `x is equal to y or z` otherwise print `\"x is equal to neither y nor z\"`\n", - "4. Write an **if statement** to check if `x` is equal to both `y` and `z` if so print `x is equal to both y and z` otherwise print `\"x is equal to neither y nor z\"`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "83d12754", - "metadata": { - "id": "83d12754", - "outputId": "e82ad424-5823-451b-8e98-e9c1a7d16116" - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3 is equal to 3 or 4 is equal to 1\n" - ] - } - ], - "source": [ - "x = 1\n", - "y = 2\n", - "z = 1\n", - "\n", - "if x == y:\n", - " print('x and y are equal')\n", - "else:\n", - " print('x and y are not equal')\n", - "\n", - "if x == z:\n", - " print('x and z are equal')\n", - "else:\n", - " print('x and z are not equal')\n", - "\n", - "if x == y or x == z:\n", - " print('x is equal to y or z')\n", - "else:\n", - " print('x is equal to neither y nor z')\n", - "\n", - "if x == y and x == z:\n", - " print('x is equal to both y and z')\n", - "else:\n", - " print('x is equal to neither y nor z')" - ] - }, - { - "cell_type": "markdown", - "id": "492aaed0", - "metadata": { - "id": "492aaed0" - }, - "source": [ - "# Exercise 05: Conditions" - ] - }, - { - "cell_type": "markdown", - "id": "302e1350", - "metadata": { - "id": "302e1350" - }, - "source": [ - "Consider the following statements:\n", - "1. Using the modulo operator `%`, check each variable if it is divisible by two and print some useful output.\n", - "2. Using the modulo operator `%`, check if at least one of the variables is divisible by two and print some useful output\n", - "3. Using the modulo operator `%`, check if all the variables ar divisible by two and print some useful output" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "3aaf1703", - "metadata": { - "id": "3aaf1703", - "outputId": "58649dc4-2f8b-4e20-ef53-a90542ad6b49", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "y is even\n", - "at least one variable is even\n" - ] - } - ], - "source": [ - "x = 9\n", - "y = 222\n", - "z = 3\n", - "\n", - "if x % 2 == 0:\n", - " print('x is even')\n", - "if y % 2 == 0:\n", - " print('y is even')\n", - "if z % 2 == 0:\n", - " print('z is even')\n", - "if x % 2 == 0 or y % 2 == 0 or z % 2 == 0:\n", - " print('at least one variable is even')\n", - "if x % 2 == 0 and y % 2 == 0 and z % 2 == 0:\n", - " print('all variables are even')" - ] - }, - { - "cell_type": "markdown", - "id": "053e15a4", - "metadata": { - "id": "053e15a4" - }, - "source": [ - "# Exercise 06: Variables and conditions" - ] - }, - { - "cell_type": "markdown", - "id": "3ecac2c0", - "metadata": { - "id": "3ecac2c0" - }, - "source": [ - "Consider the bellow statements:\n", - "- Write an **if else statement** to check wheter the variable `x` is even or odd, if it is even print `\"x is even\"` otherwise print `\"x is odd\"`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "938a6241", - "metadata": { - "id": "938a6241" - }, - "outputs": [], - "source": [ - "x = 66\n", - "\n", - "if x %2 == 0:\n", - " print('x is even')\n", - "else:\n", - " print('x is odd')" - ] - }, - { - "cell_type": "markdown", - "id": "13d33a69", - "metadata": { - "id": "13d33a69" - }, - "source": [ - "# Exercise 07: Variables and conditions" - ] - }, - { - "cell_type": "markdown", - "id": "e769faa4", - "metadata": { - "id": "e769faa4" - }, - "source": [ - "Consider the bellow code:\n", - "1. Only by looking at the code, can you tell the type of the variables `x` and `y`.\n", - "2. Print the type of the variables `x` and `y` using the function `type`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6112c1d9", - "metadata": { - "id": "6112c1d9" - }, - "outputs": [], - "source": [ - "x = True\n", - "y = False\n", - "\n", - "#Write your answer bellow" - ] - }, - { - "cell_type": "markdown", - "id": "ec61aee1", - "metadata": { - "id": "ec61aee1" - }, - "source": [ - "# Exercise 08: conditions" - ] - }, - { - "cell_type": "markdown", - "id": "328ff359", - "metadata": { - "id": "328ff359" - }, - "source": [ - "Consider the variable `x`:\n", - "- Using the modulo operator `%` and **if, elif, else** statements check if `x` is divisible by `2` if so print `\"x is divisible by 2\"` and check if `x` is divisible by `3` if so print `\"x is divisible by 3\"`, and check if `x` is divisible by `6` if so print `\"x is divisible by 6\"` else using a pass statement do nothing." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f9fc1065", - "metadata": { - "id": "f9fc1065" - }, - "outputs": [], - "source": [ - "x = 2322\n", - "if x % 2 == 0:\n", - " print('x is divisible by 2')\n", - "if x % 3 == 0:\n", - " print('x is divisible by 3')\n", - "if x % 6 == 0:\n", - " print('x is divisible by 6')\n", - "else:\n", - " pass" - ] - }, - { - "cell_type": "markdown", - "id": "bfe2c7b1", - "metadata": { - "id": "bfe2c7b1" - }, - "source": [ - "# Exercise 09: conditions" - ] - }, - { - "cell_type": "markdown", - "id": "2d173da8", - "metadata": { - "id": "2d173da8" - }, - "source": [ - "Consider the variable `x`:\n", - "- Using an **if statement** check if `x` is divisible by `2`and a **nested if statement** to check if it's divisible by `3`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e773f312", - "metadata": { - "id": "e773f312" - }, - "outputs": [], - "source": [ - "x = 8989\n", - "if x % 2 == 0:\n", - " print('x is divisible by 2')\n", - " if x % 3 == 0:\n", - " print('x is divisible by 3')" - ] - }, - { - "cell_type": "markdown", - "id": "1c40dbb2", - "metadata": { - "id": "1c40dbb2" - }, - "source": [ - "# Exercise 10: Variables and conditions" - ] - }, - { - "cell_type": "markdown", - "id": "a7f37439", - "metadata": { - "id": "a7f37439" - }, - "source": [ - "Consider following statements:\n", - "- Only by looking at the code, can you tell what would be printed. write your answer as comments next to each print statement.\n", - "- Explain the behavior, write your answer as comments at the end of the code." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4615cb39", - "metadata": { - "id": "4615cb39" - }, - "outputs": [], - "source": [ - "x = 3\n", - "y = 3.3\n", - "z = True\n", - "a = 'test'\n", - "#print(x is int)\n", - "#print(type(x) is int)\n", - "#print(type(y) is str)\n", - "#print(type(y) is float)\n", - "#print(type(z) is bool)\n", - "#print(type(a) is str)" - ] - }, - { - "cell_type": "markdown", - "id": "a854f619", - "metadata": { - "id": "a854f619" - }, - "source": [ - "# Exercise 11: Standard Input/Output" - ] - }, - { - "cell_type": "markdown", - "id": "2d941c03", - "metadata": { - "id": "2d941c03" - }, - "source": [ - "Create a program that takes an input from the user and print it in the standard output." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "cf96712f", - "metadata": { - "id": "cf96712f", - "outputId": "e89b474f-b6a0-49ac-ed9a-8093c381700a", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "enter a sentencehello\n", - "hello\n" - ] - } - ], - "source": [ - "line = input('enter a sentence')\n", - "print(line)" - ] - }, - { - "cell_type": "markdown", - "id": "ceaad399", - "metadata": { - "id": "ceaad399" - }, - "source": [ - "# Exercise 12: Standard I/O" - ] - }, - { - "cell_type": "markdown", - "id": "6a3b6743", - "metadata": { - "id": "6a3b6743" - }, - "source": [ - "Create a program that takes the name and age of the user from the standard input.\n", - " 1. If the user entered `\"hamid\"` and `\"23\"` print `hamis is 23`.\n", - " 2. Use the method `format` to do the same thing as above." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "48202165", - "metadata": { - "id": "48202165", - "outputId": "5fe4f58c-13ca-4b01-b9e7-2c932cb809b9", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "hamid 23\n", - "['hamid', '23']\n", - "hamid is 23\n" - ] - } - ], - "source": [ - "print(input().split(' '))\n", - "print(name + ' is '+ age)" - ] - }, - { - "cell_type": "markdown", - "id": "08d4179a", - "metadata": { - "id": "08d4179a" - }, - "source": [ - "# Exercise 13: Standard I/O" - ] - }, - { - "cell_type": "markdown", - "id": "5c56c31b", - "metadata": { - "id": "5c56c31b" - }, - "source": [ - "Create a program that takes an integer from the input and print its type.\n", - "- Run your code and enter the value `\"11\"`\n", - "- Run your code again and enter the value `test`\n", - "- Explain the output." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "6cdbc7f3", - "metadata": { - "id": "6cdbc7f3", - "outputId": "d922f88b-8517-499a-bcb5-a8e4a7046afa", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "123\n", - "\n" - ] - } - ], - "source": [ - "x = input()\n", - "print(type(x))" - ] - }, - { - "cell_type": "markdown", - "id": "be2f82d1", - "metadata": { - "id": "be2f82d1" - }, - "source": [ - "# Exrecise 14: Variables" - ] - }, - { - "cell_type": "markdown", - "id": "78976138", - "metadata": { - "id": "78976138" - }, - "source": [ - "1. Store the values `1`, `0.0`, `1j` and `\"this is a string\"` in the variables `a`, `b`, `c`, and `d` respectively.\n", - "2. Print the type of each variable using the function `type`.\n", - "3. \n", - " * Print the type of the following sums : `a + b` and `b + c`, and explain the behavior.\n", - " * Try summing `a` and `d`, and explain the behavior.\n", - "4. consider the two following strings `122` and `rrr`.\n", - " * Using `int` class constuctor try to convert the above strings to integer types.\n", - " * What do we call the above behavior\n", - " * *Don't worry about the term constructors we will get back to them later just use the syntax `int(122)`.*\n" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "0263f91e", - "metadata": { - "id": "0263f91e", - "outputId": "1b9b9c45-2dd5-445d-a0d3-92ad03595cae", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "122\n" - ] - } - ], - "source": [ - "a = 1\n", - "b = 0.0\n", - "c = 1j\n", - "d = 'this is a string'\n", - "print(type(a))\n", - "print(type(b))\n", - "print(type(c))\n", - "print(type(d))\n", - "print(type(a+b))\n", - "print(type(b+c))\n", - "s1 = '122'\n", - "s2 = 'rrr'\n", - "n1 = int(122.0)\n", - "print(n1)" - ] - }, - { - "cell_type": "markdown", - "id": "4a1a82eb", - "metadata": { - "id": "4a1a82eb" - }, - "source": [ - "# Exercise 15: Variables" - ] - }, - { - "cell_type": "markdown", - "id": "9d6ec9ad", - "metadata": { - "id": "9d6ec9ad" - }, - "source": [ - "Create a program that takes two strings from the user.\n", - "* Enter the values `122` and `rrr` and print their according types.\n", - "* Use the method `isdigit()` to make sure the input is a valid integer.\n", - " * *Don't worry about the term method just think of it as a special function that we call using the syntax `var.isdigit()` where var is a variable that stores some data*\n", - "* If the user entered invalid input print `\"invalid input\"` and terminate the program.\n", - "* If the user entered a valid input print the sum of the integers.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "92f1121a", - "metadata": { - "id": "92f1121a", - "outputId": "5636706c-e950-4739-dff6-dff301861139", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "4\n", - "r\n", - "invalid input\n" - ] - } - ], - "source": [ - "s1 = input()\n", - "s2 = input()\n", - "if s1.isdigit() and s2.isdigit():\n", - " n1 = int(s1)\n", - " n2 = int(s2)\n", - " print(n1 + n2)\n", - "else:\n", - " print('invalid input')" - ] - }, - { - "cell_type": "markdown", - "id": "dbb89719", - "metadata": { - "id": "dbb89719" - }, - "source": [ - "# Exercise 16: Conditions" - ] - }, - { - "cell_type": "markdown", - "id": "2515d3c1", - "metadata": { - "id": "2515d3c1" - }, - "source": [ - "- Create a program that reads from the standard input two integers and a binary operator (`+`,`-`,`/` or `*`) and prints the result of the opration on the two integers.\n", - " - Check the validity of the input, and print `\"Invalid input\"` if the input is not valid.\n", - " \n", - "- Rewrite the program so it can also take floats or complex numbers or any combinasion of the mentioned types.\n", - " - Check the validity of the input, and print `Invalid input` if the input is not valid." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "4e93835b", - "metadata": { - "id": "4e93835b", - "outputId": "a901929a-09b2-410d-c635-4a430b539c0d", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "0.4 0.7 *\n", - "0.27999999999999997\n" - ] - } - ], - "source": [ - "def isfloat(x):\n", - " try:\n", - " x = float(x)\n", - " return True\n", - " except:\n", - " return False\n", - "\n", - "\n", - "s1, s2, s3 = input().split(' ')\n", - "if not isfloat(s1) or not isfloat(s2) or not s3 in '+-/*':\n", - " print('invalid input')\n", - "n1 = float(s1)\n", - "n2 = float(s2)\n", - "if s3 == '+':\n", - " print(n1+n2)\n", - "elif s3 == '-':\n", - " print(n1-n2)\n", - "elif s3 == '/':\n", - " print(n1/n2)\n", - "elif s3 == '*':\n", - " print(n1*n2)" - ] - }, - { - "cell_type": "markdown", - "id": "ea65b58c", - "metadata": { - "id": "ea65b58c" - }, - "source": [ - "# Exercise 17: While loop" - ] - }, - { - "cell_type": "markdown", - "id": "dbbdd7a4", - "metadata": { - "id": "dbbdd7a4" - }, - "source": [ - "Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one. For example, the sequence for n=3 is as follows:
\n", - " `3→10→5→16→8→4→2→1`\n", - "- Create a program that reads the integer n from the standard input and simulates the execition of the algorithm for the given n by printing all the values in a single line.
\n", - " * Sample input:
\n", - " `3`\n", - " * Sample output:
\n", - " `3 10 5 16 8 4 2 1`" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "e996b286", - "metadata": { - "id": "e996b286", - "outputId": "25cc02b9-985d-45fc-d05b-b4060b71ddc9", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "1\n", - "1 " - ] - } - ], - "source": [ - "x = int(input())\n", - "while True:\n", - " print (x, end=' ')\n", - " if x == 1:\n", - " break\n", - " elif x % 2 == 0:\n", - " x //= 2\n", - " else:\n", - " x = 3 * x +1" - ] - }, - { - "cell_type": "markdown", - "id": "90671456", - "metadata": { - "id": "90671456" - }, - "source": [ - "## Exercise 18: For Loop" - ] - }, - { - "cell_type": "markdown", - "id": "29284bc1", - "metadata": { - "id": "29284bc1" - }, - "source": [ - "You are given a list of strings that contains some names.
\n", - "Finish up the code below so that it prints `Salam !` for each name in the list.\n", - "* Expected output:
\n", - " `Salam Omar!`
\n", - " `Salam Zineb!`
\n", - " `Salam Hamza!`
\n", - " `Salam Ibrahim!`
\n", - " `Salam Kawtar!`
\n", - " `Salam Nabil!`" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "7e5405de", - "metadata": { - "id": "7e5405de", - "outputId": "5237b37d-0a38-47e7-f10a-c2a9b7949333", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Salam Omar!\n", - "Salam Zineb!\n", - "Salam Hamza!\n", - "Salam Ibrahim!\n", - "Salam Kawtar!\n", - "Salam Nabil!\n" - ] - } - ], - "source": [ - "lst_name = ['Omar', 'Zineb', 'Hamza', 'Ibrahim', 'Kawtar', 'Nabil']\n", - "for name in lst_name:\n", - " print('Salam ' + name + \"!\")\n", - " #print('Salam {}!'.format(name))" - ] - }, - { - "cell_type": "markdown", - "id": "e90c376b", - "metadata": { - "id": "e90c376b" - }, - "source": [ - "# Exercise 19: Functions" - ] - }, - { - "cell_type": "markdown", - "id": "489b61ff", - "metadata": { - "id": "489b61ff" - }, - "source": [ - "fFinish up the code below by implementing the function sum_of_digits that takes an integer and returns the sum of its digits.\n", - "* Exepected output:
\n", - " `26`" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "a761d4c4", - "metadata": { - "id": "a761d4c4", - "outputId": "7cf3de2c-0a05-4229-ceb5-328ea908853e", - "colab": { - "base_uri": "https://localhost:8080/" - } - }, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "26\n" - ] - } - ], - "source": [ - "def sum_of_digits(x):\n", - " x = str(x)\n", - " out = 0\n", - " for c in x:\n", - " out += int(c)\n", - " return out\n", - "\n", - "def sum_of_digits(x):\n", - " out = 0\n", - " while x > 0:\n", - " out += x % 10\n", - " x //= 10\n", - " return out\n", - "print(sum_of_digits(989))" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "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.9.2" - }, + "cells": [ + { + "cell_type": "markdown", + "id": "c58884ae", + "metadata": { + "id": "c58884ae" + }, + "source": [ + "# Exercise 01: Standard output" + ] + }, + { + "cell_type": "markdown", + "id": "98a55ba6", + "metadata": { + "id": "98a55ba6" + }, + "source": [ + "1. Print your name on the standard Output using the function `print`.\n", + "2. Print your name, age and city each in a separate line.\n", + "3. Print your name, age and city In a single line\n", + "4. In a meaningful sentence Print your name, age and city in a single line" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7ec3cd3f", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "7ec3cd3f", + "outputId": "9c15173c-4c2f-4500-ccf9-65088c3aa6b7" + }, + "outputs": [], + "source": [ + "name = 'Ahmed'\n", + "age = 25\n", + "city = 'Casablanca'\n", + "print(name, end='-')\n", + "print(name)\n", + "print(age)\n", + "print(city)\n", + "print(name, age, city, sep='*')\n", + "print('my name is {0}, I am {1}, and I am from {2}'.format(name, age, city))\n", + "print(f'my name is {name}, I am {age}, and I am from {city}')" + ] + }, + { + "cell_type": "markdown", + "id": "4eb25b0a", + "metadata": { + "id": "4eb25b0a" + }, + "source": [ + "# Exercise 02: Variables" + ] + }, + { + "cell_type": "markdown", + "id": "75b5ed2c", + "metadata": { + "id": "75b5ed2c" + }, + "source": [ + "Consider the following statements (remember a statement is a line of code the interpreter can execute. `x = 1` is an expression that stores the value `1` into `x`):\n", + "1. Print the summation, subtruction, multiplication and division of `x` and `y` each in a separate line without using any other variables.\n", + "2. Store the summation, subtruction, multiplication and division of `x` and `y` each in a separate variable, print those variables each in a separate line." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3c382322", + "metadata": { "colab": { - "provenance": [] - } + "base_uri": "https://localhost:8080/" + }, + "id": "3c382322", + "outputId": "52128027-fc92-4243-a067-9e73a7004a2c" + }, + "outputs": [], + "source": [ + "x = 1\n", + "y = 2\n", + "print(x+y)\n", + "print(x-y)\n", + "print(x * y)\n", + "print(x/y)\n", + "print(x//y)\n", + "sum = x + y\n", + "diff = x - y\n", + "prod = x * y\n", + "div = x / y\n", + "print(sum)\n", + "print(diff)\n", + "print(prod)\n", + "print(div)\n", + "print(sum, diff, prod, div, sep='\\n')" + ] + }, + { + "cell_type": "markdown", + "id": "fcd700f5", + "metadata": { + "id": "fcd700f5" + }, + "source": [ + "# Exercise 03: Variables" + ] + }, + { + "cell_type": "markdown", + "id": "a608bd37", + "metadata": { + "id": "a608bd37" + }, + "source": [ + "Consider the following statements:\n", + "1. Swap the values of `x` and `y` . *`x` should store the value of `y` and `y` should store the value of `x`*\n", + "2. Store the sum of `x` and `y` into `x` and their subtraction into `y`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "28aba62a", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "28aba62a", + "outputId": "59ca51ef-f99a-4391-968f-c4eb6f4a186a" + }, + "outputs": [], + "source": [ + "x = 22\n", + "y = 33\n", + "\n", + "#x, y = y, x\n", + "x, y = x + y, x - y\n", + "print(x, y)\n", + "print(f'{x = } ; {y = }') # using f-string for formating" + ] + }, + { + "cell_type": "markdown", + "id": "cdddaca1", + "metadata": { + "id": "cdddaca1" + }, + "source": [ + "# Exercise 04: Conditions" + ] + }, + { + "cell_type": "markdown", + "id": "9fa90c43", + "metadata": { + "id": "9fa90c43" + }, + "source": [ + "Consider the following statements\n", + "1. Write an **if statement** to check if `x` is equal to `y` if so print `\"x and y are equal\"` otherwise print `\"x and y are not equal\"`\n", + "2. Write an **if statement** to check if `x` is equal to `z` if so print `\"x and z are equal\"` otherwise print `\"x and z are not equal\"`\n", + "3. Write an **if statement** to check if either `x` is equal `y` or `x` is equal to `z` if so print `x is equal to y or z` otherwise print `\"x is equal to neither y nor z\"`\n", + "4. Write an **if statement** to check if `x` is equal to both `y` and `z` if so print `x is equal to both y and z` otherwise print `\"x is equal to neither y nor z\"`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "83d12754", + "metadata": { + "id": "83d12754", + "outputId": "e82ad424-5823-451b-8e98-e9c1a7d16116" + }, + "outputs": [], + "source": [ + "x = 1\n", + "y = 2\n", + "z = 1\n", + "\n", + "if x == y:\n", + " print('x and y are equal')\n", + "else:\n", + " print('x and y are not equal')\n", + "\n", + "if x == z:\n", + " print('x and z are equal')\n", + "else:\n", + " print('x and z are not equal')\n", + "\n", + "if x == y or x == z:\n", + " print('x is equal to y or z')\n", + "else:\n", + " print('x is equal to neither y nor z')\n", + "\n", + "if x == y and x == z:\n", + " print('x is equal to both y and z')\n", + "else:\n", + " print('x is equal to neither y nor z')" + ] + }, + { + "cell_type": "markdown", + "id": "492aaed0", + "metadata": { + "id": "492aaed0" + }, + "source": [ + "# Exercise 05: Conditions" + ] + }, + { + "cell_type": "markdown", + "id": "302e1350", + "metadata": { + "id": "302e1350" + }, + "source": [ + "Consider the following statements:\n", + "1. Using the modulo operator `%`, check each variable if it is divisible by two and print some useful output.\n", + "2. Using the modulo operator `%`, check if at least one of the variables is divisible by two and print some useful output\n", + "3. Using the modulo operator `%`, check if all the variables ar divisible by two and print some useful output" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3aaf1703", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "3aaf1703", + "outputId": "58649dc4-2f8b-4e20-ef53-a90542ad6b49" + }, + "outputs": [], + "source": [ + "x = 9\n", + "y = 222\n", + "z = 3\n", + "\n", + "if x % 2 == 0:\n", + " print('x is even')\n", + "if y % 2 == 0:\n", + " print('y is even')\n", + "if z % 2 == 0:\n", + " print('z is even')\n", + "if x % 2 == 0 or y % 2 == 0 or z % 2 == 0:\n", + " print('at least one variable is even')\n", + "if x % 2 == 0 and y % 2 == 0 and z % 2 == 0:\n", + " print('all variables are even')" + ] + }, + { + "cell_type": "markdown", + "id": "053e15a4", + "metadata": { + "id": "053e15a4" + }, + "source": [ + "# Exercise 06: Variables and conditions" + ] + }, + { + "cell_type": "markdown", + "id": "3ecac2c0", + "metadata": { + "id": "3ecac2c0" + }, + "source": [ + "Consider the bellow statements:\n", + "- Write an **if else statement** to check wheter the variable `x` is even or odd, if it is even print `\"x is even\"` otherwise print `\"x is odd\"`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "938a6241", + "metadata": { + "id": "938a6241" + }, + "outputs": [], + "source": [ + "x = 66\n", + "\n", + "if x % 2 == 0:\n", + " print('x is even')\n", + "else:\n", + " print('x is odd')" + ] + }, + { + "cell_type": "markdown", + "id": "13d33a69", + "metadata": { + "id": "13d33a69" + }, + "source": [ + "# Exercise 07: Variables and conditions" + ] + }, + { + "cell_type": "markdown", + "id": "e769faa4", + "metadata": { + "id": "e769faa4" + }, + "source": [ + "Consider the bellow code:\n", + "1. Only by looking at the code, can you tell the type of the variables `x` and `y`.\n", + "2. Print the type of the variables `x` and `y` using the function `type`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6112c1d9", + "metadata": { + "id": "6112c1d9" + }, + "outputs": [], + "source": [ + "x = True\n", + "y = False\n", + "\n", + "# Write your answer bellow\n", + "# x and y are boolean\n", + "print(f'x is of type {type(x)}')\n", + "print(f'y is of type {type(y)}')" + ] + }, + { + "cell_type": "markdown", + "id": "ec61aee1", + "metadata": { + "id": "ec61aee1" + }, + "source": [ + "# Exercise 08: conditions" + ] + }, + { + "cell_type": "markdown", + "id": "328ff359", + "metadata": { + "id": "328ff359" + }, + "source": [ + "Consider the variable `x`:\n", + "- Using the modulo operator `%` and **if, elif, else** statements check if `x` is divisible by `2` if so print `\"x is divisible by 2\"` and check if `x` is divisible by `3` if so print `\"x is divisible by 3\"`, and check if `x` is divisible by `6` if so print `\"x is divisible by 6\"` else using a pass statement do nothing." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f9fc1065", + "metadata": { + "id": "f9fc1065" + }, + "outputs": [], + "source": [ + "x = 2322\n", + "if x % 2 == 0:\n", + " print('x is divisible by 2')\n", + "if x % 3 == 0:\n", + " print('x is divisible by 3')\n", + "if x % 6 == 0:\n", + " print('x is divisible by 6')\n", + "else:\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "id": "bfe2c7b1", + "metadata": { + "id": "bfe2c7b1" + }, + "source": [ + "# Exercise 09: conditions" + ] + }, + { + "cell_type": "markdown", + "id": "2d173da8", + "metadata": { + "id": "2d173da8" + }, + "source": [ + "Consider the variable `x`:\n", + "- Using an **if statement** check if `x` is divisible by `2`and a **nested if statement** to check if it's divisible by `3`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e773f312", + "metadata": { + "id": "e773f312" + }, + "outputs": [], + "source": [ + "x = 8989\n", + "if x % 2 == 0:\n", + " print('x is divisible by 2')\n", + " if x % 3 == 0:\n", + " print('x is divisible by 3')" + ] + }, + { + "cell_type": "markdown", + "id": "1c40dbb2", + "metadata": { + "id": "1c40dbb2" + }, + "source": [ + "# Exercise 10: Variables and conditions" + ] + }, + { + "cell_type": "markdown", + "id": "a7f37439", + "metadata": { + "id": "a7f37439" + }, + "source": [ + "Consider following statements:\n", + "- Only by looking at the code, can you tell what would be printed. write your answer as comments next to each print statement.\n", + "- Explain the behavior, write your answer as comments at the end of the code." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4615cb39", + "metadata": { + "id": "4615cb39" + }, + "outputs": [], + "source": [ + "x = 3\n", + "y = 3.3\n", + "z = True\n", + "a = 'test'\n", + "#print(x is int) False\n", + "#print(type(x) is int) True\n", + "#print(type(y) is str) False\n", + "#print(type(y) is float) True\n", + "#print(type(z) is bool) True\n", + "#print(type(a) is str) True" + ] + }, + { + "cell_type": "markdown", + "id": "a854f619", + "metadata": { + "id": "a854f619" + }, + "source": [ + "# Exercise 11: Standard Input/Output" + ] + }, + { + "cell_type": "markdown", + "id": "2d941c03", + "metadata": { + "id": "2d941c03" + }, + "source": [ + "Create a program that takes an input from the user and print it in the standard output." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cf96712f", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "cf96712f", + "outputId": "e89b474f-b6a0-49ac-ed9a-8093c381700a" + }, + "outputs": [], + "source": [ + "line = input('enter a sentence: ')\n", + "print(line)" + ] + }, + { + "cell_type": "markdown", + "id": "ceaad399", + "metadata": { + "id": "ceaad399" + }, + "source": [ + "# Exercise 12: Standard I/O" + ] + }, + { + "cell_type": "markdown", + "id": "6a3b6743", + "metadata": { + "id": "6a3b6743" + }, + "source": [ + "Create a program that takes the name and age of the user from the standard input.\n", + " 1. If the user entered `\"hamid\"` and `\"23\"` print `hamis is 23`.\n", + " 2. Use the method `format` to do the same thing as above." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "48202165", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "48202165", + "outputId": "5fe4f58c-13ca-4b01-b9e7-2c932cb809b9" + }, + "outputs": [], + "source": [ + "name, age = input().split(' ')\n", + "print(name + ' is ' + age)" + ] + }, + { + "cell_type": "markdown", + "id": "08d4179a", + "metadata": { + "id": "08d4179a" + }, + "source": [ + "# Exercise 13: Standard I/O" + ] + }, + { + "cell_type": "markdown", + "id": "5c56c31b", + "metadata": { + "id": "5c56c31b" + }, + "source": [ + "Create a program that takes an integer from the input and print its type.\n", + "- Run your code and enter the value `\"11\"`\n", + "- Run your code again and enter the value `test`\n", + "- Explain the output." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6cdbc7f3", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "6cdbc7f3", + "outputId": "d922f88b-8517-499a-bcb5-a8e4a7046afa" + }, + "outputs": [], + "source": [ + "x = input()\n", + "print(type(x))\n", + "\n", + "# input function return str type only" + ] + }, + { + "cell_type": "markdown", + "id": "be2f82d1", + "metadata": { + "id": "be2f82d1" + }, + "source": [ + "# Exrecise 14: Variables" + ] + }, + { + "cell_type": "markdown", + "id": "78976138", + "metadata": { + "id": "78976138" + }, + "source": [ + "1. Store the values `1`, `0.0`, `1j` and `\"this is a string\"` in the variables `a`, `b`, `c`, and `d` respectively.\n", + "2. Print the type of each variable using the function `type`.\n", + "3. \n", + " * Print the type of the following sums : `a + b` and `b + c`, and explain the behavior.\n", + " * Try summing `a` and `d`, and explain the behavior.\n", + "4. consider the two following strings `122` and `rrr`.\n", + " * Using `int` class constuctor try to convert the above strings to integer types.\n", + " * What do we call the above behavior\n", + " * *Don't worry about the term constructors we will get back to them later just use the syntax `int(122)`.*\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0263f91e", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "0263f91e", + "outputId": "1b9b9c45-2dd5-445d-a0d3-92ad03595cae" + }, + "outputs": [], + "source": [ + "a = 1\n", + "b = 0.0\n", + "c = 1j\n", + "d = 'this is a string'\n", + "print(type(a))\n", + "print(type(b))\n", + "print(type(c))\n", + "print(type(d))\n", + "print(type(a+b))\n", + "print(type(b+c))\n", + "s1 = '122'\n", + "s2 = 'rrr'\n", + "n1 = int(122.0)\n", + "print(n1)" + ] + }, + { + "cell_type": "markdown", + "id": "4a1a82eb", + "metadata": { + "id": "4a1a82eb" + }, + "source": [ + "# Exercise 15: Variables" + ] + }, + { + "cell_type": "markdown", + "id": "9d6ec9ad", + "metadata": { + "id": "9d6ec9ad" + }, + "source": [ + "Create a program that takes two strings from the user.\n", + "* Enter the values `122` and `rrr` and print their according types.\n", + "* Use the method `isdigit()` to make sure the input is a valid integer.\n", + " * *Don't worry about the term method just think of it as a special function that we call using the syntax `var.isdigit()` where var is a variable that stores some data*\n", + "* If the user entered invalid input print `\"invalid input\"` and terminate the program.\n", + "* If the user entered a valid input print the sum of the integers.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "92f1121a", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "92f1121a", + "outputId": "5636706c-e950-4739-dff6-dff301861139" + }, + "outputs": [], + "source": [ + "s1 = input()\n", + "s2 = input()\n", + "if s1.isdigit() and s2.isdigit():\n", + " n1 = int(s1)\n", + " n2 = int(s2)\n", + " print(n1 + n2)\n", + "else:\n", + " print('invalid input')" + ] + }, + { + "cell_type": "markdown", + "id": "dbb89719", + "metadata": { + "id": "dbb89719" + }, + "source": [ + "# Exercise 16: Conditions" + ] + }, + { + "cell_type": "markdown", + "id": "2515d3c1", + "metadata": { + "id": "2515d3c1" + }, + "source": [ + "- Create a program that reads from the standard input two integers and a binary operator (`+`,`-`,`/` or `*`) and prints the result of the opration on the two integers.\n", + " - Check the validity of the input, and print `\"Invalid input\"` if the input is not valid.\n", + " \n", + "- Rewrite the program so it can also take floats or complex numbers or any combinasion of the mentioned types.\n", + " - Check the validity of the input, and print `Invalid input` if the input is not valid." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4e93835b", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "4e93835b", + "outputId": "a901929a-09b2-410d-c635-4a430b539c0d" + }, + "outputs": [], + "source": [ + "def isfloat(x):\n", + " try:\n", + " x = float(x)\n", + " return True\n", + " except:\n", + " return False\n", + "\n", + "\n", + "s1, s2, s3 = input().split(' ')\n", + "if not isfloat(s1) or not isfloat(s2) or not s3 in '+-/*':\n", + " print('invalid input')\n", + "n1 = float(s1)\n", + "n2 = float(s2)\n", + "if s3 == '+':\n", + " print(n1+n2)\n", + "elif s3 == '-':\n", + " print(n1-n2)\n", + "elif s3 == '/':\n", + " print(n1/n2)\n", + "elif s3 == '*':\n", + " print(n1*n2)" + ] + }, + { + "cell_type": "markdown", + "id": "ea65b58c", + "metadata": { + "id": "ea65b58c" + }, + "source": [ + "# Exercise 17: While loop" + ] + }, + { + "cell_type": "markdown", + "id": "dbbdd7a4", + "metadata": { + "id": "dbbdd7a4" + }, + "source": [ + "Consider an algorithm that takes as input a positive integer n. If n is even, the algorithm divides it by two, and if n is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until n is one. For example, the sequence for n=3 is as follows:
\n", + " `3→10→5→16→8→4→2→1`\n", + "- Create a program that reads the integer n from the standard input and simulates the execition of the algorithm for the given n by printing all the values in a single line.
\n", + " * Sample input:
\n", + " `3`\n", + " * Sample output:
\n", + " `3 10 5 16 8 4 2 1`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e996b286", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "e996b286", + "outputId": "25cc02b9-985d-45fc-d05b-b4060b71ddc9" + }, + "outputs": [], + "source": [ + "x = int(input())\n", + "while True:\n", + " print (x, end=' ')\n", + " if x == 1:\n", + " break\n", + " elif x % 2 == 0:\n", + " x //= 2\n", + " else:\n", + " x = 3 * x +1" + ] + }, + { + "cell_type": "markdown", + "id": "90671456", + "metadata": { + "id": "90671456" + }, + "source": [ + "## Exercise 18: For Loop" + ] + }, + { + "cell_type": "markdown", + "id": "29284bc1", + "metadata": { + "id": "29284bc1" + }, + "source": [ + "You are given a list of strings that contains some names.
\n", + "Finish up the code below so that it prints `Salam !` for each name in the list.\n", + "* Expected output:
\n", + " `Salam Omar!`
\n", + " `Salam Zineb!`
\n", + " `Salam Hamza!`
\n", + " `Salam Ibrahim!`
\n", + " `Salam Kawtar!`
\n", + " `Salam Nabil!`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7e5405de", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "7e5405de", + "outputId": "5237b37d-0a38-47e7-f10a-c2a9b7949333" + }, + "outputs": [], + "source": [ + "lst_name = ['Omar', 'Zineb', 'Hamza', 'Ibrahim', 'Kawtar', 'Nabil']\n", + "for name in lst_name:\n", + " #print('Salam ' + name + \"!\")\n", + " #print('Salam {}!'.format(name))\n", + " print(f'Salam {name}!')" + ] + }, + { + "cell_type": "markdown", + "id": "e90c376b", + "metadata": { + "id": "e90c376b" + }, + "source": [ + "# Exercise 19: Functions" + ] + }, + { + "cell_type": "markdown", + "id": "489b61ff", + "metadata": { + "id": "489b61ff" + }, + "source": [ + "fFinish up the code below by implementing the function sum_of_digits that takes an integer and returns the sum of its digits.\n", + "* Exepected output:
\n", + " `26`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a761d4c4", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "a761d4c4", + "outputId": "7cf3de2c-0a05-4229-ceb5-328ea908853e" + }, + "outputs": [], + "source": [ + "# method 1\n", + "def sum_of_digits(x):\n", + " x = str(x)\n", + " out = 0\n", + " for c in x:\n", + " out += int(c)\n", + " return out\n", + "print(sum_of_digits(989))\n", + "\n", + "# method 2 using modulo\n", + "def sum_of_digits(x):\n", + " out = 0\n", + " while x > 0:\n", + " out += x % 10\n", + " x //= 10\n", + " return out\n", + "print(sum_of_digits(989))" + ] + } + ], + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" }, - "nbformat": 4, - "nbformat_minor": 5 -} \ No newline at end of file + "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.9.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}