白钱买百鸡
问题描述
鸡翁一值钱五,鸡母一值钱三,鸡雏三值钱一。百钱买百鸡,问鸡翁、鸡母、鸡雏各几何?
解决思路
穷举法:
def maiji():
cock = 0
hen = 0
for cock in range(20):
for hen in range(33):
for chicken in range(100):
if (cock + hen + chicken == 100) and (5*cock + 3*hen + chicken/3 == 100):
print("cock:" + str(cock) + "\then:" + str(hen) + "\tchicken:" + str(chicken))
if __name__ == "__main__":
maiji()
穷举法需要尝试太多次,效率太低,第三层小鸡的数量可以变为100-cock - hen
:
def maiji():
cock = 0
hen = 0
for cock in range(20):
for hen in range(33):
chicken = 100 - cock - hen
if (cock + hen + chicken == 100) and (5*cock + 3*hen + chicken/3 == 100):
print("cock:" + str(cock) + "\then:" + str(hen) + "\tchicken:" + str(chicken))
if __name__ == "__main__":
maiji()
借书方案
问题描述
当小明有5本新书要借给A、B、C这3位小朋友,且每人每次只能借1本时,则可以有多少种不同的借法?
解决思路
5本书(1、2、3、4、5)三个人(ABC)穷举法,第一个人借5次,第二个人只能借剩下的4本,第三个人只能借剩下的三本
def JieShuFangAn():
A = 1
B = 1
C = 1
count = 0
for A in range(5):
for B in range(4):
for C in range(3):
print("A:" + str(A) + "\tB:" + str(B) + "\tC:" + str(C))
count += 1
print(count)
if __name__ == "__main__":
JieShuFangAn()
优化:
①A取5本中随意一本,B取剩余四本中随意一本,C取剩余三本中随意一本,但这样列不出具体取书方案。
def JieShuFangAn():
count = 0
for A in range(1,6):
for B in range(1, 5):
for C in range(1, 4):
count += 1
print(count)
if __name__ == "__main__":
JieShuFangAn()
②AB取5本,在C处进入循环体之前首先判断a和b的取值,如果两者取值相同,则内层循环无须重复执行5次便可结束。
def JieShuFangAn():
i = 0
A = 1
while A <= 5:
B = 1
while B <= 5:
C = 1
while A != B and C <= 5:
if A != C and B != C:
print("A:%2d B:%2d C:%2d " % (A, B, C), end='')
i += 1
if i%4 == 0:
print()
C += 1
B += 1
A += 1
print(i)
if __name__ == "__main__":
JieShuFangAn()
打鱼还是晒网
问题描述
中国有句俗语是叫“三天打鱼两天晒网”。某人从1990年1月1日起开始“三天打鱼两天晒网”, 问这个人在以后的某一天中是在“打鱼”, 还是在“晒网”。
解决思路
(1)从1990年1月1日开始到指定日期的天数:
闰年2月29天,平年2月28天
闰年:能被4整除且不能被100整除 或者 能被400整除
1 3 5 7 8 10 12月为31天 一共7个月
4 6 9 11 为30天 一共4个月
(2)打鱼+晒网周期为5天
(3余数012打鱼;余数34晒网
# 打鱼还是晒网
# 平年一共31*8 + 30* 7 + 28 =365天 闰年365+1 = 366天
def dy_or_sw():
year = int(input("年份:"))
#year = 1991
if year < 1990:
print("日期从1990-1-1开始!")
return 0
#month = 2
#day = 1
month = int(input("月份:"))
day = int(input("日期:"))
now = totalday(year, month, day)
if now%5 == 1 or now%5 == 2 or now%5 == 3:
print("打鱼")
elif now%5 == 3 or now%5 == 4:
print("晒网")
# 计算1991.1.1到输入日期为第x天
def totalday(year, month, day):
permonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for year_1 in range(1990, year + 1):
if year_1 == 1990:
now = 0
elif ((year_1 - 1) % 4 == 0 and (year_1 - 1) % 100 != 0) or (year_1 - 1) % 400 == 0:
now += 366
else:
now += 365
# 月
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: # 闰年
for month_1 in permonth[:month]:
now += month_1
if month > 2:
now += 1
else:
for month_1 in permonth[:month]:
now += month_1
# 日
now = now + day
return now
if __name__ == "__main__":
dy_or_sw()