我是 python 新手。我的代码陷入无限循环,不断添加和打印numberCycles
。我在 C++ 中的逻辑工作正常。你能帮忙找出原因吗?
- 第一行输入是模拟次数。
- 下一行是单个生殖周期的分钟数。
- 下一行是行数 (
x
),后跟一个空格,然后是列数 (y
)。 - 下一组 y 行将包含
x
多个字符,一个句点 (.
) 代表一个空格,一个大写字母B
代表一个开始的 Bunny 尝试复制到up
,right
,down
,left
方向。如果有一个现有的兔子,那么它会进入睡眠状态。
输入.txt
2 # 2 simulations
5 # 5 minutes/cycle
3 3 # 3*3 map
...
.B.
...
1
4 4
B.BB
..B.
...
B.B
现货.py
#!/usr/bin/env python
class Spot(object):
isBunny = bool()
nextCycle = 0
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
SLEEP = 4
def __init__(self, newIsBunny):
self.isBunny = newIsBunny
self.nextCycle = self.UP
def setNextCycle(self):
if (self.nextCycle != self.SLEEP):
self.nextCycle += 1
def getNextCycle(self):
return self.nextCycle
def getIsBunny(self):
return self.isBunny
def makeBunny(self):
if not self.isBunny:
self.nextCycle = self.UP
self.isBunny = True
兔子.py
#!/usr/bin/env python
from Spot import Spot
import os
class Bunny(object):
@classmethod
def main(cls, args):
with open(os.path.expanduser('~/Desktop/input.txt')) as f:
numSims = int(f.readline())
myMap = []
print numSims
minPerCycle= int(f.readline())
print minPerCycle
for k in xrange(numSims):
xyLine= f.readline()
row = int(xyLine.split()[0])
col = int(xyLine.split()[1])
print row,col
for i in range(0,row):
myLine = f.readline()
myMap.append([])
for j in range(0,col):
myMap[i].append(Spot(myLine[j] == 'B'))
numCycles = 1
if cls.isFilled(row,col,myMap):
numCycles = 0
while not cls.isFilled(row,col,myMap):
numCycles += 1
print numCycles
for m in range(0,row):
for n in range(0,col):
if myMap[m][n].getIsBunny():
if myMap[m][n].getNextCycle() == Spot.UP:
if m>0:
myMap[m-1][n].makeBunny()
break
elif myMap[m][n].getNextCycle() == Spot.RIGHT:
if n<col-1:
myMap[m][n+1].makeBunny()
break
elif myMap[m][n].getNextCycle() == Spot.DOWN:
if m<row-1:
myMap[m+ 1][n].makeBunny()
break
elif myMap[m][n].getNextCycle() == Spot.SLEEP:
if n>0:
myMap[m][n- 1].makeBunny()
break
myMap[m][n].setNextCycle()
time = numCycles * minPerCycle
print "It took " , time , " minutes for the bunnies to take over the world!\n"
del myMap[:]
f.close()
@classmethod
def isFilled(cls,row,col,myMap):
for a in range(0,row):
for b in range(0,col):
if not myMap[a][b].getIsBunny():
return False
return True
if __name__ == '__main__':
import sys
Bunny.main(sys.argv)