From 9893921d09d95f8a49061c1e7c0d9c413fb05ca6 Mon Sep 17 00:00:00 2001 From: Guillermo Fiallo Montero Date: Wed, 19 Feb 2025 16:32:59 +0100 Subject: [PATCH] e2 lab-py-functions-exercises --- python_functions_exercises.ipynb | 764 ++++++++++++++++++++++++++++--- 1 file changed, 705 insertions(+), 59 deletions(-) diff --git a/python_functions_exercises.ipynb b/python_functions_exercises.ipynb index 90ce7b7..79b8995 100644 --- a/python_functions_exercises.ipynb +++ b/python_functions_exercises.ipynb @@ -20,11 +20,27 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 2, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def Max_Number (num1:int, num2:int, num3:int) -> int:\n", + " compare_numbers = [num1, num2, num3]\n", + " return max(compare_numbers)\n", + "\n", + "Max_Number(5,10, 3)" ] }, { @@ -48,11 +64,31 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "20" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def sum_all (numbers: list) ->int:\n", + " \"\"\" Here insert a list of numbers no matter how long. It will give you the sum of all of them.\n", + " \"\"\"\n", + " # I had the following line that kept giving me a differnt result.\n", + " # numbers = [] it clears the input list so it has to be without it.\n", + " \n", + " return sum(numbers)\n", + "\n", + "sum_all([8, 2, 3, 0, 7])" ] }, { @@ -77,11 +113,32 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "-336" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def multiply_all (numbers: list) ->int:\n", + " \"\"\"This function is used to insert a list of numbers and it multiplies all of them.\n", + " Only integers allowed?\"\"\"\n", + " total_product = 1\n", + " for i in numbers:\n", + " total_product *= i\n", + " # numbers *= numbers I tried this and it is wrong!\n", + " return total_product\n", + "\n", + "multiply_all([8, 2, 3, -1, 7])" ] }, { @@ -106,11 +163,26 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'4321dcba'" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here\n" + "# Your code here\n", + "def reverse_str (string: str) -> str:\n", + " return string[::-1]\n", + "\n", + "reverse_str(\"abcd1234\")" ] }, { @@ -124,11 +196,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 28, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Factorial de 5: 120\n", + "Factorial de -3: Only non-negative integers are allowed.\n" + ] + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "\n", + "def calc_factorial (number : int) -> int :\n", + " if number < 0:\n", + " return \"Only non-negative integers are allowed.\"\n", + " else:\n", + " x = 1\n", + " for i in range(1, number+1):\n", + " x *= i\n", + " # while n !=1:\n", + " # multip = n * (n-1)\n", + " return x\n", + " \n", + "print('Factorial de 5:', calc_factorial(5))\n", + "print('Factorial de -3:', calc_factorial(-3))" ] }, { @@ -142,11 +237,61 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 39, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'Number 9 is within your input range.'" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def number_range_checker(number, start, stop) :\n", + " for i in range(start, stop+1):\n", + " # print(f\"Checking {number}...\")\n", + " if i == number:\n", + " return f\"Number {i} is within your input range.\"\n", + " # Loop finished → No match found\n", + " return f\"Number {number} is NOT within your input range.\"\n", + "\n", + "number_range_checker(9, -5, 10)\n", + "\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number 8 is within your input range.\n" + ] + } + ], + "source": [ + "# 2nd option\n", + "\n", + "def number_range_checker(number, start, stop):\n", + " # Directly check if the number is within the range, inclusive\n", + " if start <= number <= stop:\n", + " return f\"Number {number} is within your input range.\"\n", + " else:\n", + " return f\"Number {number} is NOT within your input range.\"\n", + "\n", + "# Example usage:\n", + "print(number_range_checker(8, -5, 10)) # Should print \"Number 8 is within your input range.\"\n", + "\n" ] }, { @@ -176,11 +321,37 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 94, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Uppercase letters: 4\n", + "Lowercase letters: 12\n" + ] + } + ], "source": [ - "# Your code here" + "def count_upper_and_lower(s):\n", + " # Initialize counters\n", + " upper_count = 0\n", + " lower_count = 0\n", + " \n", + " # Iterate through each character in the string\n", + " for char in s:\n", + " if char.isupper():\n", + " upper_count += 1\n", + " elif char.islower():\n", + " lower_count += 1\n", + " \n", + " # Print the results\n", + " print(f\"Uppercase letters: {upper_count}\")\n", + " print(f\"Lowercase letters: {lower_count}\")\n", + "\n", + "# Example usage\n", + "count_upper_and_lower(\"The Quick Brown Fox\")" ] }, { @@ -205,11 +376,31 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 46, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5]" + ] + }, + "execution_count": 46, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def unique_elements (input_list):\n", + " # Convert list to set to remove duplicates\n", + " unique_set = set(input_list)\n", + " # Convert set back to list\n", + " unique_list = list(unique_set)\n", + " return unique_list\n", + " \n", + "\n", + "unique_elements([1, 2, 3, 3, 4, 5])\n" ] }, { @@ -223,11 +414,41 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 57, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'Is prime Number!'" + ] + }, + "execution_count": 57, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def is_prime (num):\n", + " if num < 1:\n", + " return \"Your number is not prime\"\n", + " elif num > 2 and num % 2 == 0 :\n", + " return \"Your number is not prime\"\n", + " else:\n", + " num == 2\n", + " return \"Is prime Number!\"\n", + "\n", + " # Check divisibility from 3 upwards, up to square root of num\n", + " for i in range(3, int(num ** 0.5) + 1, 2):\n", + " if num % i == 0:\n", + " return \"Your number is not prime\"\n", + " \n", + " return \"Is prime number!\"\n", + "\n", + "\n", + "\n", + "is_prime(13)" ] }, { @@ -252,11 +473,30 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 61, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 4, 6, 8, 10]" + ] + }, + "execution_count": 61, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def even_list (lst):\n", + " new_lst = []\n", + " for num in lst:\n", + " if num % 2 == 0:\n", + " new_lst.append(num)\n", + " return new_lst\n", + "\n", + "even_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n" ] }, { @@ -274,7 +514,39 @@ "metadata": {}, "outputs": [], "source": [ - "# Your code here" + "# Your code here\n", + "def perf_num (num):\n", + " if num == \n" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "28 is a perfect number.\n" + ] + } + ], + "source": [ + "# Function to check if the number is perfect\n", + "def is_perfect(n):\n", + " sum_of_divisors = 0\n", + " for i in range(1, n):\n", + " if n % i == 0:\n", + " sum_of_divisors += i\n", + " return sum_of_divisors == n\n", + "\n", + "# Driver code\n", + "n = 28\n", + "if is_perfect(n):\n", + " print(f\"{n} is a perfect number.\")\n", + "else:\n", + " print(f\"{n} is not a perfect number.\")" ] }, { @@ -288,11 +560,71 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 89, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n" + ] + } + ], + "source": [ + "def is_palindrome(s):\n", + " # Initialize an empty string for the cleaned version\n", + " cleaned_string = \"\"\n", + " \n", + " # Loop through each character in the input string\n", + " for char in s:\n", + " # Convert to lowercase and check if it is alphanumeric\n", + " if char.isalnum():\n", + " cleaned_string += char.lower()\n", + " \n", + " # Check if the cleaned string is equal to its reverse\n", + " length = len(cleaned_string)\n", + " for i in range(length // 2):\n", + " if cleaned_string[i] != cleaned_string[length - i - 1]:\n", + " return False\n", + " \n", + " return True\n", + "\n", + "# Example usage\n", + "print(is_palindrome(\"A man, a plan, a canal: Panama\")) # Should return True\n", + "print(is_palindrome(\"hello\")) # Should return False" + ] + }, + { + "cell_type": "code", + "execution_count": 88, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n", + "True\n" + ] + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "\n", + "def is_palindrome(s):\n", + " # Normalize the string: remove spaces, convert to lowercase\n", + " cleaned_string = ''.join(char.lower() for char in s if char.isalnum())\n", + " \n", + " # Check if cleaned string is the same forwards and backwards\n", + " return cleaned_string == cleaned_string[::-1]\n", + "\n", + "# Example usage\n", + "print(is_palindrome(\"A man, a plan, a canal: Panama\")) # Should return True\n", + "print(is_palindrome(\"hello\")) # Should return False\n", + "print(is_palindrome(\"Anna\")) # Should return False" ] }, { @@ -304,19 +636,87 @@ "Create a function that prints the first `n` rows of Pascal's triangle.\n" ] }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1]\n", + "[1, 1]\n", + "[1, 2, 1]\n", + "[1, 3, 3, 1]\n", + "[1, 4, 6, 4, 1]\n", + "[1, 5, 10, 10, 5, 1]\n" + ] + } + ], + "source": [ + "# Your code here\n", + "\n", + "def generate_pascals_triangle(n):\n", + " # Initialize the triangle with the first row\n", + " triangle = [[1]]\n", + " \n", + " for i in range(1, n):\n", + " prev_row = triangle[-1] # Get the last row\n", + " new_row = [1] # Start the new row with a 1\n", + " \n", + " # Generate the middle values of the row\n", + " for j in range(1, i):\n", + " new_row.append(prev_row[j - 1] + prev_row[j])\n", + " \n", + " new_row.append(1) # End the new row with a 1\n", + " triangle.append(new_row) # Add the new row to the triangle\n", + " \n", + " # Print the triangle\n", + " for row in triangle:\n", + " print(row)\n", + "\n", + "# Example usage:\n", + "generate_pascals_triangle(6)" + ] + }, { "cell_type": "code", "execution_count": null, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]\n", + "None " + ] + } + ], "source": [ - "# Your code here" + "def pascal(n):\n", + " levels = []\n", + " for i in range(n):\n", + " level = []\n", + " for j in range(i+1):\n", + " if j == 0 or j == i:\n", + " level.append(1)\n", + " else:\n", + " level.append(levels[i-1][j-1] + levels[i-1][j])\n", + " levels.append(level)\n", + " \n", + " print(levels)\n", + "\n", + "pascal(6)\n", + "print(pascal(6),end = \" \")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", "\n", "### Exercise 14: Pangram Checker\n", "Define a function to check if the input string is a pangram (contains every letter of the alphabet at least once).\n" @@ -335,11 +735,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 58, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 58, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def pangram(string):\n", + "\t# alphabet_set = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}\n", + "\talphabet_set = set('abcdefghijklmnopqrstuvwxyz') # Correct way to create a set\n", + "\n", + "\tinput_string = string.lower()\n", + "\tfor char in input_string:\n", + "\t\tif char.isalpha() and char in alphabet_set : # Combine checks using 'and'\n", + "\t\t\talphabet_set.remove(char)\t\t\t# Remove the letter from the set\n", + " \t\t\t# If alphabet_set is empty, we've seen every letter\n", + "\treturn len(alphabet_set) == 0\n", + "\n", + "pangram(\"The quick brown fox jumps over the lazy dog\")" ] }, { @@ -364,11 +787,43 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 91, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "apple-banana-grape-orange\n", + "black-green-red-white-yellow\n" + ] + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def sort_hyphen_separated_words(input_string):\n", + " # Step 1: Split the input string into words using hyphen as a delimiter\n", + " words = input_string.split('-')\n", + " \n", + " # Step 2: Sort the list of words\n", + " words.sort() # This sorts the list in place\n", + "\n", + " # Step 3: Manually reconstruct the sorted string with hyphens\n", + " sorted_string = \"\"\n", + " for i in range(len(words)):\n", + " sorted_string += words[i]\n", + " # Add a hyphen between words, but not after the last word\n", + " if i < len(words) - 1:\n", + " sorted_string += \"-\"\n", + " \n", + " # Step 4: Print the result\n", + " print(sorted_string)\n", + "\n", + "# Example usage\n", + "sort_hyphen_separated_words(\"banana-apple-orange-grape\")\n", + "\n", + "sort_hyphen_separated_words(\"green-red-yellow-black-white\")\n", + "\n" ] }, { @@ -382,11 +837,58 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 93, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The square of 1 is 1\n", + "The square of 2 is 4\n", + "The square of 3 is 9\n", + "The square of 4 is 16\n", + "The square of 5 is 25\n", + "The square of 6 is 36\n", + "The square of 7 is 49\n", + "The square of 8 is 64\n", + "The square of 9 is 81\n", + "The square of 10 is 100\n", + "The square of 11 is 121\n", + "The square of 12 is 144\n", + "The square of 13 is 169\n", + "The square of 14 is 196\n", + "The square of 15 is 225\n", + "The square of 16 is 256\n", + "The square of 17 is 289\n", + "The square of 18 is 324\n", + "The square of 19 is 361\n", + "The square of 20 is 400\n", + "The square of 21 is 441\n", + "The square of 22 is 484\n", + "The square of 23 is 529\n", + "The square of 24 is 576\n", + "The square of 25 is 625\n", + "The square of 26 is 676\n", + "The square of 27 is 729\n", + "The square of 28 is 784\n", + "The square of 29 is 841\n", + "The square of 30 is 900\n" + ] + } + ], "source": [ - "# Your code here" + "# Your code here \n", + "def generate_squares():\n", + " # Loop over each number from 1 to 30\n", + " for number in range(1, 31):\n", + " # Calculate the square of the current number\n", + " square = number * number\n", + " # Print the squared value\n", + " print(f\"The square of {number} is {square}\")\n", + "\n", + "# Call the function to execute it\n", + "generate_squares()" ] }, { @@ -400,11 +902,42 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 76, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, World!\n" + ] + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "\n", + "# Decorator for bold text\n", + "def bold_decorator(fn):\n", + " def wrapper():\n", + " # Applying bold formatting\n", + " return f\"{fn()}\"\n", + " return wrapper\n", + "\n", + "# Decorator for italic text\n", + "def italic_decorator(fn):\n", + " def wrapper():\n", + " # Applying italic formatting\n", + " return f\"{fn()}\"\n", + " return wrapper\n", + "\n", + "# Function to apply decorators to\n", + "@bold_decorator\n", + "@italic_decorator\n", + "def get_text():\n", + " return \"Hello, World!\"\n", + "\n", + "# Example usage\n", + "print(get_text()) # Output should be \"Hello, World!\"" ] }, { @@ -418,11 +951,55 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 77, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, World!\n" + ] + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "\n", + "code = \"\"\"\n", + "def greet():\n", + " print(\"Hello, World!\")\n", + "\n", + "greet()\n", + "\"\"\"\n", + "\n", + "exec(code)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The sum is: 14\n" + ] + } + ], + "source": [ + "# A string containing Python code\n", + "code_string = \"\"\"\n", + "def suma (a,b):\n", + " result = a + b\n", + " return print('The sum is:', result)\n", + "\n", + "suma(5,9)\n", + "\"\"\"\n", + "\n", + "# Using exec() to execute the code in the string\n", + "exec(code_string)" ] }, { @@ -436,11 +1013,59 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 85, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, Alice!\n" + ] + } + ], + "source": [ + "# Your code here\n", + "\n", + "def greet(name):\n", + " # Inner function to format the greeting\n", + " def add_exclamation(greeting):\n", + " return greeting + \"!\"\n", + " \n", + " # Use the inner function to create a greeting\n", + " basic_greeting = f\"Hello, {name}\"\n", + " excited_greeting = add_exclamation(basic_greeting)\n", + " return excited_greeting\n", + "\n", + "# Example usage\n", + "print(greet(\"Alice\")) # Should print \"Hello, Alice!\"\n" + ] + }, + { + "cell_type": "code", + "execution_count": 86, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "13\n" + ] + } + ], "source": [ - "# Your code here" + "def outer_function(x):\n", + " # Inner function\n", + " def inner_function(y):\n", + " return y * 2\n", + " \n", + " # Use inner function\n", + " result = inner_function(x) + 3\n", + " return result\n", + "\n", + "# Usage example\n", + "print(outer_function(5)) # Outcome should be 13, since (5*2) + 3 = 13" ] }, { @@ -463,11 +1088,32 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 63, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n" + ] + } + ], "source": [ - "# Your code here" + "# Your code here\n", + "def count_local_variables():\n", + " # Declare local variables\n", + " a = 1\n", + " b = 2\n", + " c = 3\n", + " # Call locals() to get the local variables dictionary\n", + " local_vars = locals()\n", + " # Return the count of local variables\n", + " return len(local_vars)\n", + "\n", + "# Example usage:\n", + "print(count_local_variables()) # Should output the number of local variables inside the function\n", + "\n" ] }, { @@ -481,7 +1127,7 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3", + "display_name": "base", "language": "python", "name": "python3" }, @@ -495,7 +1141,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.0" + "version": "3.12.7" } }, "nbformat": 4,