Commit 06e58ee7 by yangpengflag

update

parent fddb87fe
'''
你和你的朋友,两个人一起玩 Nim游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
示例:
输入: 4
输出: false
解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
'''
def nim_game_by_recursive(stone_num):
if stone_num <= 0:
print("请输入大于0的整数")
return False
# 当轮到你拿时剩余的石块大于0小于4,你讲获胜
if stone_num > 0 and stone_num < 4 :
return True
# 使用递归判断,但是数字大的时候可能会出现递归太深的问题
return not(nim_game_by_recursive(stone_num-1) & nim_game_by_recursive(stone_num-2) & nim_game_by_recursive(stone_num-3))
print(nim_game_by_recursive(16))
print(nim_game_by_recursive(8))
print(nim_game_by_recursive(4))
print(nim_game_by_recursive(20))
print(nim_game_by_recursive(5))
print(nim_game_by_recursive(6))
print(nim_game_by_recursive(7))
#发现一个规律,只要被4整除都不可能赢。。。。
def nim_game(stone_num):
if stone_num % 4 != 0:
return True
else:
return False
print(nim_game(1))
print(nim_game(2))
print(nim_game(3))
print(nim_game(4))
print(nim_game(5))
print(nim_game(6))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment