114k views
1 vote
a.Write a Python function sum_1k(M) that returns the sum푠푠= ∑1푘푘푀푀푘푘=1b.Compute s for M = 3 by hand and write another function test_sum_1k() that calls sum_1k(3) and checks that the answer is correct. When you call the sum_1k(3) function, you will see some messages according to if the test is successful or not.

User Msln
by
5.0k points

1 Answer

5 votes

Answer:

def sum_1k(M):

s = 0

for k in range(1, M+1):

s = s + 1.0/k

return s

def test_sum_1k():

expected_value = 1.0+1.0/2+1.0/3

computed_value = sum_1k(3)

if expected_value == computed_value:

print("Test is successful")

else:

print("Test is NOT successful")

test_sum_1k()

Step-by-step explanation:

It seems the hidden part is a summation (sigma) notation that goes from 1 to M with 1/k.

- Inside the sum_1k(M), iterate from 1 to M and calculate-return the sum of the expression.

- Inside the test_sum_1k(), calculate the expected_value, refers to the value that is calculated by hand and computed_value, refers to the value that is the result of the sum_1k(3). Then, compare the values and print the appropriate message

- Call the test_sum_1k() to see the result

User Nick Canzoneri
by
5.4k points