Problem 1
Consider the following function definition:
def integerDivision(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the integer division of x divided by a.
"""
while x >= a:
count += 1
x = x - a
return count
When we call
print integerDivision(5, 3)
we get the following error message:
Traceback (most recent call last):
File "L7_Problem_5.py", line 15, in <module>
print integerDivision(5, 3)
File "L7_Problem_5.py", line 9, in integerDivision
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
Your task is to modify the code for integerDivision so that this error does not occur.
Analyze
Answer
def integerDivision(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the integer division of x divided by a.
"""
count = 0
while x >= a:
x = x - a
count += 1
return count
Problem 2
Consider the following function definition:
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
rem(x-a, a)
When we call
rem(2, 5)
==> IDLE returns 2.
When we call
rem(5, 5)
==> IDLE returns 0.
But when we call
rem(7, 5)
==> IDLE does not return anything!
Analyze
在递归时,要形成递归关系应当return到函数本身而并非调用。
Answer
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
return rem(x-a, a)
Problem 3
Consider the following function definition:
def f(n):
"""
n: integer, n >= 0.
"""
if n == 0:
return n
else:
return n * f(n-1)
When we call f(3) we expect the result 6, but we get 0.
When we call f(1) we expect the result 1, but we get 0.
When we call f(0) we expect the result 1, but we get 0.
So, what's the problem?
Analyze
先分析这个函数想要做什么。
此处的函数期望结果为n!,但是在终止时的返回值是错误的,应改为return 1。
Answer
def f(n):
"""
n: integer, n >= 0.
"""
if n == 0:
return 1
else:
return n * f(n-1)