CodingNic

Functions

Functions Exercises

Functions 40 min read

Functions Exercises

Objectives

This chapter introduces no new concepts. It’s a chance to put functions, parameters, scope, and recursion together across a wide range of small problems.

Part I: Write These Functions

difference

Takes two parameters and returns the difference between them.

python
difference(2, 2)  # 0
difference(0, 2)  # -2

product

Takes two parameters and returns their product.

python
product(2, 2)  # 4
product(0, 2)  # 0

Takes a number from 1–7 and returns the corresponding day of the week (1 is Sunday, 2 is Monday, and so on). Returns None if the number is out of range.

python
print_day(4)   # "Wednesday"
print_day(41)  # None

last_element

Takes a list and returns its last value, or None if the list is empty.

python
last_element([1, 2, 3, 4])  # 4
last_element([])            # None

number_compare

Takes two numbers. Returns "First is greater", "Second is greater", or "Numbers are equal" as appropriate.

python
number_compare(1, 1)  # "Numbers are equal"
number_compare(1, 2)  # "Second is greater"
number_compare(2, 1)  # "First is greater"

single_letter_count

Takes a word and a letter, and returns how many times that letter appears, case-insensitively.

python
single_letter_count("amazing", "A")  # 2

multiple_letter_count

Takes a string and returns a dictionary of each letter mapped to how many times it appears.

python
multiple_letter_count("hello")   # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
multiple_letter_count("person")  # {'p': 1, 'e': 1, 'r': 1, 's': 1, 'o': 1, 'n': 1}

list_manipulation

Takes a list, a command ("remove" or "add"), a location ("end" or "beginning"), and (for "add") a value.

python
list_manipulation([1, 2, 3], "remove", "end")          # 3
list_manipulation([1, 2, 3], "remove", "beginning")    # 1
list_manipulation([1, 2, 3], "add", "beginning", 20)   # [20, 1, 2, 3]
list_manipulation([1, 2, 3], "add", "end", 30)         # [1, 2, 3, 30]

is_palindrome

Returns True if the input reads the same forwards and backwards. Bonus: ignore whitespace and capitalization, so is_palindrome('a man a plan a canal Panama') returns True.

python
is_palindrome("testing")  # False
is_palindrome("tacocat")  # True
is_palindrome("hannah")   # True
is_palindrome("robert")   # False

frequency

Takes a list and a search term, and returns how many times that value appears.

python
frequency([1, 2, 3, 4, 4, 4], 4)         # 3
frequency([True, False, True, True], False)  # 1

flip_case

Takes a string and a letter, and flips the case of every occurrence of that letter.

python
flip_case("Hardy har har", "h")  # "hardy Har Har"

multiply_even_numbers

Takes a list of numbers and returns the product of all the even ones.

python
multiply_even_numbers([2, 3, 4, 5, 6])  # 48

mode

Takes a list of numbers and returns the most frequent one. You can assume the mode is unique.

python
mode([2, 4, 1, 2, 3, 3, 4, 4, 5, 4, 4, 6, 4, 6, 7, 4])  # 4

capitalize

Takes a string and returns it with the first letter capitalized.

python
capitalize("erin")    # "Erin"
capitalize("jordan")  # "Jordan"

compact

Takes a list and returns only its truthy values.

python
compact([0, 1, 2, "", [], False, {}, None, "All done"])  # [1, 2, "All done"]

partition

Takes a list and a callback function. Runs the callback on each element, and returns two lists inside one: elements where the callback returned True, and elements where it returned False.

python
def is_even(num):
    return num % 2 == 0

partition([1, 2, 3, 4], is_even)  # [[2, 4], [1, 3]]

intersection

Takes two lists and returns the values common to both.

python
intersection([1, 2, 3], [2, 3, 4])  # [2, 3]

sum_digits (recursive)

Takes a positive integer and returns the sum of its digits, written recursively rather than with a loop.

python
sum_digits(1234)  # 10
sum_digits(5)     # 5

once

Takes a function and returns a new function that can only run once: every call after the first returns None. You’ll need to define a function inside once and track whether it’s already run (an attribute on the inner function works well for this, the same trick from the closures section in the Function Scope lesson).

python
def add(a, b):
    return a + b

one_addition = once(add)
one_addition(2, 2)     # 4
one_addition(2, 2)     # None
one_addition(12, 200)  # None

Bonus: once you’ve reached the decorators lesson later in this course, come back and rewrite once as a decorator, so it can be used like this:

python
@run_once
def add(a, b):
    return a + b

add(2, 2)   # 4
add(2, 20)  # None

Part II: More Practice

For extra practice applying functions to new problems, search Codewars for these kata by name:

  • Reversed Strings
  • Looking for a Benefactor
  • Sum of a Sequence
  • Max Diff
  • Count the Smiley Faces
  • Sentence Count
  • Tortoise Racing
  • Calculate String Rotation

Recap

You can now write functions with flexible parameters (including defaults, *args, and **kwargs), reason about scope, and document your functions with docstrings and type hints. That’s the toolkit Module 4 set out to build.

Next lesson: a mini project. Build a command-line quiz game using everything from this module.