here is my code :
if __name__ == '__main__':
n = int(input())
for i in range(n):
name = input()
score = float(input())
python_students = [[name, score]]
z=len(python_students)
for i in range(z):
if python_students[i][1]<python_students[i+1][1]:
list = [python_students[1]]
list.sort()
print(list)
error : Traceback (most recent call last):
File "solution.py", line 9, in <module>
if python_students[i][1]<python_students[i+1][1]:
IndexError: list index out of range
i am literally confused with this type of error , kindly explain and help me with this code.
i am trying to fetch names in alphabetical order from the list
z should be len(python_students)-1. At the last iteration, python_students[i+1][1] goes outside the bounds of the list.
Below is simplifed code, your code has lots of loopholes. you shouldn't use list to store list elements, since list is build class provided by python. its not good practice. also use append to append elements into the list.
if __name__ == '__main__':
python_students = []
n = int(input())
for i in range(n):
name = input()
score = float(input())
python_students.append([name,score])
#python_students = [[name, score]]
z=len(python_students) - 1
p_s = []
for i in range(0,z):
if python_students[i][1]<python_students[i+1][1]:
p_s.append(python_students[1])
p_s.sort()
print(p_s)
Related
I am trying to solve 1st step from Numeric Matrix Processor (hyperskill.org). I have to write program (without using numpy) which takes 2 matrix and then if number of rows and number of columns are equal I have to output sum of these 2 matrix. I know that for now number of columns is not used (only in if condition) but it doesn't matter. The problem is "IndexError: list index out of range" after I call summing function. Can someone tell me what am I doing wrong? Thx for helping!
main = []
main2 = []
final = []
mat = []
def reading():
print("rows:")
reading.rows = int(input())
print("columns:")
reading.columns = int(input())
for i in range(reading.rows):
mat = input().split()
mat = list(map(int, mat))
main.append(mat)
return main
def reading2():
print("rows:")
reading2.rows = int(input())
print("columns:")
reading2.columns = int(input())
for i in range(reading2.rows):
mat = input().split()
mat = list(map(int, mat))
main2.append(mat)
return main2
def summing():
if reading.rows == reading2.rows and reading.columns == reading2.columns:
for i in range(reading.rows):
for j in range(reading.columns):
final[i][j] = main[i][j] + main2[i][j]
print(final[j][i], end=" ")
print()
else:
print('ERROR')
reading()
reading2()
summing()
i have made a list by using while list and then used if statements. In the first two conditions, the code runs perfectly without any error. But in the third condition it is showing that the list is empty. I have no clue what is wrong here.
CODE:
# time table generator with python
import random
no_of_classes = int(input("Please enter the number of classes in a day: "))
name_of_classes = input("Please enter the subject name/name of classes (please separate then by commas): ")
class_name_list = name_of_classes.split(",")
days_in_week = int(input("Enter the number of days in a week for which the school is working:"))
list_1 = [] `list with the problem`
x = 1
while x <= no_of_classes:
list_1.append(x)
x += 1
final_list = []
for j in range(days_in_week):
subject_list = []
if no_of_classes > len(class_name_list):
for i in class_name_list:
a = random.choice(list_1)
subject_list.insert((a - 1), i)
for m in range(no_of_classes - len(class_name_list)):
b = random.choice(class_name_list)
subject_list.append(b)
final_list.append(subject_list)
elif no_of_classes == len(class_name_list):
for i in class_name_list:
a = random.choice(list_1)
subject_list.insert((a-1), i)
final_list.append(subject_list)
else: `having problem with this condition`
temp_class_list = []
list_2 = class_name_list
for m in range(no_of_classes):
n = random.choice(list_2)
a = random.choice(list_1)
list_1.remove(a)
list_2.remove(n)
subject_list.insert((a-1), n)
for k in range(days_in_week):
print(final_list[k])
OUTPUT:
Traceback (most recent call last):
File "/Users/arungupta/Documents/trial (delete).py", line 24, in <module>
a = random.choice(list_1)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py", line 301, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
THANK YOU FOR YOUR HELP. MUCH APPRECIATED!!!
You just forgot to fill the final_list : final_list.append(subject_list)
else:
temp_class_list = []
list_2 = class_name_list
for m in range(no_of_classes):
n = random.choice(list_2)
a = random.choice(list_1)
list_1.remove(a)
list_2.remove(n)
subject_list.insert((a-1), n)
final_list.append(subject_list)
There are two problems actually:
You forgot final_list.append(subject_list) as noted by Castiell
You emptied list_1, which makes your program crash in the next iteration (and actually, the error message you showed is due to this)
Here is my proposed correction: make a copy of list_1 before you empty it:
else:
temp_class_list = []
list_2_copy = class_name_list.copy()
list_1_copy = list_1.copy()
for m in range(no_of_classes):
n = random.choice(list_2_copy)
a = random.choice(list_1_copy)
list_1_copy.remove(a)
list_2_copy.remove(n)
subject_list.insert((a-1), n)
final_list.append(subject_list)
(I also made a copy of class_name_list because I suspect it is the source of another undiscovered bug)
How do I fix the error my code comes up with the following?
Traceback (most recent call last):
File "main.py", line 143, in <module>
print(question_list2[random_int])
IndexError: list index out of range
This is the code in question:
question_list2 = []
question_list2.append(" the marines are ___ based opreatives ")
question_list2.append(" for under water travel marines use _____ ")
question_list2.append(" the avergae marine trains for _ weeks ")
answer_list2 = []
answer_list2.append("sea")
answer_list2.append("subamrines")
answer_list2.append("13")
top_index = 4
correct = 0
for i in range (0,4):
random_int = random.randint(0,top_index)
print(question_list2[random_int])
top_index = top_index - 1
user_answer1 = input("fill in the blank with the correct word ")
if user_answer == answer_list1[random_int]:
correct = correct + 3
del question_list1[random_int]
del answer_list1[random_int]
From the random docs
random.randint(a, b)
Return a random integer N such that a <= N <= b
This means that:
top_index = 4
random_int = random.randint(0,top_index)
Has the possibility of setting random_int to 3 or 4 which are outside the range of your list which only has three items with index 0, 1, and 2.
Rather than mutating your lists and using indexes, it might be easier to make a list of indexes, shuffle it, then iterate over it:
indexes = random.sample(range(0, len(question_list)), k = len(question_list))
for i in indexes:
# etc...
If you kept the questions and answers together in a single list, you could do away with the indexes altogether. This would be a good use for named tuples
import random
from collections import namedtuple
qa = namedtuple('QA', ['question', 'answer'])
question_list = [
qa(" the marines are ___ based opreatives ", 'sea'),
qa(" for under water travel marines use _____ ",'submarines'),
qa(" the avergae marine trains for _ weeks ", '13')
]
random.shuffle(question_list)
correct = 0
for qa in question_list:
print(qa.question)
user_answer = input("fill in the blank with the correct word ")
if user_answer == qa.answer:
correct = correct + 1
I believe that you only have three things on your list. The range should be range(0,3) and maybe your top_index should be top_index = 2.
Since the indexes on your list are [0,1,2]
The first item in list > index = 0
The second item in list > index = 1
The third item in list > index = 2
How do I say to the code to get the value 1 of the array within a while loop?
while line < 1000000:
userpass = passfile.readline().split()
line = line + 1
up = userpass[1]
print(userpass)
up = decode(TH3, up)
#See Values
#print (line)
#print (str(userpass))
#print (str(userEntry))
#Checking If Account Is Created
Traceback (most recent call last):
File "DataBase.py", line 55, in <module>
up = userpass[v]
IndexError: list index out of range
My error was that i did'nt append so the value userpass was replaced to a len of 2 to a len of 0 :
[] just added an if len > 0 :
before
Seems like userpass's length is less than 2.
In python, lists, tuples and dictionaries are 0-indexed. Meaning if you want to access the first element, you should write it like :
up = userpass[0]
Not too sure what is causing this error
Using the Hackerrank 30 day challenge on day 5 and I can't seem to be able to change this so it'll work - I'm not too familiar with placeholders but have a basic understanding of how they work.
#!/bin/python3
import sys
n = int(input().strip())
for i in range(1, 10):
answer = n * i
print("{} x {} = {}".format((n, i, answer)))
Error:
Traceback (most recent call last):
File "solution.py", line 9, in <module>
print("{} x {} = {}".format((n, i, answer)))
IndexError: tuple index out of range
n = int(input().strip())
for i in range(1, 10):
answer = n * i
print("{} x {} = {}".format(n, i, answer)) # changed here
You had a tuple for n,i,answer that was passed into format(). You just need to pass what you want to print and format into the function format(), no need to wrap it in a tuple.