Python includes exercises 76
Title: Write a function that input n is an even number, call the function evaluation 1/2 + 1/4 + ... + 1 / n, when the input n is odd, the function is called 1/1 + 1/3 + .. . + 1 / n (use the pointer function)
Program Analysis: None.
Source Code:
#!/usr/bin/python # -*- coding: UTF-8 -*- def peven(n): i = 0 s = 0.0 for i in range(2,n + 1,2): s += 1.0 / i return s def podd(n): s = 0.0 for i in range(1, n + 1,2): s += 1 / i return s def dcall(fp,n): s = fp(n) return s if __name__ == '__main__': n = int(raw_input('input a number:\n')) if n % 2 == 0: sum = dcall(peven,n) else: sum = dcall(podd,n) print sum
The above example output is:
input a number: 6 0.916666666667