python:
用户定义函数,递归函数相关问题
- 判断一个数即是素数,又是回文数
num=222;
def is_palin(num):
num_p=0;
num_t=num;
while num_t !=0:
num_p=num_p*10+num_t%10;
num_t=num_t/10;
if num_p==num:
return True;
else :
return False;
def is_prime(num):
for i in range(2,num):
if num%i == 0:
return False;
return True;
if is_palin(num) and is_prime(num):
print "ok";
else :
print "no";
2.汉诺塔问题(递归)
将前 n-1 个盘子,通过 C,从 A 移动到 B
从 A 到 C 移动第 n 个盘子
将前 n-1 个盘子,通过 A,从 B 移动到 C
def hanoi(n,A,B,C):
global count;
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');
优势(strength):它能使一个蕴含递归关系且结构复杂的程序简洁精炼, 增加可读性 特别是在难于找到从边界到解的全过程的情况下,如果把问题推进一步,其结果仍维持原问题的关系。
劣势(weakness) :嵌套层次深,函数调用开销大 重复计算
3.日历相关
题目内容:
若已知1800年1月1日为星期3,则对于一个给定的年份和月份,输出这个月的最后一天是星期几。
输入格式:
两行整数,分别代表年份和月份
输出格式:
星期数,0代表星期日
输入样例:
2033
12
输出样例:
6
时间限制:500ms内存限制:32000kb
def is_leap_year(Year):#判断闰年
if Year % 4 == 0 and Year % 100 != 0 or Year % 400 == 0:
return True
else:
return False
def year_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_leap_year(Year):
return 29
else:
return 28
def year_days(Year):
if is_leap_year(Year):
return 366
else:
return 365
def weekday_year_month(Year, Month):
Weekday = 2
for year in range(1800, Year):
Weekday = (Weekday + year_days(year) ) % 7
for month in range(1, Month + 1):
Weekday = (Weekday + year_month_days(Year, month)) % 7
print Weekday
Y = int(raw_input())
M = int(raw_input())
weekday_year_month(Y, M)