这是一个模拟程序,大力神与九头蛇交战,由几轮组成。如果假设大力士击败了九头蛇,它应该输出Result: Hercules defeats Hydra in "i" rounds.如果它超过100轮,那么它应该输出:Hydra defeated Hercules。下一件事是:如果每轮后的头部大小为1,则通过。如果head大小大于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作为示例,输出应该是这样的:
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: ' '我在这里做错了什么?
发布于 2014-04-27 10:45:55
大块头
stat = stat.strip()
initHydraHeads = []
for i in range(len(stat)):
initHydraHeads.append(int(stat[i]))已经坏了。遍历数字之间包含空格的字符串。和tese空格中断int()转换。最好使用下面这样的代码:
heads = [int(x) for x in stat.split()]因此,顺便说一句,你不仅会得到数字,还会得到整数。
https://stackoverflow.com/questions/23318597
复制相似问题