Question: PYTHON Required Question 1 We've seen that we can give new names to existing functions. Fill in the blanks in the following function definition for
PYTHON
Required Question 1
We've seen that we can give new names to existing functions. Fill in the blanks in the following function definition for addingato the absolute value ofb, without callingabs.
from operator import add, sub def a_plus_abs_b(a, b): """Return a+abs(b), but without calling abs. >>> a_plus_abs_b(2, 3) 5 >>> a_plus_abs_b(2, -3) 5 """ if b < 0: f = _____ else: f = _____ return f(a, b)
Required Question 2
Write a function that takes threepositivenumbers and returns the sum of the squares of the two largest numbers.Use only a single line for the body of the function.
def two_of_three(a, b, c): """Return x*x + y*y, where x and y are the two largest members of the positive numbers a, b, and c. >>> two_of_three(1, 2, 3) 13 >>> two_of_three(5, 3, 1) 34 >>> two_of_three(10, 2, 8) 164 >>> two_of_three(5, 5, 5) 50 """ return _____
Required Question 3
Write a function that takes an integerngreater than 1and returns the largest integer smaller thannthat evenly dividesn.
Hint: To check ifbevenly dividesa, you can use the expressiona % b == 0, which can be read as, "the remainder of dividingabybis 0."
def largest_factor(n): """Return the largest factor of n that is smaller than n. >>> largest_factor(15) # factors are 1, 3, 5 5 >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40 40 """ "*** YOUR CODE HERE ***"
Required Question 4
Let's try to write a function that does the same thing as anifstatement.
def if_function(condition, true_result, false_result): """Return true_result if condition is a true value, and false_result otherwise. >>> if_function(True, 2, 3) 2 >>> if_function(False, 2, 3) 3 >>> if_function(3==2, 3+2, 3-2) 1 >>> if_function(3>2, 3+2, 3-2) 5 """ if condition: return true_result else: return false_result
Despite the doctests above, this function actually doesnotdo the same thing as anifstatement in all cases. To prove this fact, write functionsc,t, andfsuch thatwith_if_statementreturns the number1, butwith_if_functiondoes not (it can doanythingelse):
def with_if_statement(): """ >>> with_if_statement() 1 """ if c(): return t() else: return f() def with_if_function(): return if_function(c(), t(), f()) def c(): "*** YOUR CODE HERE ***" def t(): "*** YOUR CODE HERE ***" def f(): "*** YOUR CODE HERE ***"
To test your solution, open an interactive interpreter
and try calling bothwith_if_functionandwith_if_statement, and check thatwith_if_statementreturns a one (1) andwith_if_functionreturns something else (e.g., throws an exception).
Required Question 5
Implement the function keep(), which takes in a predicate pred and a number n, and only prints a number from 1 to n to the screen if it fulfills the predicate.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
