Write a function threshold(values, goal) that behaves
as follows. The first parameter is a sequence of numbers. The
second parameter is a single positive number. The function is
to return the smallest possible integer n such that
the sum of the first n numbers in the sequence is
greater than or equal to goal. For example,
If the goal is unachievable, the function should return 0.
Solution:
def theshold(data, goal):
total = 0
for k in range(len(goal)):
total += data[k]
if total > goal:
return 1+k # e.g., if data[0] pushed us over the goal, we needed 1 item
return 0 # if we reach this line, we were unsuccessful
Strings have many convenient behaviors, one of which is that you can test whether a pattern occurs in another string, using the syntax
pattern in originalwhich produces a boolean result.
We want you to implement this test from basic principles. Provide an implemenation of a function with calling signature
isSubstring(pattern, original)that returns True or False, depending on the given parameters. Furthermore, you must not rely on any of the built-in behaviors of the string class, other than the fact that you can determine their lengths and you can use indexing to retrieve a single character of a string at a given index. That is, you are allowed to use syntaxes such as len(original) or pattern[j], but you must not use any other features of the string class such as find, index, or slicking notation pattern[j:k]. Instead use control structures to look for the pattern yourself, presumably testing every possible placement of where it might occur within the original string, and then testing character-by-character to see if you find a match.
Solution:
def isSubstring(pattern, original):
for k in range(len(original)-len(pattern)+1):
# determine whether we find a match starting at original[k]
match = True # optimism
for j in range(len(pattern)):
if pattern[j] != original[j+k]:
match = False # so much for optimism...
break # for sake of efficiency
if match:
return True # we found a legitimate match
return False # if we get this far, no match was ever found