My code is giving me the error of:
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
IndexError: list assignment index out of range.
I have searched for this error and i still can't find what is the problem.
Edit: Full Traceback
Traceback (most recent call last):
File "", line 420, in run_nodebug
File "C:\Documents and Settings\jhsilva\Desktop\Monte carlo\Teste.py", line 71, in
generateRandomNumbers(list_subs)
File "C:\Documents and Settings\jhsilva\Desktop\Monte carlo\Teste.py", line 41, in generateRandomNumbers
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
IndexError: list assignment index out of range
The Code
def generateRandomNumbers(list_subs):
for n in range(len(list_subs)):
string = list_subs[n][3]
string = string.lower()
if(string == "normal"):
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
print("Numero gerado:",list_subs[n][4])
variables = [v for v in variables if v not in special]
list_subs=[[0 for col in range(6)] for row in range(len(variables)-1)]
#This prints fine
print(len(list_subs))
#this prints fine too
print(list_subs[0][4])
for n in range(len(variables)):
if n>0:
(media,desviopadrao,distribuicao) = eval(input("For variable "+variables[n]+" input: median, std, distr \n"))
list_subs[n-1] = [variables[n], media, desviopadrao, distribuicao]
N = eval(input("Qual o numero de iteracoes que deseja:"))
Var = []
for n in range(N):
generateRandomNumbers(list_subs)
Var.append(calcEq(formula))
list_subs[n-1] = [variables[n], media, desviopadrao, distribuicao]
You are setting list_subs to be a list of lists of length 4. This means that the valid indeces are 0, 1, 2, 3. In generateRandomNumbers you access index 4, which is invalid.
Security note: Don't use eval(input(...)). If you want to parse numbers/tuples etc simply use ast.literal_eval, which is a safe alternative.
Related
I'm trying to call a function that creates matrices from user input, but it says that i haven't defined something.
lstA = []
lstB = []
lstC = []
def get_list(data):
lst = []
for i in range(4):
aux = []
for j in range(4):
aux.append(data)
lst.append(aux)
return lst
lstA = get_list(int(input(f'A i[{i}] j[{j}]: ')))
lstB = get_list(int(input(f'B i[{i}] j[{j}]: ')))
lstC = get_list(lstA[i][j] + lstB[i][j])
The program should take two 4x4 matrixes from user, by putting each informed number inside the lstA[i][j] and lstB[i][j].
Finally, lstC is used to sum A and B.
Error message:
Traceback (most recent call last):
File "<string>", line 13, in <module>
NameError: name 'i' is not defined
[Program finished]
How can I solve this?
To read the data into the matrices, make a function like this:
def get_lst():
mat = [[]] * 4
for i in range(4):
mat[i] = [0] * 4
for j in range(4):
mat[i][j] = int(input(f'mat[{i}][{j}]: '))
return mat
This function will ask the user for input for each element of the matrix and populate that position with what the user entered.
Now this is how you use it:
lstA = get_lst()
lstB = get_list()
As for summing the elements of the matrices, refer to this answer
I am aware of what it means to be out of range when indexing, but I am struggling to see why my code is generating this error...
import random
howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0, howMany):
newList[i] = oldList[random.randint(0, len(oldList)-1)] # subtract one
You are getting the error because newList is empty (its length is 0). You are trying to access elements in it using an index, but there are no indices. Here's a simpler example of what's happening:
>>> newList = []
>>> i = 0
>>> newList[i] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
What you want to do is use append():
import random
howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0,howMany):
newList.append(oldList[random.randint(0, len(oldList)-1)]) # subtract one
My goal is to try to return all the value in the list which has even position as well. The following is my python code. I don't know which part should I update. Please help!! Thanks
def evenValue(numbers):
results = []
for x in numbers:
if results.index(x) %2 ==0:
results.append(x)
return results
My error message is
> Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
evenValue([1,2,3,4,5,6])
File "<pyshell#6>", line 4, in evenValue
if results.index(x) %2 ==0:
ValueError: 1 is not in list
Try this. The slice takes even numbered elements.
def evenValue(numbers):
return numbers[0::2]
or shorter:
evenValue=lambda numbers: numbers[0::2]
def evenValue(numbers):
results = []
for x in numbers:
if numbers.index(x) %2 ==0: #Use 'numbers' list instead of 'results' list
results.append(x)
return results
print(evenValue([1,2,3,4,5,6,7]))
Output:
[1, 3, 5, 7]
Using list comprehension:
lst = list(range(50))
even_indexes = lambda numbers: [lst[i] for i in range(len(lst)) if i%2==0]
even_indexes(lst)
Trying to loop around a list from with info from a OptionMenu infoWhen i try to loop i get a error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\Users\Dominic\Desktop\Homework creator\The accuall program.py", line 79, in create_button
selecting_qs()
File "C:\Users\Dominic\Desktop\Homework creator\The accuall program.py", line 88, in selecting_qs
if dif == main_list[n][1]:
TypeError: list indices must be integers, not list
My list is made up with numbers and letters so im not sure if my option menu has to be a intiger or a string to be able to search for a specific part in my list.
this is the code:
def selecting_qs():
main_list = main_file_info()
dif = difficulty.get()
for n in main_list:
if dif == main_list[n][1]:
print(main_list[n][1])
#delating empty strings and /n from list
def rm(list_):
return [x for x in list_ if x != '\n' and x != ' ']
#main list order:
#Question ID , Difficulty , Topic , Answer ID , Picture ID , Frequency
def main_file_info():
main_list=[]
main_file = open("main_file.txt","r")
main_file_info=main_file.readlines()
for line in main_file_info:
main_list.append(rm(line.split("#")))
main_file.close()
return(main_list)
You are getting the item list with for n in main_list and use the result as an index in the same list. If the items in your list are a String or a list, you get an error. Try to use the following code:
def selecting_qs():
main_list = main_file_info()
dif = difficulty.get()
resp = []
for n in main_list:
if dif == n[1]:
resp.append(n[1])
return resp
I am not sure why I am getting this list index out of bounds error
Basically what is supposed to happen is I am sending my def a list of twitter userIds and then breaking them into chunks of 100 looking them up in twitter, then adding them to a dictionary using the userIds as the key. So lets say 00001 is johnny we look up 00001 get johnny and then make a dictionary with 00001, johnny. However the if statements don't seem to trigger.
Here is the code:
def getUserName(lookupIds):
l = len(lookupIds) # length of list to process
i = 0 #setting up increment for while loop
screenNames = {}#output dictionary
count = 0 #count of total numbers processed
print lookupIds
while i < l:
toGet = []
if l - count > 100:#blocks off in chunks of 100
for m in range (0,100):
toGet[m] = lookupIds[count]
count = count + 1
print toGet
else:#handles the remainder
r = l - count
print screenNames
for k in range (0,r):#takes the remainder of the numbers
toGet[k] = lookupIds[count]
count = count + 1
i = l # kills loop
screenNames.update(zip(toGet, api.lookup_users(user_ids=toGet)))
#creates a dictionary screenNames{user_Ids, screen_Names}
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their userID number as the
#index value Count is for monitoring how far the loop has been progressing.
print len(screenNames) + 'screen names correlated'
return screenNames
The error is as follows:
Traceback (most recent call last):
File "twitterBot2.py", line 78, in <module>
toPrint = getUserName(followingids)#Testing Only
File "twitterBot2.py", line 42, in getUserName
toGet[k] = lookupIds[count]
IndexError: list assignment index out of range
toGet is initialized to the empty list, and you're attempting to assign [0] a value. This is illegal. Use append instead:
toGet.append(lookupIds[count])
This is likely because you're attempting to lookup index zero when it doesn't exist. Example:
>>> x=[]
>>> x[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
def getUserName(lookUpIds):
blockSize = 100
screenNames = {}
indexes = xrange(0, len(lookUpIds), blockSize)
blocks = [lookUpIds[i:(i + blockSize)] for i in indexes]
for block in blocks:
users = api.lookup_users(user_ids=block)
screenNames.update(zip(block, users))
return screenNames