In: Computer Science
# RQ3 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 ***" # RQ4 # Write functions c, t, and f such that calling the with_if_statement and # calling the with_if_function do different things. # In particular, write the functions (c,t,f) so that calling with_if_statement function returns the integer number 1, # but calling the with_if_function function throws a ZeroDivisionError. 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 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 ***"
RQ3
def largest_factor(n):
l=[]
for i in range(1,n):
if n%i==0:
l.append(i)
return l[-1]
print(largest_factor(15))
print(largest_factor(80))
Output
RQ4
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
def with_if_statement():
"""
>>> with_if_statement()
1
"""
if c(): #if c() is false then f() should be
executed and should return 1
return t()
else:
return f()
def with_if_function(): #should throw ZeroDivisionError
return if_function(c(), t(), f())
def c():
return False
def t():
return 2/0 #throws ZeroDivisionError
def f():
return 1
print(with_if_statement())
print(with_if_function())
Output