Python Functions Exercises¶
Programming for Data Science Bootcamp
Functions¶
Exercise 1¶
Write a function with these requirements:
- takes two inputs: a string and an integer
- returns
True
if the string length is equal to the integer, elseFalse
- Don't worry about error checking
Then call the function, passing the following inputs:
"Is this text the right length?"
for the string30
for the integer
Verify the output is True
. Try other combinations.
def verify_string_length(text, val):
"""
PURPOSE: check if the length of text is equal to a value
INPUTS:
text str
val integer
OUTPUTS:
check bool
"""
return len(text) == val
txt = "is this text the right length?"
val = 30
out = verify_string_length(txt, val)
out
True
verify_string_length("The foul occurred after the buzzer.", 10)
False
Exercise 2¶
Write a function with these requirements:
- uses the argument unpacking operator, e.g.
*args
, for the input argument - squares each argument then prints the value. You can use a
for
loop. - returns
None
Call the function, passing at least two integers.
Recall that the *
operator allows your function to taken an arbitrary number of arguments and treats them all as a single tuple.
def square_args(*vars):
for var in vars:
print(var**2)
return None
square_args(2,3,8)
4 9 64
This works, too:
list_o_nums = [10, 100, 5, 62, 42]
square_args(*list_o_nums)
100 10000 25 3844 1764
It's the same as this:
square_args(10, 100, 5, 62, 42)
100 10000 25 3844 1764
Exercise 3¶
Write a function called make_numeronym()
that takes a long word and replaces it
with a string that has the same first and last letters capitalized,
and replaces the middle letters with the number of middle letters.
For example, "internationalization" would be returned as "I18N".
Make sure it only accepts strings and that they have a minimum length of $4$.
Include a short docstring.
Hint: You can use isinstance()
to check the variable type.
def make_numeronym(long_word):
"""Converts a long word into word with
internal letters replaced by their count."""
# Validate data type
if not isinstance(long_word, str):
print(f"{long_word} is a {type(long_word)}, not a string!")
return False
# Validate word length
elif len(long_word) < 4:
print(f"{long_word} is too short. \
Put in a word at least {min_len} letters long.")
return False
# Do the work ...
else:
first_letter = long_word[0].upper()
last_letter = long_word[-1].upper()
middle_number = len(long_word[1:-1])
new_word = first_letter + str(middle_number) + last_letter
return new_word
make_numeronym('localization')
'L10N'
Here's a more concise version:
def make_numeronym2(long_word):
"""Converts a long word into word with
internal letters replace by their count."""
# Validate
if not isinstance(long_word, str) or len(long_word) < 4:
print(f"{long_word} not a string or too short.")
return False
# Do the work ...
return f"{long_word[0]}{len(long_word[1:-1])}{long_word[-1]}"\
.upper()
make_numeronym2("antidisestablishmentarianism")
'A26M'
And here's a one-liner version:
get_shorty = lambda x: f"{x[0]}{len(x[1:-1])}{x[-1]}".upper() \
if isinstance(x, str) and len(x) > 3 else None
get_shorty("operationalization")
'O16N'
Exercise 4¶
Define a function with these requirements:
- take one numeric (integer or float) value as input
- subtract $5$ from the value
- return $1$ if the difference is non-negative, else return $0$
- don't worry about error checking or docstring
Call the function on different values to test it.
def thunk(x):
diff = x - 5
if diff >= 0:
return 1
return 0
samples = [5, 10, 4, 30]
results = [thunk(s) for s in samples]
results
[1, 1, 0, 1]
Shorter versions:
def thunk2(x):
return 1 if x - 5 >= 0 else 0
thunk2(4)
0
def thunk3(x):
return int(x - 5 >= 0)
thunk3(6.5)
1
Scope¶
Exercise 5¶
Write a function that defines and prints a variable called secret_x
.
Show that calling this variable outside the function produces an error.
def my_func():
secret_x = 5
print(secret_x)
my_func()
5
print(secret_x)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[92], line 1 ----> 1 print(secret_x) NameError: name 'secret_x' is not defined
Exercise 6¶
Read the following code blocks (to be displayed).
For each block predict what the output will be.
Try predicting without writing code.
def print_me():
print(x1)
print_me()
def print_me():
print(x1)
print_me()
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[93], line 4 1 def print_me(): 2 print(x1) ----> 4 print_me() Cell In[93], line 2, in print_me() 1 def print_me(): ----> 2 print(x1) NameError: name 'x1' is not defined
def print_me2():
x2 = 5
print(x2)
print_me2()
def print_me2():
x2 = 5
print(x2)
print_me2()
5
x2 = 7
print_me2()
x2 = 7
print_me2()
5
x2 = 7
print_me2()
print(x2)
x2 = 7
print_me2()
print(x2)
5 7
def print_me3(x3):
print(x3)
x3 = 9
print_me3()
print_me3(x3)
print_me3()
print(x3)
def print_me3(x3):
print(x3)
x3 = 9
print_me3()
print_me3(x3)
print_me3()
print(x)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[32], line 5 2 print(x3) 4 x3 = 9 ----> 5 print_me3() 6 print_me3(x3) 7 print_me3() TypeError: print_me3() missing 1 required positional argument: 'x3'
def print_me4(x4=5):
print(x4)
x4 = 9
print_me4()
print_me4(x4)
print_me4()
print(x4)
def print_me4(x4=5):
print(x4)
x4 = 9
print_me4()
print_me4(x4)
print_me4()
print(x4)
5 9 5 9
Lambda Functions¶
Exercise 6¶
Write a lambda function to check if a value is in a range: $x >= 10$ and $x <= 20$
Call the function with different values to verify it works.
in_range = lambda x: x >= 10 and x <= 25
in_range(15)
True
in_range(0)
False
Exercise 7¶
Generalize the lambda function in_range
.
Call it in_range_general
.
Have it ake three inputs:
x
: the valuea
: lower boundb
: upper bound
Call the function with different x
, a
, b
to verify it works.
in_range_general = lambda x, a, b: x >= a and x <= b
in_range_general(0, 1, 10)
False
in_range_general(0, -1, 100)
True
Exercise 8¶
Write a lambda function called str_test
that checks if a given string is found in another string.
Return True
if found, otherwise False
.
In other words, check if a string is a substring of another.
Call the function with different inputs to verify it works.
str_test = lambda s1, s2: s2 in s1
str_test("Opera is fun", "is")
True
str_test("Opera is fun", "gasket")
False
Exercise 9¶
Write three lambda functions:
c2f
that converts a Celsius (C) value to Farenheit (F), given $F = 1.8C + 32$.f2c
that converts an F value to C, given $C = (F - 32)/1.8$t2t
that combines the two previous functions and takes two arguments:- an integer representing the known temperature in either F or C.
- a character representing the unknown temparture scale to convert to, either 'f' or 'c'.
Have t2t
return an integer value.
For example, if have a temperature of $45$ C and want to know what this is in F, it should work like this:
>>> f = t2t(45, 'f')
>>> print(f)
>>> 113
c2f = lambda cval: 1.8 * cval + 32
c2f(45)
113.0
f2c = lambda fval: (fval - 32) / 1.8
f2c(113)
45.0
t2t = lambda tval, target: int(f2c(tval) if target == 'c' \
else c2f(tval))
t2t(45, 'f')
113
Here's another way:
targets = {
'f': c2f,
'c': f2c
}
t2t = lambda tval, target: int(targets[target](tval))
t2t(45, 'f')
113
Or, more compactly:
targets = {
'f': lambda cval: 1.8 * cval + 32,
'c': lambda fval: (fval - 32) / 1.8
}
t2t = lambda tval, target: int(targets[target](tval))
t2t(45, 'f')
113
The most compact:
t2t = lambda tval, target: \
int({'f': lambda cval: 1.8 * cval + 32, 'c': \
lambda fval: (fval - 32) / 1.8}[target](tval))
t2t(45, 'f')
113
Recursion¶
Exercise 10¶
The Fibonacci sequence looks like this:
$1, 1, 2, 3, 5, 8, 13, 21, ...$
Series like this can be expressed as a recursive function involving preceding values and positional numbers.
To generate it, you can imagine doing something like this:
Fib(1) = Fib(2) = 1
Fib(3) = Fib(2) + Fib(1) = 1 + 1 = 2
Fib(4) = Fib(3) + Fib(2) = 2 + 1 = 3
Fib(5) = Fib(4) + Fib(3) = 3 + 2 = 5
Fib(6) = Fib(5) + Fib(4) = 5 + 3 = 8
Use this pattern to generate the next $2$ terms (by hand).
Fib(7) = Fib(6) + Fib(5) = 8 + 5 = 13
Fib(8) = Fib(7) + Fib(6) = 13 + 8 = 21
Now, write a Python function fibonacci()
to return the $n^{th}$ term in the sequence.
Specifically, write the function with these requirements:
- takes an integer
n
as input - includes the rules that defines the sequence
- computes the $n^{th}$ term in the sequence, using recursion (the function will call itself)
- returns the computed term
- expects
n
to an integer $> 0$, but don't do error checking
Call fibonacci(n)
for $n = 1, 2, 3, 4, 5, 6$ and verify it works properly.
def fibonacci(n):
if n in [1,2]:
return 1
return fibonacci(n-1) + fibonacci(n-2)
for n in range(1,7):
print(f"{n}:", fibonacci(n))
1: 1 2: 1 3: 2 4: 3 5: 5 6: 8
Exercise 11¶
Try writing a function to create the Fibonacci sequences without using recursion.
The function should take a parameter n
for the length of the sequence.
It should return a list that is initialized as [1,1]
.
def fibo(n):
if not isinstance(n, int) or n < 3:
return "Try using an integer greater than 2."
seq = [1,1]
for i in range(3, n+1):
seq.append(sum(seq[-2:]))
return seq
fibo(7)
[1, 1, 2, 3, 5, 8, 13]
Exercise 12¶
Write a Python program that allows users to play the MadLibs® game, using the example story sheet provided.
Capture the values for each blank by using the input()
function.
This is an example of MadLib story sheet:
plaintext
Today I went to the zoo. I saw a(n) ___________(adjective)
_____________(Noun) jumping up and down in its tree.
He _____________(verb, past tense) __________(adverb)
through the large tunnel that led to its _______(adjective)
__________(noun). I got some peanuts and passed
them through the cage to a gigantic gray _______(noun)
towering above my head. Feeding that animal made
me hungry. I went to get a __________(adjective) scoop
of ice cream. It filled my stomach. Afterwards I had to
__________(verb) __________ (adverb) to catch our bus.
When I got home I __________(verb, past tense) my
mom for a __________(adjective) day at the zoo.
def madlibs1():
words = dict(adjective1 = '',
noun1 = '', verb_past_tense1 = '', adverb1 = '',
adjective2 = '', noun2 = '', noun3 = '', adjective3 = '',
verb1 = '', adverb2 = '', verb_past_tense2 = '', adjective4 = '')
for pos in words:
prompt = pos.replace('_', ' ')[:-1] # Assumes single digit suffix
words[pos] = input(f"Enter a(n) {prompt}: ")
text = f"Today I went to the zoo.\nI saw a(n) {words['adjective1']} \
{words['noun1']} jumping up and down in its tree.\n\
He {words['verb_past_tense1']} {words['adverb1']} through the large tunnel \
that led to its {words['adjective2']} {words['noun2']}.\nI got some peanuts and passed \
them through the cage to a gigantic gray {words['noun3']} \
towering above my head.\nFeeding that animal made \
me hungry.\nI went to get a {words['adjective3']} scoop \
of ice cream.\nIt filled my stomach.\nAfterwards I had to \
{words['verb1']} {words['adverb2']} to catch our bus.\n\
When I got home I {words['verb_past_tense2']} my \
mom for a {words['adjective4']} day at the zoo."
print(text)
madlibs1()
Today I went to the zoo. I saw a(n) green house jumping up and down in its tree. He ran quickly through the large tunnel that led to its happy carriage. I got some peanuts and passed them through the cage to a gigantic gray bacterium towering above my head. Feeding that animal made me hungry. I went to get a blue scoop of ice cream. It filled my stomach. Afterwards I had to flew mightily to catch our bus. When I got home I happened my mom for a fast day at the zoo.