这是一个模拟程序,Hercules与Hydra战斗,它由圆形组成。如果让我们说Hercules击败Hydra,它应该输出Result: Hercules defeats Hydra in "i" rounds.
如果它超过100轮,那么它应输出:Hydra defeated Hercules
。接下来是:如果每轮后的头部大小为1,则它会通过。如果头部大小大于1,那么它会增加“headize // 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
作为示例,这是输出的外观:
Please input name of file to read: hydra.txt
Hercules' strategy: smallest
Initial Heads: [8, 7, 3]
Hydra Growth Period: 10
文本文件应该如下所示:
smallest
8 7 3
10
所以我正在运行该程序,它给了我一个错误:
initHydraHeads.append(int(stat[i]))
ValueError: invalid literal for int() with base 10: ' '
我在这里做错了什么?
答案 0 :(得分:0)
块
stat = stat.strip()
initHydraHeads = []
for i in range(len(stat)):
initHydraHeads.append(int(stat[i]))
坏了。您遍历包含数字之间空格的字符串。并且tese space会中断int()
转换。最好使用这样的东西:
heads = [int(x) for x in stat.split()]
因此顺便提一下,您不仅可以获得数字,还可以获得整个数字。