f = open('transaction.log','r')
ClerkHash = dict()
arr = [0,0]
for line in f:
Tdate = line[0:12]
AccountKey = line[12:50]
TransType = line[22:2]
ClerkKey = line[24:10]
CurrencyCode = line[34:2]
Amount = line[36:45]
print line
print '\n'
print AccountKey
print '\n'
print Tdate print '\n'
if TransType=="04":
ClerkHash[ClerkKey+AccountKey] = arr; // is this line corrent ? i don't want to corrupt the array every time ? how should i do it ?
ClerkHash[ClerkKey+AccountKey][0]+=1
ClerkHash[ClerkKey+AccountKey][1]+= Amount
for Key in ClerkHash.keys():
if ClerkHash[key][0] >= 3 and ClerkHash[key][1] > 1000:
print Key
i want to have an hash name ClerkHash[ClerkKey+AccountKey]
which consistes of array of 2 int : first index is withdrawl num , and second is ammount
did i defined the array and hash well ?
in addition i want to sum the ammount...how can i do it ?
Here is few issue I seen so far
Amount = line[36:45]
should be
Amount = int(line[36:45])
and
ClerkHash[ClerkKey+AccountKey] = arr[0,0]
should be
ClerkHash[ClerkKey+AccountKey] = [0,0]
Check your slice intervals! The second argument is another index, NOT the number of steps to take from the first index. I guess
TransType = line[22:2]
should rather be
TransType = line[22:24]
You overwrite values if you set
ClerkHash[ClerkKey+AccountKey] = [0, 0]
each time you encounter TransType == "04". So change
if TransType=="04":
ClerkHash[ClerkKey+AccountKey] = arr[0,0]
ClerkHash[ClerkKey+AccountKey][0]+=1
ClerkHash[ClerkKey+AccountKey][1]+= Amount
to
if TransType=="04":
if not ClerkHash.has_key(ClerkKey+AccountKey):
ClerkHash[ClerkKey+AccountKey] = [1, Amount]
else:
ClerkHash[ClerkKey+AccountKey][0] += 1
ClerkHash[ClerkKey+AccountKey][1] += Amount
Related
I want to save the result of my while loop every time it runs to an array. Then once all conversions have been run, the array that stores all the values will be summed.
raw_user_age = input("Number: ")
x = int(raw_user_age)
g=0
while g < x :
if __name__ == "__main__":
YOUR_ACCESS_KEY = ''
url = 'https://api.exchangerate-api.com/v4/latest/USD'
c = Currency_convertor(url)
from_country = input("From Country: ")
to_country = input("TO Country: ")
amount = int(input("Amount: "))
returnedamount=c.convert(from_country, to_country, amount)
g += 1
print(returnedamount)
First create your array before the beginning of the loop:
values_returned = []
You can use the append method to add an element to the array every time the loop runs:
values_returned.append(returnedamount)
After the loop is done, you can use the sum() function to get the sum of all values in the array:
sum(values_returned)
You can simply append the value to the array (list) like so:
list_ = []
value1 = 1
value2 = 2
list_.append(value1)
list_.append(value2)
I have a .txt-file called ecc.txt. It contains more than 8000 lines of numbers. I want to count the average of every 360 lines in that file.
Here is the code:
import math
f = open(r'ecc.txt').read()
data = []
for line in data:
sum = 0
for i in range (len(data)):
if i % 360 != 0:
sum = sum + ecc[i]
else:
average = sum / 360
print(average)
sum = 0
When I am running it, nothing happens. I didn't get any results. The code just running and end without any result.
Is there something wrong with this code?
Thank you.
avg_dict = {}
with open('ecc.txt') as f:
data = f.read().split(' ')
sum = 0
i = 0
for str_number in data:
sum += int(str_number)
i += 1
if i % 360 == 0:
avg_dict[i] = sum/360
sum = 0
I've assumed that your file text has an empty space as separator. Otherwise, you can change the sep value in the split method. If there is not separator change data as:
data = list(f.read())
You code would work with some changes:
import math
data=[]
with open(r'ecc.txt') as f:
for i in f:
data.append(int(i))
for line in data:
sum = 0
for i in range (len(data)):
if i%360 !=0:
sum = sum + ecc[i]
else:
average = sum/360
print(average)
sum=0
Be aware though, that this code doesn't include values for each 360th element (i guess it's not a problem for an average) and also you don't have average for last elements
This question already has answers here:
Does "IndexError: list index out of range" when trying to access the N'th item mean that my list has less than N items?
(7 answers)
Closed 5 years ago.
def calcDistance(x1, y1, x2, y2):
distance = sqrt((x1-x2)**2 + (y1-y2)**2)
return distance
def make_dict():
return defaultdict(make_dict)
# Capture 1 input from the command line.
# NOTE: sys.argv[0] is the name of the python file
# Try "print sys.argv" (without the quotes) to see the sys.argv list
# 1 input --> the sys.argv list should have 2 elements.
if (len(sys.argv) == 2):
print "\tOK. 1 command line argument was passed."
# Now, we'll store the command line inputs to variables
myFile = str(sys.argv[1])
else:
print 'ERROR: You passed', len(sys.argv)-1, 'input parameters.'
quit()
# Create an empty list:
cities = []
# Create an empty dictionary to hold our (x,y) coordinate info:
myCoordinates = {}
# Open our file:
myFile = '%s.csv' % (myFile)
with open(myFile, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in spamreader:
# Only read rows that do NOT start with the "%" character.
if (row[0][0] != '%'):
# print row
id = int(row[0])
isHome = int(row[1])
x = float(row[2])
y = float(row[3])
myCoordinates[id] = {'x': x, 'y': y}
# print myCoordinates[id]['x']
# print myCoordinates[id]['y']
if (isHome == 1):
# Store this id as the home city
homeCity = id
cities.append(id)
print homeCity
print cities
# Create a TSP tour.
# VERSION 1 -- Using range() and for() loops:
myTour = []
for i in range(homeCity, len(cities)+1):
myTour.append(i)
for i in range(1, homeCity+1):
myTour.append(i)
print myTour
# VERSION 2 -- Using only range()
'''
firstPart = range(homeCity, len(cities)+1)
secondPart = range(1, homeCity+1)
myTour = firstPart + secondPart
print myTour
'''
tau = defaultdict(make_dict)
for i in cities:
# print "distance[%d][%d] = 0" % (i, i)
tau[i][i] = 0
for j in range(i+1, len(cities)+1):
# print "distance[%d][%d] > 0" % (i, j)
tau[i][j] = calcDistance(myCoordinates[i]['x'], myCoordinates[i]['y'], myCoordinates[j]['x'], myCoordinates[j]['y'])
# print "distance[%d][%d] = distance[%d][%d]" % (j, i, i, j)
tau[j][i] = tau[i][j]
# FIXME -- Edit the code below...
# Calculate the total distance of our TSP solution:
i = myTour[i]
for myIndex in range(1, len(myTour)+1):
j = myTour[myIndex]
print j
Function to calculate cost based on distance. Need to be modified.
def cost(rate,j):
cost = rate * j
cost = cost(1000,j)
print cost
Also I need to calculate cost based on distance traveled. with myIndex i am getting an error of list index out of range. I am not knowing what exactly is going there. The j is like total distance calculated.
List in python have 0 based index. If you add n elements to a list the indexes are from 0 to n-1. But you are running the loop from 1 to n. So, it getting list index out of range error.
You should do this-
for myIndex in range(0, len(myTour)):
j = myTour[myIndex]
print(j)
If you are getting list index out of range error then change the loop where you are getting the error and accessing a list using 1-based indexing, from range(1,len(some_list)+1) to range(0,len(some_list)). Or you can simply write range(len(some_list)). When there is no start value passed in the range function it starts from 0 by default.
To calculate cost try this -
for myIndex in range(0, len(myTour)):
j = myTour[myIndex]
cost = rate * j
print(cost)
Set the value of rate before starting the loop.
I'd appreciate some help debugging this code:
testing = """There is something unique about this line
in that it can span across several lines, which is unique and
useful in python."""
listofthings = []
i = 0
while i < len(testing):
if testing[i] == " ":
listofthings.append(i + 1)
i = i + 1
listofthings.insert(0, 0)
listofthings.append(len(testing))
print listofthings
word_list = []
i = 0
while i < len(listofthings):
l = i + 1
x = listofthings[i]
y = listofthings[l]
word = testing[x:y]
word_list.append(word)
i = l
print word_list
I am not sure why I am getting the index out of range error. I understand what the error means obviously, but am not sure what I am doing wrong. Weirdly enough, this only happens when I run the above code. It doesn't give me any errors when I run this:
word = testing[x:y]
print word
I am fairly new with Python(going on three days) so I am sure it is a stupid overlooked syntactical error...
l = i + 1
x = listofshit[i]
y = listofshit[l]
word = testing[x:y]
word_list.append(word)
When i=length-1,then y=length, which is an error.Python array indexing starts from 0, hence max address is length-1
The length of list listofshit is 21 with the range of index from 0 to 20. And when it comes to the final loop, i is 20 and l is 21, so there is a out of range error. And I think the following code is what you want:
testing = """There is something unique about this line
in that it can span across several lines, which is unique and
useful in python."""
listofshit = []
i = 0
while i < len(testing):
if testing[i] == " ":
listofshit.append(i)
i = i + 1
listofshit.insert(0, 0)
listofshit.append(len(testing))
word_list = []
i = 0
while i < len(listofshit) - 1:
l = i + 1
x = listofshit[i]
y = listofshit[l]
word = testing[x:y]
word_list.append(word)
i = l
print word_list
while i < len(listofshit):
l = i + 1
x = listofshit[i]
y = listofshit[l]
When i corresponds to the last element,
y = listofshit[l]
You are trying to access the element next to the last element. Thats why it is throwing the error.
On the last iteration of the second while loop, l is set to len(listofshit). This is past the end of listofshit; the last valid index is len(listofshit) - 1.
What is wrong in the method end in the code?
The method end returns always 1 although it should return 0 with the current data.
# return 1 if the sum of four consecutive elements equal the sum over other sum of the other three sums
# else return 0
# Eg the current sums "35 34 34 34" should return 0
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = data.split("|");
def do_row ( arra, n ):
return arra[4*n:4 + 4*n]
def row_summa (row):
return sum(map(int,row))
def end ( summat ): # problem here!
equality = 1
for i in summat[2:5]:
print "Comparing: ", summat[1], " and ", i, ".\n"
if summat[1] != i:
equality = 0
print equality
for i in range(0,4):
summat = []
summat.append( row_summa( do_row(arra,i) ) )
print row_summa ( do_row(arra,i) )
summa = 0
end(summat)
I can't really tell what you're trying to do here, but I can certainly say why end() returns 1 instead of 0. In your last for loop, you reset summat to [] at the start of the loop, so at the end, summat only contains a single value (the one you most recently appended on). So when you ask for summat[2:5] on a list of a single item, Python returns an empty list (as there are no values in that range) - in which case there are no chances for equality to be set to zero because the loop in end never runs.
I think you may have an off-by-one error. Remember that array indexes in Python start at 0, not 1. So where you do this:
for i in summat[2:5]:
print "Comparing: ", summat[1], " and ", i, ".\n"
if summat[1] != i:
equality = 0
you are not looking at summat[0] at all. Try perhaps:
for i in summat[1:4]:
print "Comparing: ", summat[0], " and ", i, ".\n"
if summat[0] != i:
equality = 0
You should also study this piece of code
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = map(int,data.split("|"))
summat = [sum(arra[i:i+4]) for i in range(0,len(arra),4)]
print summat
print len(set(summat))==1
First off, end doesn't return 1. It returns None. It prints 1. Kind of deceptive if you're running it from the command line.
Second, when you call end, summat is equal to [34]. So this:
for i in summat[2:5]:
never even executes. It won't do anything unless summat contains at least 3 elements.
You have two problems. Initialising summat to [] inside the loop, also the off by one error Greg mentioned
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = data.split("|");
def do_row ( arra, n ):
return arra[4*n:4 + 4*n]
def row_summa (row):
return sum(map(int,row))
def end ( summat ): # problem here!
equality = 1
for i in summat[1:]: # 1 <=== IS THE SECOND ELEMENT
print "Comparing: ", summat[0], " and ", i, ".\n"
if summat[0] != i:
equality = 0
print equality
summat = [] # <=== DO THIS BEFORE THE LOOP
for i in range(0,4):
summat.append( row_summa( do_row(arra,i) ) )
print row_summa ( do_row(arra,i) )
summa = 0
end(summat)