我是python的新手,但我来自一个基本的java背景。面对学习曲线,所以我遇到了麻烦。特别是这个循环...
from random import randint;
class simpleAI:
inputMatter = 0;
inputEnergyString = 0;
inputEnergy = 0;
resultMatter = 0;
resultEnergy = 0;
inputMatterMemory = [];
inputEnergyMemory = [];
resultMatterMemory = [];
resultEnergyMemory = [];
searchIndex = 0;
found = 0;
lookin = 0;
lookingEnergy = 0;
def cycle(self):
self.inputMatter = input("Matter: ");
self.inputMatter = int(self.inputMatter, 10);
self.inputMatterMemory.append(self.inputMatter);
self.inputEnergyString = input("Energy: ");
self.inputEnergy = int(self.inputEnergyString, 10);
self.inputEnergyMemory.append(self.inputEnergy);
#Check for an event that resulted in positive energy
while(self.searchIndex < self.resultEnergyMemory.__len__()):
print("we are foring!");
if(self.inputEnergyMemory.__getitem__((self.inputMatterMemory.index(self.inputMatter))) == self.inputEnergy):
print("we are iffy!");
self.resultMatter = self.resultMatterMemory.__getitem__(self.inputMatterMemory.index(self.inputMatter));
self.resultEnergy = self.resultEnergyMemory.__getitem__(self.inputEnergyMemory.index(self.inputEnergy));
self.found = 1;
break;
else:
self.searchIndex = self.searchIndex + 1;
if(self.found == 0):
self.resultMatter = randint(0, 256);
self.resultMatterMemory.append(self.resultMatter);
self.resultEnergy = randint(0, 256);
self.resultEnergyMemory.append(self.resultEnergy);
print("Creating new pair...");
print("Result matter: ", self.resultMatter);
print("Result Energy: ", self.resultEnergy);
elif(self.found == 1):
print("Found positive pair from memory");
print("Result matter: ", self.resultMatter);
print("Result memory: ", self.resultEnergy);
self.inputMatter = 0;
self.inputEnergyString = 0;
self.inputEnergy = 0;
self.resultMatter = 0;
self.searchIndex = 0;
self.found = 0;
它在第一次迭代时产生正确的结果,但是在其他迭代中回退到“创建”一对新的对,即使它在之前输入时应该返回一对。我究竟做错了什么?
答案 0 :(得分:1)
你为自己做了很多额外的工作。您可以简单地创建一个单独的类来将所有数据保存在一起,而不是尝试维护多个并行数组,只需要通过该类的单个数组进行循环。
from random import randint;
class MatterEnergyData:
def __init__(self, inputMatter, inputEnergy, resultMatter, resultEnergy):
self.inputMatter = inputMatter
self.inputEnergy = inputEnergy
self.resultMatter = resultMatter
self.resultEnergy = resultEnergy
def __str__(self):
return "Result matter: %s\r\nResult energy: %s" % \
self.resultMatter, self.resultEnergy
class simpleAI:
matterEnergyDataPoints = []
def cycle(self):
inputMatter = int(input("Matter: "))
inputEnergy = int(input("Energy: "))
resultObj = None
for obj in self.matterEnergyDataPoints:
if obj.inputEnergy == inputEnergy and obj.inputMatter == inputMatter:
print("Found positive pair from memory")
resultObj = obj
break
if resultObj == None:
print("Creating new pair...")
resultObj = MatterEnergyData(inputMatter, inputEnergy, randint(0, 256), randint(0, 256))
self.matterEnergyDataPoints.append(resultObj)
print resultObj