天天看点

Python第四周:函数与递归函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32502811/article/details/51160127

第一题:

题目内容:

一个斐波那契数列的前10项为:1, 2, 3, 5, 8, 13, 21, 34, 55, 89,对于一个最大项的值不超过n的斐波那契数列,求值为偶数的项的和。

输入格式:

一个正整数n,如100。

输出格式:

值为偶数的项的和,如 2 + 8 + 34 = 44。

输入样例:

100

输出样例:

44

```python

n = int(raw_input())
number = 1
even_sum = 0
def fib(num):
    if num == 1 or num == 2:
        return 1
    else:
        i = 2
        f1 = 1
        f2 = 1
        while i < num:
            f3 = f1 + f2
            f1 = f2
            f2 = f3
            i += 1
        return f3
def is_even(num):
    if num % 2 == 0:
        return True
    else:
        return False
while fib(number) < n:
    if is_even(fib(number)):
        even_sum += fib(number)
    number += 1
print even_sum
           

第二题:

若已知1800年1月1日为星期3,则对于一个给定的年份和月份,输出这个月的最后一天是星期几。

两行整数,分别代表年份和月份

星期数,0代表星期日

2033

12

6

```python
y=int(raw_input())
m=int(raw_input())
def is_leapyear(year):
    if year%4==0 and year%100!=0 or year%400==0:
        return True
    else:
        return False
def month_days(year,month):
    if month in (1,3,5,7,8,10,12):
        return 31
    elif month in (4,6,9,11):
        return 30
    elif is_leapyear(year):
        return 29
    else:
        return 28
def get_all_days(year,month):
    days=0
    for i in range(1800,year):
        if is_leapyear(i):
            days += 366
        else:
            days+=365
    for j in range(1,month+1):
        days += month_days(year,j)
    return days
def get_endday(year,month):
    return (2+get_all_days(year,month))%7
print get_endday(y,m)           

第三题

如在汉诺塔游戏中,我们希望将塔A上的n个盘子,通过塔B移动到塔C,则对于任意输入的n,给出移动的步骤。

一个正整数n

移动的步骤

2

Move 1 from A to B

Move 2 from A to C

Move 1 from B to C

```python
def hanoi(n,A,B,C):
    if n==1:
        print "Move",n,"from",A,"to",C
    else:
        hanoi(n-1,A,C,B)
        print "Move",n,"from",A,"to",C
        hanoi(n-1,B,A,C)
n=int(raw_input())
hanoi(n,'A','B','C')