getting error as list index out of range - python

I have the following program to calculate the percentage of CO2 every year.
I get an error, "list index out of range", once the entire program runs on the following line:
m= co2level[i+1][1]
Code:
# Program to calculate percentage of CO2 every year
co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
(2006,323.91),(2008,341.47),(2009,348.22)]
i = 0
while i!=len(co2level):
m= co2level[i+1][1] # I am getting error here as list index out of range
n= co2level[i][1]
percentage=((m-n)/n)*100
print " Change in percentage of CO2 in year %r is"%co2level[i][0],percentage
i+=1

You could avoid the bounds error like this:
co2level = [(2001,320.93),(2003,322.16),(2004,328.07),
(2006,323.91),(2008,341.47),(2009,348.22)]
i = 1
while i != len(co2level):
old = co2level[i-1][1]
act = co2level[i][1]
percentage=((act-old)/old)*100
print (" Change in percentage of CO2 in year %r is " %co2level[i][0],percentage)
i+=1
You start with the 1st year you can get a "delta" for and inspect the one before this. You compare act to old so you are not going over the bound.

Python is 0 indexed; that means for a list with n elements, the first element of a list is at index 0 and the last element is at index n - 1
Consider the following snippent from your code:
while i!=len(co2level):
m= co2level[i+1][1]
The line m = co2level[i+1][1] implies that you start iterating from the element at index 1 (2003,322.16) and tries to get the item at index 6 at the end which causes the error. Morover you have an error in how you assigned m and n. To correct this you can do:
i = 0
while i!=len(co2level):
m= co2level[i][0] # I am getting error here as list index out of range
n= co2level[i][1]
percentage=((m-n)/n)*100
print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage
i+=1
The more pythonic way (using for loops) will be
for i in co2level:
m = i[0]
n = i[1]
percentage=((m-n)/n)*100
print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage
better still:
for i in co2level:
m, n = i
percentage=((m-n)/n)*100
print" Change in percentage of CO2 in year %r is"%co2level[i][0],percentage

Related

Trying to print correct element corresponding to value

def main():
rain = [] # empty list awaiting user input
MONTH = ["January", "February"] # parallel to the rain?
SIZE = 2 # array size
getRain(rain,SIZE) # ask user to input each month rainfall amount
highest = findHigh(rain, SIZE, MONTH)
displayValues(SIZE, highest, rain)
# get input and add to list
def getRain(rain, SIZE):
index = 0
while (index <= SIZE - 1):
print('Enter rainfall for month', index + 1)
rainInput = int(input('Enter rainfall: '))
rain.append(rainInput)
index = index + 1
# finding the highest value in the array and printing the highest value with month
def findHigh(rain, SIZE, MONTH):
highest = rain[0]
index = 1
while (index <= SIZE - 1):
if (rain[index] > highest):
highest = rain[index]
else:
index = index + 1
print("The highest month is:", MONTH[index - 1]) # not too sure if I need this here
return highest
# display the values
def displayValues(SIZE, highest, rain):
print("--------------------------------")
print("The highest value is:", highest)
# run code
main()
Hi, I am trying to figure out how to get it so then my output would print the right month in correlation to the amount of rainfall each month has (for example: january has 50 and february has 40)
Output: The highest month is: January
I've tried making another condition thing or another module to try to check the values, but I cannot compare strings to int in the list. I have also tried moving the print values but I feel like another module would be needed to find the right month unless I am just printing it in the wrong area
If you don't want to change the rest of the code, you can modify findHigh to track and print the month with the highest value:
def findHigh(rain, SIZE, MONTH):
highest = 0
index = 1
while (index <= SIZE - 1):
if (rain[index] > rain[highest]):
highest = index
else:
index = index + 1
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
return rain[highest]
or slightly more pythonic:
def findHigh(rain, SIZE, MONTH):
highest = 0
for index in range(SIZE):
if rain[index] > rain[highest]:
highest = index
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
return rain[highest]
It may be better to move both the prints to displayValues:
def main():
rain = [] # empty list awaiting user input
MONTH = ["January", "February"] # parallel to the rain?
SIZE = 2 # array size
getRain(rain,SIZE) # ask user to input each month rainfall amount
highest = findHigh(rain, SIZE)
displayValues(SIZE, highest, rain, MONTH)
# get input and add to list
def getRain(rain, SIZE):
index = 0
while (index <= SIZE - 1):
print('Enter rainfall for month', index + 1)
rainInput = int(input('Enter rainfall: '))
rain.append(rainInput)
index = index + 1
# finding the highest value in the array and printing the highest value with month
def findHigh(rain, SIZE):
highest = 0
for index in range(SIZE):
if rain[index] > rain[highest]:
highest = index
return highest
# display the values
def displayValues(SIZE, highest, rain, MONTH):
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
print("--------------------------------")
print("The highest value is:", rain[highest])

I want to add elements in a particular column of Excel one by one using Python

I am able to write the function but I get a memory error.
I want to get the data of i in a column name (bolded below in code)
Suppose there is a column of date time with format '%Y-%M-%D %H:%m:%s' and I have another column with price changing every second , then I need to make two new columns where 1st will carry the average of price for last 1 min, and while 2nd will carry the average of price for last ten minutes, where these two column will fill perfectly according to time, like if suppose we start at 10 :10:01 and ends at 10:11:00 then we add same average value of last one min in all rows between this one minute period , same with 2nd one where "x" is a list of 12000 elements
m = list(set(x))
f1 = [0,0,]
f10 = [0,0,]
index = []
index10 = []
for i in m:
index.append(x.index(i))
for i in index[0:len(index):9]:
index10.append(i)
For differnce if equal to 1 in x
total = 0
for i in index[2:len(index)-1]:
j = i+1
list = df['Price'][i:j]
for i in list:
total = (total+i)/j
f1.append(total)
total = 0
for i in f1[0:len(m)]:
j = i+1
for l in range(0,j):
**df['Average last 1 min'][l] = i**
for differnce if equal to 10 in x
total1 = 0
for i in index10[2:len(index10)-1]:
j = i+1
list = df['Price'][i:j]
for i in list:
total1 = (total1+i)/j
f1.append(total1)
total1 = 0
for i in f10[0:len(m)]:
j = i+1
for l in range(0,j):
**df['Average last 10 min'][l] = i**
df.to_excel('A:\\Test\\time.xlsx')

subtract n values from input python

I haven't found anything even relevant to my question, so i may be asking it wrong.
I am working on an exercise where I am given sequential values starting at 1 and going to n, but not in order. I must find a missing value from the list.
My method is to add the full 1 => n value in a for loop but I can't figure out how to add n - 1 non-sequential values each as its own line of input in order to subtract it from the full value to get the missing one.
I have been searching modifications to for loops or just how to add n inputs of non-sequential numbers. If I am simply asking the wrong question, I am happy to do my own research if someone could point me in the right direction.
total = 0
for i in range (1 , (int(input())) + 1):
total += i
print(total)
for s in **?????(int(input()))**:
total -= s
print(total)
sample input:
5
3
2
5
1
expected output: 4
To fill in the approach you're using in your example code:
total = 0
n = int(input("How long is the sequence? "))
for i in range(1, n+1):
total += i
for i in range(1, n):
total -= int(input("Enter value {}: ".format(i)))
print("Missing value is: " + str(total))
That first for loop is unnecessary though. First of all, your loop is equivalent to the sum function:
total = sum(range(1,n+1))
But you can do away with any iteration altogether by using the formula:
total = int(n*(n+1)/2) # division causes float output so you have to convert back to an int
I don't know if you are supposed to create the initial data (with the missing item), so I added some lines to generate this sequence:
import random
n = 12 # or n = int(input('Enter n: ')) to get user input
# create a shuffled numeric sequence with one missing value
data = list(range(1,n+1))
data.remove(random.randrange(1,n+1))
random.shuffle(data)
print(data)
# create the corresponding reference sequence (without missing value)
data2 = list(range(1,n+1))
# find missing data with your algorithm
print("Missing value =", sum(data2)-sum(data))
Here is the output:
[12, 4, 11, 5, 2, 7, 1, 6, 8, 9, 10]
Missing value = 3

Python tablecheck error

def tableCheck(elev, n, m):
tablePosCount = 0
rowPosCount = 0
for r in range(1, n):
for c in range(1, m):
if elev[r][c] > 0:
tablePosCount = tablePosCount + 1
rowPosCount = rowPosCount + 1
print 'Number of positive entries in row ', r , ' : ', rowPosCount
print 'Number of positive entries in table :', tablePosCount
return tablePosCount
elev = [[1,0,-1,-3,2], [0,0,1,-4,-1], [-2,2,8,1,1]]
tableCheck(elev, 3, 5)
I'm having some difficulty getting this code to run properly. If anyone can tell me why it might being giving me this output
Number of positive entries in row 1 : 1
Number of positive entries in row 2 : 2
Number of positive entries in row 2 : 3
Number of positive entries in row 2 : 4
Number of positive entries in row 2 : 5
Number of positive entries in table : 5
There are three things in your code that I suspect are errors, though since you don't describe the behavior you expect, it's possible that one or more of these is working as intended.
The first issue is that you print out the "row" number every time that you see a new value that is greater than 0. You probably want to unindent the print 'Number of positive entries in row ' line by two levels (to be even with the inner for loop).
The second issue is that you don't reset the count for each row, so the print statement I suggested you move will not give the right output after the first row. You probably want to move the rowPosCount = 0 line inside the outer loop.
The final issue is that you're skipping the first row and the first value of each later row. This is because your ranges go from 1 to n or m. Python indexing starts at 0, and ranges exclude their upper bound. You probably want for r in range(n) and for c in range(m), though iterating on the table values themselves (or an enumeration of them) would be more Pythonic.

Python, append within a loop

So I need to save the results of a loop and I'm having some difficulty. I want to record my results to a new list, but I get "string index out of range" and other errors. The end goal is to record the products of digits 1-5, 2-6, 3-7 etc, eventually keeping the highest product.
def product_of_digits(number):
d= str(number)
for integer in d:
s = 0
k = []
while s < (len(d)):
j = (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4]))
s += 1
k.append(j)
print(k)
product_of_digits(n)
Similar question some time ago. Hi Chauxvive
This is because you are checking until the last index of d as s and then doing d[s+4] and so on... Instead, you should change your while loop to:
while s < (len(d)-4):

Categories

Resources