# python之捕鱼问题

python 同时被 2 个专栏收录
19 篇文章 0 订阅
14 篇文章 1 订阅

2018.03.04
auther:wills

##### 先从正向捕鱼说起

fish = 1
while True
flag = 1
for _ in range(5):
if (fish - 1)%5==0:
fish = (fish - 1)//5*4
else:
flag = 0
break
if flag:
print(fish)
break
fish += 1


#### 这段代码我已运行就进入死循环，找了半天都没找到问题点，最后才发现我从fish=1开始，进入if语句后fish被修改为0，然后又fish+=1，进入了死循环。修改后代码如下

fish = 1
while 1:
flag = 1
total = fish
for _ in range(5):
if (total - 1)%5==0:
total = (total -1)//5*4
else:
flag = 0
if flag:
print(fish)
break
fish += 1


#### 逆向思维，假设第五个人分鱼后剩下的鱼为fish，这样分鱼过程就只有4次，可以少一个循环代码如下

for fish in range(1,10000):
for n in range(4)：
if (fish -1 )%5 == 0 and fish%4 == 0：
fish = fish//4*5+1
if n ==3:
print(fish)
# else:
#     break

#### 下面这个while＋for循环的办法可以更高的提高代码执行速度，不过稍微需要多加几个变量

fish = 1
flag = 1
while flag:
total = fish
for n in range(4):
if (total-1)%5==0 and total%4==0:
total = total//4*5+1
if n==3:
print(fish)
print(total)
flag =0
fish += 1

#### 下面我把4种捕鱼代码都放到一起，并且使用了一个time函数来进行计时，比较几种代码的运行效率

from time import time
a1 = time()
fish = 1
while 1:
flag = 1
total = fish
for _ in range(5):
if (total - 1)%5==0:
total = (total -1)//5*4
else:
flag = 0
if flag:
print(fish)
break
fish += 1
a2 = time()
for fish in range(1,10000):
for n in range(4):
if (fish -1 )%5 == 0 and fish%4 == 0:
fish = fish//4*5+1
if n ==3:
print(fish)
a3 = time()
for fish in range(1,10000):
for n in range(4):
if (fish -1 )%5 == 0 and fish%4 == 0:
fish = fish//4*5+1
if n ==3:
print(fish)
else:
break
a4 = time()

fish = 1
flag = 1
while flag:
total = fish
for n in range(4):
if (total-1)%5==0 and total%4==0:
total = total//4*5+1
if n==3:
print(fish)
print(total)
flag =0
fish += 1

a5 = time()
print(a2-a1)
print(a3-a2)
print(a4-a3)
print(a5-a4)


#### 可以看出第二种代码最简洁，但是运行速度最慢，第四种虽然有点冗长，但是运行速度是最快的。那么众位看官，你们会选哪一种呢。

• 3
点赞
• 0
评论
• 4
收藏
• 一键三连
• 扫一扫，分享海报

09-17

09-15 8588
11-19 496
08-08 1734
04-26 416
11-25 423
06-21 1万+
07-03 1506
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。