加拿大瑞尔森大学 Python习题 Lab 5
Lab 5 – CPS 106
This lab helps you practice recursion, string manipulation and numerical approximation.
1. Find a given element in a list using a recursive function. The function is defined as find(elm_list, x), where elm_list is the input list and x is the element to be found. The function return the index of x if x is in the list, otherwise it returns -1.
Test you function with following:
[1.2, 3, 555, 66, 6, 35, 345, 345, 78, 12341],
x = 78,
x = 11
2. Write a function that computes the inner product of two lists. The inner product of two lists L1 and L2 of length n is defined as L1[0] * L2[0] + L1[1] * L2[1] + ... + L1[n – 1] * L2[n – 1]. If the lists are not of the same length, the function should return None.
Test your function with the following:
L1 = [8.17, 4.99, 16.56, 7.31, 0.21, 16.18, 13.75, 11.28, 4.3, 17.79]
L2 = [17.68, 1.19, 2.64, 13.01, 8.5, 15.04, 0.3, 18.72, 4.58, 9.66]
3. Write a function that extract a number from a string. The string can contain any character. The number you return is the concatenation of all the digits you find in the string. For example, the extracted number from the string “sk8dfjn*HG23Yh$%7-5~5” is 823755.
Test your function with the following:
“1ksdj4sdf>R?387BDYGrrf%44@2”
4. Write a function that computes the sum
1 + 1 / 2**2 + 1 / 3**2 + ... + 1 / n**2
for a given integer n. For large n, this sum converges to pi**2 / 6 where pi = 3.141592653589793. How large should n be for the sum to be within distance 0.001 of pi**2 / 6?
代码
5-1
5-2
5-3
5-4
5-4-2