def countUniqueDigits(n):
# This function takes an int n and returns the number of unique digits in n.
n = abs(n)
if n == 0:
return 1
digits = [ ]
while n > 0:
d = n % 10
if __________________:
digits.append(d)
n //= 10
return len(digits)
def testCountUniqueDigits():
assert(countUniqueDigits(12312111) == 3) # 1, 2, 3
assert(countUniqueDigits(-4444444) == 1) # 4
assert(countUniqueDigits(0) == 1) # 0
d not in digits
import copy
def findMedian(L):
# This function takes a non-empty list L of integers and returns the median,
# which is the middle value if the list is sorted (or the average
# of the middle two values if the list has an even number of values).
# Note that there are far better ways to do this. :-)
assert(len(L) > 0)
L = copy.copy(L)
while len(L) > 2:
for v in [min(L), max(L)]:
L.remove(v)
return __________________
def testFindMedian():
assert(findMedian([1,2,3]) == 2)
assert(findMedian([1,3,2]) == 2)
assert(almostEqual(findMedian([1,3,2,4]), 2.5)) # (2 + 3)/2
Here are two valid answers:
sum(L) / len(L)
L[0] if len(L) == 1 else (L[0] + L[1])/2
def isRectangular(L):
# This function takes a possibly-ragged 2d list L and returns True if
# L is rectangular, and False otherwise.
M = [len(rowList) for rowList in L]
return M == __________________
def testIsRectangular():
assert(isRectangular([[1, 2], [3, 4]]) == True)
assert(isRectangular([[1, 2], [3, 4, 5]]) == False)
[M[0]] * len(M)
def capitalize(s):
# This function takes a string s of words separated by spaces,
# and returns the string where the first letter
# of each word is capitalized and all other letters are lowercase.
# Note that ther are better ways to do this. :-)
t = ''
inSpace = __________________
for c in s:
if c == ' ':
t += c
inSpace = True
elif inSpace:
t += c.upper()
inSpace = False
else:
t += c.lower()
return t
def testCapitalize():
assert(capitalize('this IS a tEsT') == 'This Is A Test')
True
def cubeRoot(n):
# This function takes a non-negative number n and uses bisection to approximate
# the cube root of n.
# You may wish to review findZeroWithBisection from Hw2.
assert(n >= 0)
lo = 0
hi = n
epsilon = 10**-10
while (hi - lo > epsilon):
mid = (lo + hi)/2
if __________________ > n:
hi = mid
else:
lo = mid
return mid
def testCubeRoot():
assert(almostEqual(cubeRoot(27), 3))
assert(almostEqual(cubeRoot(3.14**3), 3.14))
mid**3