这是一个模拟程序,大力神与九头蛇搏斗,它由子弹组成。如果假设大力神击败了九头蛇,它应该输出Result: Hercules defeats Hydra in "i" rounds.
如果它超过100回合,那么它应该输出:Hydra defeated Hercules
。下一个问题是:如果每轮后的头部大小为1,则通过。如果头部大小大于1,则它将添加“headsize//2”的大小以在其所在位置重新增长。这只是模拟应该是什么样子的一点线索。在
from array_heap import*
###################################################################
#Function for the file reader #
###################################################################
def file():
"""
Opens the file and reads it for the simulation
"""
fileName = input("Enter file name: ")
fp = open(fileName)
line = fp.readline()
stat = fp.readline()
stat = stat.strip()
initHydraHeads = []
for i in range(len(stat)):
initHydraHeads.append(int(stat[i]))
growHydraHead = fp.readline()
return line, initHydraHeads, growHydraHead
###################################################################
#Starting the simulation #
###################################################################
def HydraHeadStartOfGame(initHydraHeads, line):
"""
Takes 2 arguments:
initHydraHeads
line
Returns an instance of the hydra head initially
"""
if line == "largest":
choise = greater
else:
choise = less
hHead = mkHeap((len(initHydraHeads) + 100), choise)
for i in range(len(initHydraHeads)):
add(hHead, initHydraHeads[i])
return hHead
def HydraHeadGrowBack(headsize, hHead):
"""
HydraHeadGrowBack function makes the head grow twice in size if the headsize is greater than 1
"""
if headsize == 1:
pass
else:
for i in range(2):
newHeads == headsize//2
add(hHead, newHeads)
return hHead
def headGrowbyOne(hHead, i):
"""
Makes the head grow by one after each round
"""
if i == 0:
pass
else:
for i in len(hHead.array):
hHead.array[i] += 1
return hHead
def main():
line, initHydraHeads, growHydraHead = file()
print("Hercules' strategy: ", line)
print("Initial Hydra Heads: ", initHydraHeads)
print("Hydra growth period: ", HydraHeadGrowBack)
hHead = HydraHeadStartOfGame(initHydraHeads, line)
#print(removeMin(hHead))
i = 0
while i < 100: #100 means 100 rounds
headGrowbyOne(hHead, i)
if hHead.size == 0:
print("Hercules wins, Hydra is dead!")
print("Result: Hercules slays the hydra after ", i, "rounds")
break;
else:
print("Current size: ", hHead.size)
severedHead = removeMin(hHead)
HydraHeadGrowBack(severedHead, hHead)
print(hHead.array)
i += 1
main() #run the program
例如,输出应该是这样的:
^{2}$文本文件应该如下所示:
smallest
8 7 3
10
所以我在运行程序,它给了我一个错误:
initHydraHeads.append(int(stat[i]))
ValueError: invalid literal for int() with base 10: ' '
我在这里做错什么了?在
大块
坏了。遍历包含数字之间空格的字符串。和tese空格中断
^{pr2}$int()
转换。最好用这样的方法:因此,你不仅可以得到数字而且可以得到完整的数字。在
相关问题 更多 >
编程相关推荐