This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def myLog(x, b): | |
''' | |
x: a positive integer | |
b: a positive integer; b >= 2 | |
returns: log_b(x), or, the logarithm of x relative to a base b. | |
''' | |
if x < b: | |
return 0 | |
return myLog(x / b, b) + 1 | |
## test | |
# myLog(27, 3) | |
# 3 | |
# myLog(26, 3) | |
# 2 | |
# myLog(4, 16) | |
# 0 | |
def laceStrings(s1, s2): | |
""" | |
s1 and s2 are strings. | |
Returns a new str with elements of s1 and s2 interlaced, | |
beginning with s1. If strings are not of same length, | |
then the extra elements should appear at the end. | |
""" | |
s1 = list(s1) | |
i = 0 | |
for j in s2: | |
s1.insert(i + 1, j) | |
i += 2 | |
result = '' | |
for k in s1: | |
result += k | |
return result | |
## test | |
# laceStrings('aaaaaa', 'zzzzzz') | |
# 'azazazazazaz' | |
# laceStrings('', '') | |
# '' | |
# laceStrings('af', 'cdizxtau') | |
# 'acfdizxtau' | |
# laceStrings('mqjkxtav', 'sk') | |
# 'msqkjkxtav' | |
def laceStringsRecur(s1, s2): | |
""" | |
s1 and s2 are strings. | |
Returns a new str with elements of s1 and s2 interlaced, | |
beginning with s1. If strings are not of same length, | |
then the extra elements should appear at the end. | |
""" | |
def helpLaceStrings(s1, s2, out): | |
if s1 == '': | |
return out + s2 | |
if s2 == '': | |
return out + s1 | |
else: | |
return helpLaceStrings(s1[1:], s2[1:], out + s1[0] + s2[0]) | |
return helpLaceStrings(s1, s2, '') | |
def McNuggets(n): | |
""" | |
n is an int | |
Returns True if some integer combination of 6, 9 and 20 equals n | |
Otherwise returns False. | |
""" | |
if n < 0: | |
return False | |
elif n == 0: | |
return True | |
else: | |
return any(McNuggets(n - x) for x in [6, 9, 20]) | |
## test | |
# McNuggets(236) | |
# True | |
# McNuggets(146) | |
# True | |
# McNuggets(239) | |
# True | |
# McNuggets(16) | |
# False | |
def fixedPoint(f, epsilon): | |
""" | |
f: a function of one argument that returns a float | |
epsilon: a small float | |
returns the best guess when that guess is less than epsilon | |
away from f(guess) or after 100 trials, whichever comes first. | |
""" | |
guess = 1.0 | |
for i in range(100): | |
if abs(f(guess) - guess) < epsilon: | |
return guess | |
else: | |
guess = f(guess) | |
return guess |
没有评论:
发表评论