題目
【問題描述】
有n個人圍成一圈,按順序從1到n編號。從第一個人開始報數,報數3的人退出圈子,下一個人從1開始重新報數,報數3的人退出圈子。如此循環,直到留下最後一個人。問留下來的人的編號。
【輸入形式】
考慮如下兩種情況:
如果n超出“n must be a natural number less than 10000”,則打印“n is out of range of valid values.”;其中n應該用如上輸入的具體的n數值代替;換行;
如果n是有效範圍的數值,則打印“Last No. is:”;然後直接在冒號後面輸出最後留下來的人的編號;換行;
思路
猴子選大王簡化版,設變量out,每當out=3,移除當前index,out清零,直到剩一個爲止
代碼
m = int(input('總數:'))
p = []
out = 0
index = 0
if(m>0 and m<=10000):
for i in range(1,m+1):
p.append(i)
while(len(p) > 1):
out += 1
index += 1
if (index > len(p)):
index = 1
if(out == 3):
out = 0
p.pop(index-1)
index -= 1
print("Last No. is", p[0])
else:
print(m, "is out of range of valid values.")
Python真是妙啊