class Journey has a list, self.leg_miles
class ManyJourneys has a list of journeys created by
self.journeys = []
for i in range(2):
self.journeys.append(Journey())
from some input I add to the list leg_miles for each Journey kind of like this:
self.journeys[self.count].addLeg(temp)
temp is a number i read from a list. it is always changed to what was inputted right before the above line.
for some reason instead of creating a new list for journey[1] it just adds to the created list.
for example: if for journey[0] the leg_miles had [4,5,6] and I moved on to journey[1] to add 4 and 6 it would have : leg_miles = [4,5,6,4,6]
I do not understand why it is adding on. I have self in it. I do not understand how to upload code or pictures.
I hope this is enough information to solve the problem
EDIT: Here is the code I have.
class Journey:
def __init__(self,odometer=0,leg_miles=[],leg_gas=[]): #constructor
self.odometer = odometer
self.leg_miles = leg_miles
self.leg_gas = leg_gas
def addLeg(self,miles,gas):
#adds to a list of miles and gas
self.leg_miles.append(miles)
self.leg_gas.append(gas)
def getLists(self):
#returns the list of miles and the list of gas
return self.leg_miles,self.leg_gas
def calculate(self):
#calculate the miles per litre for the journey and return
miles_per_litre = 0
for i in range(len(self.leg_miles)): #calcs miles per litre for each leg and adds to total
miles_per_litre += int(self.leg_miles[i]/self.leg_gas[i])
return miles_per_litre
class ManyJourneys:
def __init__(self,name):
self.myfile = open(name,"r")
self.content = self.myfile.read().split("\n")
self.journeys = []
for i in range(self.content.count("")+1):
self.journeys.append(Journey())
self.count = 0
for i in self.content:
if i == "":
self.count+=1
else:
temp = i.split(" ")
self.journeys[self.count].addLeg(int(temp[0]),int(temp[1]))
def statistics(self):
sum = 0
for i in self.journeys:
sum += i.calculate()
return sum/len(self.journeys)
def main():
filename = input("Please enter a file name. (Eg: test.txt): ")
manyJourneys1 = ManyJourneys(filename)
print("You got {0} miles per litre.".format(manyJourneys1.statistics()))
main()
and a sample text file would be
100 54
340 109
23 4
333 33
4500 678