#!/usr/bin/env python # coding: utf-8 # # Welcome back # # How was lab? Was anything confusing? # # Review # # Last time we covered functions. Functions are critical to programming. # # Syntax for functions # # The general syntax for functions is: # ```python # def function_name(): # # return # ``` # # There are several things to note about the syntax (we will go through examples): # - You can have zero, one, or more arguments. # - You need the `:` after the function # - The body can be complex! # - You technically don't need a return statement at the end, but we will almost alway have a return at the end # In[2]: def minimum_two(x, y): if x < y: return x else: return y minimum_two(1, 2) # In[3]: def min_list(l): minimum = l[0] for x in l[1:]: minimum = minimum_two(minimum, x) return minimum min_list([6, 5, 4, 3, 2, 1]) # In[4]: min(1, 2) # In[5]: max(1, 2) # # You cannot use certain words in Python as variables # # Conversion: # - `int` # - `float` # - `bool` # - `str` # - `list` # - `dict` # # Build in: # - `min` # - `max` # - `sum` # # DO NOT USE THESE AS VARIABLE NAMES # # Function examples # # We will go through examples of functions # In[8]: def sum_list(l): s = 0 for x in l: s += x return s sum_list([1, 2, 3, 4, 5]) # In[14]: def is_palindrome(s): for ind in range(len(s)): if s[ind] != s[len(s) - ind - 1]: return False return True print(is_palindrome("abccba")) print(is_palindrome("abcba")) print(is_palindrome("abcbab")) # # Functions can call other functions # In[16]: def add_two_numbers(x, y): return x + y add_two_numbers(1, 2) # In[17]: def add_three_numbers(x, y, z): sum_two = add_two_numbers(x, y) return sum_two + z add_three_numbers(1, 2, 3) # # Functions can _call themselves_ # In[18]: def calls_itself(x): if x < 0: return 0 else: print(x) return calls_itself(x - 1) calls_itself(2) # In[19]: def sum_list(l): if len(l) == 0: return 0 return l[0] + sum_list(l[1:]) sum_list([1, 2, 3]) # # # WARNING: IF A FUNCTION CALLS ITSELF, IT MUST STOP AT SOME POINT # In[ ]: # WARNING # WARNING # WARNING # DO NOT RUN THIS CELL def calls_itself(x): print(x) return calls_itself(x - 1) calls_itself(2) # # Recursion # # When a function calls itself, it is called _recursion_. This is a powerful, yet confusing concept. # In[29]: def nth_power(x, nth): if nth == 0: return 1 return x * nth_power(x, nth - 1) nth_power(2, 5) # In[24]: def fibonacci(n): if n < 0: return 0 if n == 0 or n == 1: return n return fibonacci(n - 1) + fibonacci(n - 2) fibonacci(8) # In[26]: def factorial(x): if x == 1: return 1 return x * factorial(x - 1) factorial(5) # In[31]: def sum_n(n): if n == 1: return 1 return n + sum_n(n - 1) sum_n(5) # In[32]: def reverse(s): if len(s) == 0: return s else: return reverse(s[1:]) + s[0] reverse("hi") # In[35]: def is_palindrome(s): if len(s) <= 1: return True return (s[0] == s[-1]) and is_palindrome(s[1:-1]) print(is_palindrome("abccba")) print(is_palindrome("abcba")) print(is_palindrome("abcbab")) # In[ ]: