{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "JaRNlEgU9IeO" }, "source": [ "# Practice Problems\n", "\n", "Follows are practice problems on various topics we covered in the course. These will make you familar with the Python language and being able to practice writing programs is **invaluable**." ] }, { "cell_type": "markdown", "metadata": { "id": "yY8S9kefcVFk" }, "source": [ "## General Python" ] }, { "cell_type": "markdown", "metadata": { "id": "jMXBZO9acWvb" }, "source": [ "### **Problem 1**\n", "\n", "Write a Python program to calculate the volume of a sphere with radius 6." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Q8-VMl269IeV" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "P90Cb5rz9IeX" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "QvP7-iKv9IeY" }, "outputs": [], "source": [ "import numpy as np\n", "\n", "# set the radius of the sphere\n", "r = 6\n", "\n", "# calculate the volume\n", "volume = (4/3)*np.pi*r**3" ] }, { "cell_type": "markdown", "metadata": { "id": "7GdVMQY5e7Kz" }, "source": [ "### **Problem 2**\n", "\n", "Write a Python program to test whether a number is within 100 of 1000 or 2000." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "La2VLt__9Ieb" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "db3zusmv9Ieb" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wegSi0NV9Iec" }, "outputs": [], "source": [ "def near_thousand(n):\n", " '''\n", " This function checks whether a number is within 100 of 1000 or 2000. \n", "\n", " The function returns the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.\n", "\n", " Parameters\n", " ----------\n", " n : int, float, complex\n", " One-electron orbital of electron at r1.\n", " \n", " Returns\n", " -------\n", " ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100)) : int\n", " absolute value of number\n", " \n", " '''\n", " return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))\n", "\n", "print(near_thousand(1100))" ] }, { "cell_type": "markdown", "metadata": { "id": "e9rFCYtffIoR" }, "source": [ "### **Problem 3**\n", "\n", "Write a Python program to calculate the sum of three given numbers. If all three values are equal then return three times their sum." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "CdWr8b-l9Iee" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "DsQsQPmK9Iee" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "EQDz4Uwe9Iee" }, "outputs": [], "source": [ "def sum_thrice(x, y, z):\n", " '''\n", " This function takes three numbers and calculates their sum.\n", "\n", " If all three inputs are equal their sum is returned\n", " '''\n", " # add the three numbers together\n", " sum = x + y + z\n", " \n", " # catch if all three numbers are equal\n", " if x == y == z:\n", " sum = sum * 3\n", " \n", " return sum\n", "\n", "print(sum_thrice(1, 2, 3))" ] }, { "cell_type": "markdown", "metadata": { "id": "R2smu4cefT-W" }, "source": [ "### **Problem 4**\n", "\n", "Write a Python program to find whether a given number is even or odd and print out an appropriate message." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "OSOQMAcS9Ieg" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "4nOeD-Lq9Ieh" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "16EEFrBo9Ieh" }, "outputs": [], "source": [ "\n", "# specify a integer number\n", "num = 2\n", "\n", "# calculate the remainder to see if it is divisible by num\n", "mod = num % 2\n", "\n", "# print suitable message\n", "if mod > 0:\n", " print(\"This is an odd number.\")\n", "else:\n", " print(\"This is an even number.\")" ] }, { "cell_type": "markdown", "metadata": { "id": "S3iPKKOmfm9T" }, "source": [ "### **Problem 5**\n", "\n", "Write a Python program that will accept the base and height of a triangle and compute the area." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "NDcIVNfq9Iej" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "KE_lMfMn9Iej" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "FZ8uyR_K9Iej" }, "outputs": [], "source": [ "\n", "# input the base and height of triangle\n", "base = 5\n", "height = 8\n", "\n", "# calculate the area of the triangle\n", "area = (1/2) * base * height\n", "\n", "print(\"area = \", area)" ] }, { "cell_type": "markdown", "metadata": { "id": "TNrJPBmrfwY8" }, "source": [ "### **Problem 6**\n", "\n", "Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ebOs33Gl9Iek" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "VGZWCQwY9Iek" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "M-nKP7h69Iek" }, "outputs": [], "source": [ "\n", "def equal_sum(x, y):\n", " '''\n", " This function tests whether or not two numbers are equal or their sum or difference is 5.\n", "\n", " Parameters\n", " ----------\n", " x : int\n", " First number to compare\n", "\n", " y : int\n", " Second number to compare\n", "\n", " Returns\n", " -------\n", " True/False : Boolean\n", " Whether or not the comparison is True or False\n", " '''\n", " if x == y or abs(x-y) == 5 or (x+y) == 5:\n", " return True\n", " else:\n", " return False\n", "\n", "print(equal_sum(7, 2))\n", "print(equal_sum(27, 53))" ] }, { "cell_type": "markdown", "metadata": { "id": "cNcEHcx-gA0v" }, "source": [ "### **Problem 7**\n", "\n", "Given variables x=10 and y=60, write a Python program to print \"10+60=70\" as a string. Make this program generic for any variable values." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7ZEDW-cg9Iem" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "0NLsGO-59Iem" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vOfBZdKb9Iem" }, "outputs": [], "source": [ "\n", "# specify the input values of x and y\n", "x = 10\n", "y = 60\n", "\n", "# print the sum\n", "print(\"{} + {} = {}\".format(x, y, x + y))" ] }, { "cell_type": "markdown", "metadata": { "id": "6e-EFVXmgae7" }, "source": [ "### **Problem 8**\n", "\n", "Write a Python program to filter the positive numbers from a list." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wyosRqVv9Ien" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "bjsUseg39Ien" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "8yW5_uuF9Ieo" }, "outputs": [], "source": [ " \n", "# create a list of numbers\n", "list1 = [11, -21, 0, 45, 66, -93]\n", " \n", "# iterating each number in list\n", "for num in list1: \n", " # checking condition\n", " if num >= 0:\n", " print(num, end = \" \")" ] }, { "cell_type": "markdown", "metadata": { "id": "EHFWcQf3hKMI" }, "source": [ "### **Problem 9**\n", "\n", "Write a function that takes an integer minutes and converts it to seconds.\n", "\n", "e.g.\n", "\n", "`convert_to_secs(5) -> 300`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "M4hE-bBA9Iep" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "aexmmueE9Iep" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "OvS3VmOK9Iep" }, "outputs": [], "source": [ "\n", "def convert_to_secs(n):\n", " '''\n", " This function takes an integer minutes and converts it into seconds.\n", "\n", " Parameters\n", " ----------\n", " n : int\n", " The number of minutes\n", "\n", " Returns\n", " -------\n", " None\n", " '''\n", " # multiply the minutes by 60 to compute the seconds\n", " seconds = n * 60;\n", " \n", " print(\"{} minutes is equal to {} seconds\".format(n, seconds))\n", " \n", "# specity the number of minutes\n", "n = 5\n", "\n", "# call the function\n", "convert_to_secs(n)" ] }, { "cell_type": "markdown", "metadata": { "id": "UD6KPTO6gkwd" }, "source": [ "### **Problem 10**\n", "\n", "Write a function, `add_it_up()`, that takes a single integer as input and returns the sum of the integers from zero to the input parameter.\n", "\n", "The function should return 0 if a non-integer is passed in." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ESKL2aAJ9Ier" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "O5fjscUi9Ier" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hpJXi0je9Ier" }, "outputs": [], "source": [ "\n", "def add_it_up(n):\n", " '''\n", " This function takes an integer input and computes the sum of the integers from 0 to the input value.\n", "\n", " We build the list of integers using range and call sum to add them together.\n", "\n", " We use tryand except here which you might not have seen before, but it is similar to a if statement:\n", "\n", " ' try this part of the code and if it can be evaluated without error then continue with the program. If it returns an error run the code in the exception part'\n", "\n", " Parameters\n", " ----------\n", " n : int\n", " an integer input\n", "\n", " Returns\n", " -------\n", " result : int\n", " The result of the summation, or 0 if a float is passed to the function\n", " '''\n", " # use try and except t\n", " try:\n", " result = sum(range(n + 1))\n", " except TypeError:\n", " result = 0\n", "\n", " return result\n", "\n", "# call the function\n", "add_it_up(4)" ] }, { "cell_type": "markdown", "metadata": { "id": "zMivIRrbhp7N" }, "source": [ "### **Problem 11**\n", "\n", "Create a function that takes a string and returns it as an integer." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vOq2lpfe9Ies" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "zg1Ypc059Iet" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "K_sm3muM9Iet" }, "outputs": [], "source": [ "\n", "# specify your string\n", "string = '34'\n", "\n", "# test whether or not \n", "try:\n", " numerical_or_not = int(string)\n", "except:\n", " numerical_or_not = \"Your string is not numerical so cannot be converted to an integer\"\n", "\n", "print(numerical_or_not)" ] }, { "cell_type": "markdown", "metadata": { "id": "NJOD_Zpeh3yc" }, "source": [ "### **Problem 12**\n", "\n", "Create a function that takes a list containing only numbers and return the first element." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "iiLKlHNh9Ieu" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "z4_w0p0O9Ieu" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "iaqWHNHJ9Ieu" }, "outputs": [], "source": [ "\n", "def only_numbers(lst):\n", " '''\n", " This function checks if a list contains only numbers. If it does it will then return the first item from that list.\n", " \n", " We use the following commands:\n", "\n", " isinstance : The isinstance() function returns True if the specified object is of the specified type, otherwise False. Here we check for integer or float.\n", "\n", " all : The all() function returns True if all items in an iterable are true, otherwise it returns False.\n", "\n", " Parameters\n", " ----------\n", " lst : list\n", " A list of numbers\n", "\n", " Returns\n", " -------\n", " lst[0] : int/float\n", " The value of the first item in the list\n", " ''' \n", " # test if the list contains only numbers\n", " if all(isinstance(e, (int, float)) for e in lst):\n", " pass\n", " else:\n", " return \"Your list does not contain only numbers!\"\n", "\n", " return lst[0]\n", "\n", "\n", "lst = [1,2,3,4,5]\n", "print(only_numbers(lst))\n", "\n", "lst2 = [1,2,'string',4,5]\n", "print(only_numbers(lst2))" ] }, { "cell_type": "markdown", "metadata": { "id": "ELKkEbMRiGTi" }, "source": [ "### **Problem 13**\n", "\n", "Create a function that takes a list of numbers. Return the largest number in the list." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1qEmUpj19Ieu" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "cBk12WBu9Ieu" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "q4VQaWvV9Iev" }, "outputs": [], "source": [ "\n", "def return_max(lst):\n", " '''\n", " Returns the largest item in a list\n", "\n", " Parameters\n", " ----------\n", " lst : list\n", " A list of numbers\n", "\n", " Returns\n", " -------\n", " max(lst) : int/float\n", " The largest number in the list\n", " '''\n", " return max(lst)\n", "\n", "# specify a list of numbers\n", "lst = [1,30,681,104]\n", "\n", "return_max(lst)" ] }, { "cell_type": "markdown", "metadata": { "id": "PpB5dTiviUa6" }, "source": [ "### **Problem 14**\n", "\n", "Create a function that returns `True` if an integer is divisible by 5, and `False` otherwise." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "fbSjNaPd9Iew" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "FjLDJ3Jw9Iew" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "klZEQ90-9Iew" }, "outputs": [], "source": [ "def div_by_5(n):\n", " '''\n", " Returns True if a number is divisible by 5, False if not.\n", "\n", " Parameters\n", " ----------\n", " n : int\n", " The integer number to divide by 5\n", "\n", " Returns\n", " -------\n", " True/False : Boolean\n", " '''\n", " if n % 5 == 0:\n", " return True\n", " else:\n", " return False\n", "\n", "print(div_by_5(5))" ] }, { "cell_type": "markdown", "metadata": { "id": "MP5f-OKdimgr" }, "source": [ "### **Problem 15**\n", "\n", "Create a function that takes an angle in radians and returns the corresponding angle in degrees." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XiOEicQy9Iex" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "V-QV2K1Y9Iey" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "IAqPKAZA9Iey" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "def convert_to_rad(theta_rad):\n", " '''\n", " Converts an angle in radian to an angle in degrees.\n", "\n", " To convert from radians to degrees we divide by Pi and multiply by 180.\n", "\n", " Parameters\n", " ----------\n", " theta_rad : int/float\n", " The angle in radians to be converted\n", "\n", " Returns\n", " -------\n", " theta_deg : int/float\n", " The converted angle in degrees\n", " '''\n", " theta_deg = theta_rad/np.pi * 180\n", "\n", " return theta_deg\n", "\n", "\n", "convert_to_rad(2*np.pi)" ] }, { "cell_type": "markdown", "metadata": { "id": "YSKVpqm2ixq_" }, "source": [ "### **Problem 16**\n", "\n", "Write a function that takes a list and a number as arguments. Add the number to the end of the list, then remove the first element of the list. The function should then return the updated list.\n", "\n", "e.g.\n", "\n", "`next_in_line([5, 6, 7, 8, 9], 1) ➞ [6, 7, 8, 9, 1]`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "uGOSbrTi9Ie0" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "SEcY3hCJ9Ie0" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "209v83XB9Ie1" }, "outputs": [], "source": [ "\n", "def next_in_line(lst, num):\n", " '''\n", " This function takes a number and appends it to the supplied list. \n", "\n", " It then removes the first item from the list.\n", "\n", " Parameters\n", " ----------\n", " lst : list\n", " A list of data\n", "\n", " num : int/float\n", " A number to append to the list\n", "\n", " Returns\n", " -------\n", " lst : int, float, string, bool\n", " The first item from the list\n", " '''\n", " # add the number to the end of the list\n", " lst.append(num)\n", "\n", " # remove the first item from the list using the del command\n", " del lst[0]\n", "\n", " return lst\n", "\n", "# define a list of numbers\n", "lst = [5, 6, 7, 8, 9]\n", "\n", "# define a number to append to the list\n", "num = 1\n", "\n", "# call the function\n", "next_in_line(lst, num)" ] }, { "cell_type": "markdown", "metadata": { "id": "HS8MhXpujn63" }, "source": [ "### **Problem 17**\n", "\n", "Write a function that takes coordinates of two points on a two-dimensional plane and returns the length of the line segment connecting those two points.\n", "\n", "e.g.\n", "\n", "`line_length([0, 0], [1, 1]) ➞ 1.41`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "pYcooAHr9Ie1" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "ozNRjTn-9Ie1" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "-c8lOOkE9Ie1" }, "outputs": [], "source": [ "\n", "def line_length(pt1, pt2):\n", " '''\n", " Returns the length of the line segment between two points. \n", "\n", " This is calculated as the following\n", "\n", " sqrt((x2 - x1) ^2 + (y2 - y1)^2))\n", "\n", " Parameters\n", " ----------\n", " x : list\n", " list of x coordinates\n", " y : list\n", " list of y coordinates\n", "\n", " Returns\n", " -------\n", " np.sqrt((pt1[1] - pt2[0])**2 + (pt1[1] - pt2[1])**2) : int, float\n", " The length of the line segment\n", "\n", " '''\n", " return ((pt1[1] - pt2[0])**2 + (pt1[1] - pt2[1])**2)**(1/2)\n", "\n", "\n", "line_length([0, 0], [1, 1])\n" ] }, { "cell_type": "markdown", "metadata": { "id": "KlRUt36XkIzl" }, "source": [ "### **Problem 18**\n", "\n", "Create a function that takes two parameters and, if both parameters are strings, add them as if they were integers or if the two parameters are integers, concatenate them. If the two parameters are different data types, return None.\n", "\n", "e.g.\n", "\n", "`silly_addition(1, 2) -> \"12\"`\n", "\n", "`silly_addition(\"1\", \"2\") -> 3`\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0-UkZqeN9Ie3" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "GSXSVrm09Ie3" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Bjg6qBbf9Ie3" }, "outputs": [], "source": [ "\n", "def silly_addition(param1, param2):\n", " '''\n", " Takes two parameters and, if both parameters are strings, adds them as if they were integers \n", " \n", " If the two parameters are integers, concatenates them.\n", "\n", " Parameters\n", " ----------\n", " param1 : int, str\n", " The first of the parameters\n", "\n", " param2 : int, str\n", " The second of the parameters\n", " \n", " Returns\n", " -------\n", " int, str, None : The output of the comparison\n", " '''\n", " if (type(param1) == str) and (type(param2) == str):\n", " return int(param1) + int(param2)\n", " elif (type(param1) == int) and (type(param2) == int):\n", " return str(param1) + str(param2)\n", " else:\n", " return None\n", "\n", "silly_addition(\"1\", \"2\")" ] }, { "cell_type": "markdown", "metadata": { "id": "ad6xlreXk8Jz" }, "source": [ "### **Problem 19**\n", "\n", "Write a program that checks whether a number is a palindrome (reads the same forwards as backwards.\n", "\n", "e.g.\n", "\n", "`is_it_palindrome(1331) -> Yes!`\n", "\n", "`is_it_palindrome(4983) -> No!`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1OcdQI1k9Ie4" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "xwH-3QS09Ie4" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_YKZOEx99Ie4" }, "outputs": [], "source": [ "\n", "\"\"\"\n", "1. The value of the integer is stored in a temporary variable.\n", "2. A while loop is used and the last digit of the number is obtained by using the modulus operator.\n", "3. The last digit is then stored at the one’s place, second last at the ten’s place and so on.\n", "4. The last digit is then removed by dividing the number with 10.\n", "5. This loop terminates when the value of the number is 0.\n", "6. The reverse of the number (rev) is then compared with the integer value stored in the temporary variable.\n", "7. If both are equal, the number is a palindrome.\n", "8. If both aren’t equal, the number isn’t a palindrome.\n", "\n", "Another, simpler solution using strings is presented after the first implementation\n", "\"\"\"\n", "\n", "n = 1010101\n", "\n", "temp=n\n", "rev=0\n", "while(n>0):\n", " dig=n%10\n", " rev=rev*10+dig\n", " n=n//10\n", "if(temp==rev):\n", " print(\"The number is a palindrome!\")\n", "else:\n", " print(\"The number isn't a palindrome!\")\n", "\n", "\n", "#\n", "# using strings\n", "#\n", "\n", "n2 = 1010101\n", "\n", "# convert the number to a string\n", "str_n = str(n2)\n", "\n", "# reverse the characters in the string\n", "reverse_str = str_n[::-1]\n", "\n", "# compare reversed string with the converted number string\n", "if str_n == reverse_str:\n", " print(\"The number is a palindrome!\")\n", "else:\n", " print(\"The number isn't a palindrome!\")\n" ] }, { "cell_type": "markdown", "metadata": { "id": "jWPde8Bsn7qt" }, "source": [ "### **Problem 20**\n", "\n", "The Collatz conjecture states that the following sequence always reaches 1:\n", "\n", "1. Start with a positive integer n. \n", "2. The next number in the sequence is $\\frac{n}{2}$ if $n$ is even and $3n + 1$ if $n$ is odd.\n", "\n", "Write a Python program to test this conjecture.\n", "\n", "e.g.\n", "\n", "`n = 5 -> 5 16 8 4 2 1`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "-bkRMmDn9Ie6" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "V6ST5K2d9Ie6" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "niucwRdb9Ie7" }, "outputs": [], "source": [ "\n", "# create an empty list\n", "i = []\n", "\n", "def collatz(n):\n", " '''\n", " Test the Collatz conjecture\n", "\n", " 1. Start with a positive integer n. \n", " 2. The next number in the sequence is $\\frac{n}{2}$ if $n$ is even and $3n + 1$ if $n$ is odd.\n", "\n", " We solve this using recursion, i.e. the function calls it self repeatedly until n == 1 when it terminates.\n", "\n", " Parameters\n", " ----------\n", " n : int\n", " An integer number, the starting value for the Collatz conjecture\n", "\n", " Returns\n", " -------\n", " collatz(n), i : func, int\n", " Either the function call itself and returns its own output or returns integer if terminates\n", " ''' \n", " if n == 1:\n", " return i\n", " if n % 2 == 0:\n", " n = n // 2\n", " else:\n", " n = ((3*n) + 1)\n", " \n", " # add the number to the empty list\n", " i.append(n)\n", " \n", " return collatz(n)\n", "\n", "print(collatz(5))" ] }, { "cell_type": "markdown", "metadata": { "id": "Y12D4cmk9Ie8" }, "source": [ "## NumPy" ] }, { "cell_type": "markdown", "metadata": { "id": "tyT82iNT9Ie8" }, "source": [ "### **Problem 1**\n", "\n", "Write a NumPy program to create a $3 \\times 3$ identity matrix." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "2ICbUkFT9Ie9" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "5Ek0R3Qi9Ie9" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hLXOAB3o9Ie9" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "np.identity(3)" ] }, { "cell_type": "markdown", "metadata": { "id": "0gWfp7k79Ie-" }, "source": [ "### **Problem 2**\n", "\n", "Write a NumPy program to find the number of rows and columns of a given matrix." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "lFpb97md9Ie-" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "_3KMW81L9Ie-" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Qo7EutC49Ie-" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create a randomly populated matrix of dimensions 5 x 5\n", "mat = np.random.randn(5,5)\n", "\n", "# print the arrays' shape\n", "print(mat.shape)" ] }, { "cell_type": "markdown", "metadata": { "id": "CsQj55I59Ie-" }, "source": [ "### **Problem 3**\n", "\n", "Write a NumPy program to convert an array to a `string` type." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "yoAUAV0E9Ie-" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "O0wShdCb9Ie-" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4eGQIM429Ie_" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create a randomly populated matrix of dimensions 5 x 5\n", "mat = np.random.rand(5,5)\n", "\n", "# change the type of the arrya using `astype`\n", "mat.astype(str)" ] }, { "cell_type": "markdown", "metadata": { "id": "XCq3IVsC9Ie_" }, "source": [ "### **Problem 4**\n", "\n", "Write a NumPy program to compute the multiplication of two arrays you define." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "60KSTb9m9Ie_" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "flKEVqqX9IfA" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "movJM3jW9IfB" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create first array\n", "array1 = np.random.rand(10,10)\n", "\n", "# create second array\n", "array2 = np.random.rand(10,10)\n", "\n", "np.matmul(array1, array2)" ] }, { "cell_type": "markdown", "metadata": { "id": "4JyFLFDh9IfC" }, "source": [ "### **Problem 5**\n", "\n", "Write a NumPy program to compute the determinant of a given square array." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "BI_EypRe9IfC" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "bU56yFlM9IfD" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XzJ7ANX19IfE" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create a random array\n", "array = np.random.rand(10,10)\n", "\n", "# call `det` from the numpy linalg library (linear algebra) which calcuates the determinant\n", "np.linalg.det(array)" ] }, { "cell_type": "markdown", "metadata": { "id": "FUDffOSR9IfE" }, "source": [ "### **Problem 6**\n", "\n", "Write a NumPy program to compute the inverse of a given array." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "rkoKTtU29IfE" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "RLMJCr9N9IfE" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3PDxpqjv9IfF" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create a random array\n", "array = np.random.rand(10,10)\n", "\n", "# call `inv` from the numpy linalg library (linear algebra) which calculates the matrix inverse\n", "np.linalg.inv(array)" ] }, { "cell_type": "markdown", "metadata": { "id": "UxvbTlNO9IfF" }, "source": [ "### **Problem 7**\n", "\n", "Write a NumPy program to compute the sum of the diagonal element of a given array." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Fb90ekyx9IfF" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "m84gPkx89IfF" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "8LBYrAyr9IfF" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create a random array\n", "array = np.random.rand(10,10)\n", "\n", "# call trace which adds up the diagonal numbers in an array. i.e. calculates the trace of a matrix\n", "np.trace(array)" ] }, { "cell_type": "markdown", "metadata": { "id": "Gku0aBQ19IfF" }, "source": [ "### **Problem 8**\n", "\n", "Consider the following array:\n", "\n", "`arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])`\n", "\n", "Write a program to extract the odd numbers." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "mn9U2QCv9IfH" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "wnOb9PB_9IfH" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "W0-YGwOx9IfH" }, "outputs": [], "source": [ "\n", "\n", "arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n", "\n", "# check if the numbers leave a remainder when divided by 2\n", "arr[arr % 2 == 1]" ] }, { "cell_type": "markdown", "metadata": { "id": "vj9VT9nR9IfH" }, "source": [ "### **Problem 9**\n", "\n", "Convert a 1D array to a 2D array with 2 rows." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9QDe75eu9IfI" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "J1-09uYm9IfI" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_poBsyne9IfJ" }, "outputs": [], "source": [ "\n", "arr = np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9])\n", "\n", "# use the respahe command to resize it to 5 columns and 2 rows\n", "arr.reshape(2,5)" ] }, { "cell_type": "markdown", "metadata": { "id": "hXMERjfe9IfK" }, "source": [ "### **Problem 10**\n", "\n", "Create two arrays and stack them vertically and horizontally." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "C-XjHeLm9IfK" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "012fvNq_9IfK" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Sqvx2it29IfK" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create two random arrays\n", "array1 = np.random.rand(5,5)\n", "array2 = np.random.rand(5,5)\n", "\n", "# vertically stack using vstack\n", "print(np.vstack([array1, array2]))\n", "\n", "# horizontally stack using hstack\n", "print(np.hstack([array1, array2]))" ] }, { "cell_type": "markdown", "metadata": { "id": "EMk3vGPT9IfL" }, "source": [ "### **Problem 11**\n", "\n", "Use the following line of code to generate an array of random numbers and extract all numbers between 5 and 10.\n", "\n", "`arr = np.array([2, 6, 1, 9, 10, 3, 27])`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "-uhq-eDs9IfM" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "x62WK-rK9IfM" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "eEu9Ng7C9IfM" }, "outputs": [], "source": [ "\n", "# build array\n", "np.array([2, 6, 1, 9, 10, 3, 27])\n", "\n", "# apply conditions directly to the array as an index condition\n", "arr[(arr >= 5) & (arr <= 10)]" ] }, { "cell_type": "markdown", "metadata": { "id": "horGTg_19IfN" }, "source": [ "### **Problem 12**\n", "\n", "Find the mean, median and standard deviation of an array you create." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "NGRDhctR9IfN" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "sV5b8lQA9IfO" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4wQewPoD9IfO" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create random 10 x 10 array\n", "arr = np.random.rand(10,10)\n", "\n", "# calculate the mean by calling .mean()\n", "print(\"mean is {}\".format(arr.mean()))\n", "\n", "# calculate the standard deviation by calling .std()\n", "print(\"Standard deviation is {}\".format(arr.std()))" ] }, { "cell_type": "markdown", "metadata": { "id": "QiYLm84Z9IfO" }, "source": [ "### **Problem 13**\n", "\n", "The following Python code snippet will create a $10 \\times 10$ array filled with random numbers\n", "\n", "`arr = np.random.rand(10, 10)`\n", "\n", "Extract the $3 \\times 3$ sub-matrix starting from the top left corner.\n", "\n", "Example of a $2 \\times 2$ sub-matrix extracted from a $3 \\times 3$ matrix:\n", "\n", "$$\n", " \\begin{pmatrix}\n", " 1 & 2 & 3 \\\\\n", " 4 & 5 & 6 \\\\ \n", " 7 & 8 & 9\n", " \\end{pmatrix}\n", " \\rightarrow\n", " \\begin{pmatrix}\n", " 1 & 2 \\\\\n", " 4 & 5 \\\\ \n", " \\end{pmatrix}\n", "$$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "pXFoXsmz9IfO" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "ZofmTbcM9IfP" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "lnOqwj1V9IfP" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "arr = np.random.rand(10, 10)\n", "\n", "arr[:7, :7]" ] }, { "cell_type": "markdown", "metadata": { "id": "93HX3Hpy9IfP" }, "source": [ "### **Problem 14**\n", "\n", "Transpose the array, `arr`, from question 13." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "NDITighH9IfQ" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "XYXQYaca9IfQ" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "JZhxnqQm9IfQ" }, "outputs": [], "source": [ "\n", "arr = np.random.rand(10, 10)\n", "\n", "# transpose using .T\n", "arr.T" ] }, { "cell_type": "markdown", "metadata": { "id": "oTJGrBnx9IfQ" }, "source": [ "### **Problem 15**\n", "\n", "Given a 1D array, negate all elements which are between 3 and 8." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Gda6dyCz9IfQ" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "3nzD1Nuh9IfR" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ZzY_qhjE9IfR" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create a integer array\n", "arr = np.array([1,8,3,84,2,7,11,5])\n", "\n", "# setup the conditions\n", "m = (arr >= 3 ) & (arr <= 8)\n", "\n", "# apply the conditions to the array and multipl by -1 for elements which satisfy the condition\n", "arr[m] *= -1\n", "\n", "# print the new array with the correct elements negated\n", "print(arr)" ] }, { "cell_type": "markdown", "metadata": { "id": "t4ND3a_T9IfR" }, "source": [ "### **Problem 16**\n", "\n", "Calculate the eigenvalues and eigenvectors of the following array:\n", "\n", "$$\n", " \\begin{pmatrix}\n", " 1 & 2 \\\\\n", " 2 & 3 \\\\ \n", " \\end{pmatrix}\n", "$$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "pMIThDll9IfS" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "jTZCO7Ko9IfS" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "UKtG0pwh9IfS" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "\n", "# create array\n", "arr = np.array([[1,2],\n", " [3,4]])\n", "\n", "# call the eigenvalue command, `eig` from the numpy linalg module\n", "np.linalg.eig(arr)" ] }, { "cell_type": "markdown", "metadata": { "id": "A_jBh6309IfS" }, "source": [ "### **Problem 17**\n", "\n", "Write a NumPy program to add a new row to an empty NumPy array." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "CF-XT_pp9IfT" }, "outputs": [], "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "Xlx9Rtt89IfU" }, "source": [ "#### Answer" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3NnVRO279IfU" }, "outputs": [], "source": [ "\n", "import numpy as np\n", "create an empty integer array\n", "\n", "arr = np.empty((0,3), int)\n", "\n", "print(\"Empty array:\") print(arr)\n", "add a new row\n", "\n", "arr = np.append(arr, np.array([[10,20,30]]), axis=0) print(\"After adding a new row:\") print(arr)" ] } ], "metadata": { "colab": { "collapsed_sections": [ "P90Cb5rz9IeX", "db3zusmv9Ieb", "DsQsQPmK9Iee", "4nOeD-Lq9Ieh", "KE_lMfMn9Iej", "VGZWCQwY9Iek", "0NLsGO-59Iem", "bjsUseg39Ien", "aexmmueE9Iep", "O5fjscUi9Ier", "zg1Ypc059Iet", "z4_w0p0O9Ieu", "cBk12WBu9Ieu", "FjLDJ3Jw9Iew", "V-QV2K1Y9Iey", "SEcY3hCJ9Ie0", "ozNRjTn-9Ie1", "GSXSVrm09Ie3", "xwH-3QS09Ie4", "V6ST5K2d9Ie6", "5Ek0R3Qi9Ie9", "_3KMW81L9Ie-", "O0wShdCb9Ie-", "flKEVqqX9IfA", "bU56yFlM9IfD", "RLMJCr9N9IfE", "m84gPkx89IfF", "wnOb9PB_9IfH", "J1-09uYm9IfI", "012fvNq_9IfK", "x62WK-rK9IfM", "sV5b8lQA9IfO", "ZofmTbcM9IfP", "XYXQYaca9IfQ", "3nzD1Nuh9IfR", "jTZCO7Ko9IfS", "Xlx9Rtt89IfU" ], "name": "Copy of PracticeProblems.ipynb", "provenance": [] }, "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.10" }, "toc-autonumbering": true }, "nbformat": 4, "nbformat_minor": 0 }