This is a basic exercise on using loops.
######################Free Code###########################
## good old == is fine for everything else.
def close_enough(x,y):
"""prec: x, y are numbers
postc: returns True if x and y are close enough for
our purposes. use this to check for "equality" of
floating-point numbers."""
return abs(x - y) < 1e-6
######################Problem 0###########################
def meanie(x):
"""prec: x is non-empty numerical list
postc: returns the mean of x."""
total = 0
for k in x:
total += k
return total/len(x)
######################Problem 1###########################
def count_down(n):
"""prec: n is an integer and n >= 0
post: returns a countdown string. FOr example
count_down(10) returns "10 9 8 7 6 5 4 3 2 1 0 Blastoff!"
"""
return ""
######################Problem 2###########################
def trimmed_sum(x, a):
"""prec: x is a numerical list, and a is a number
postc: computes the sum of all value in the list x
that are <= a."""
return 0
######################Problem 3###########################
def median(x):
"""precondition: x is a numerical list
postcondtion: returns the median of x. This is the
middle value in numerical order if the length is odd and the
average of the two middle values if the length is even."""
return 0
######################Problem 4###########################
def sigma(f, n):
"""precondition: f is a function defined on the nonnegative
integers, and n is a nonnegative integer.
postcondition: returns sum(f(k), k = 0..n)."""
return 0
######################Problem 5###########################
def seek_string(quarry, file_name):
"""precondition: quarry and file_name are strings
postcondtion: if the file named by file_name does not
exist, return the string "(file_name) not found."
If it does, return a list containing all lines of
the file in which the string quarry is a substring of the line."""
if __name__ == "__main__":
#This is what my testing code looks like.
#feel free to crib it and bend it to your purposes.
print("****************** Test Problem 0****************")
x = [1,2,3,4,5,6]
y = 3.5
print(f"Case x = {x}: ", end = "")
print("PASS" if close_enough(meanie(x),y) else "FAIL")
x = [-2, -1, 0, 1, 2]
y = 0
print(f"Case x = {x}: ", end = "")
print("PASS" if close_enough(meanie(x),y) else "FAIL")
In case you have forgotten, it's very easy to iterate
through a file a line at a time. Download the file
linewise.py
to see how to do this.