欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)

程序员文章站 2022-03-31 10:06:55
...

1.给定一个具体的年份和月份输出这个月的日历(1900年1.1是星期一)
设计的流程如下

2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)
2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)



def print_month(year,month):
    print("             {}          {}       ".format(get_month_name(month),year))
    print("----------------------------------")
    print("    Sun Mon Tue Wed Thu Fri Sat   ")
    days=0
    if month in (1, 3, 5, 7, 8, 10, 12):
        days = 31
    elif month in (4, 6, 9, 11):
        days = 30
    elif is_leap_year(year):
        days = 29
    else:
        days = 28

    for i in range(1,days+1):
        if i ==1:
            print(" "*get_start_day(year,month),end="")
        print(" {}".format(i),end="")
        if (get_start_day(year,month)+i)%7==0:
            print(" ")

    pass

def get_month_name(month):
    m_list=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"]
    return m_list[month-1]
    pass

def is_leap_year(year):
    if(year%400==0 or (year%4==0 and year%100!=0)):
        return True
    else:
        return False

    pass

def get_num_of_days_in_month(year,month):
    days=0
    for i in range (1900,year):
        if is_leap_year(i):
            days+=366
        else:
            days+=365
    for i in range(1,month):
        if i in (1,3,5,7,8,10,12):
            days+=31
        elif i in (4,6,9,11):
            days+=30
        elif is_leap_year(year):
            days+=29
        else:
            days+=28
    return days

    pass

def get_start_day(year,month):
    return (get_num_of_days_in_month(year,month)+1)%7
    pass


input_year=int(input("输入年份"))
input_month=int(input("输入月份"))
print(get_start_day(input_year,input_month))
print_month(input_year,input_month)

运行结果如下
2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)

2.递归函数(汉诺塔)
递归函数的本质是自身调用自身,将一个大问题拆分成若干个小问题而且这些小问题也是同构的
2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)
2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)
2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)

2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)
2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)

问题二
2018/8/23(python学习之关于递归函数的理解于,,输出某个月的日历,,路边停车,,汉诺塔)

import random
count=0
def hannoi(n,A,B,C):
    global count
    if n==0:
        return
    else:
        hannoi(n-1,A,C,B)
        print("move {} from {} to {}".format(n, A, C))
        count+=1
        hannoi(n-1,B,A,C)
def parking(low,high):  #停车问题 即设马路有low到hign这么长 每辆车长1 问平均能停多少
                         #分解为停的这辆车前面能停多少加上后面能停多少
                         #而前面与后面能停多少辆车又回到了原问题
    if high-low<1:
        return 0
    else:
        x=random.uniform(low,high-1)
        return print(low,x)+1+print(x+1,high)

    pass
hannoi(7,"left","mid","right")
print(count)

print(parking(0,10))
相关标签: 递归