I dont know what is wrong with my code (just started python) - python

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)

Related

USACO Code Submission Problem - Output File Missing

I've started practicing for the USACO contest tomorrow, I'm relativly new so I'm not too familiar with their input/output methods. Here's the code I submitted to the website
n = int(input())
a = input()
b = input()
swap_number = 0
a_list = []
b_list = []
for i in range(n):
if a[i] != b[i]:
a_list.append(a[i])
b_list.append(b[i])
one_value = 0
two_value = 0
for x in range(len(a_list)):
if a_list[x] == "H":
one_value += 1
else:
two_value += 1
list = [one_value,two_value]
list.sort()
swap_number = list[0] + (list[1]-list[0])
print(swap_number)
after loading for a couple minutes, it displayed:
Your output file breedflip.out:
[File missing!]
I rewrote, retested every problem using this simple code, but still receive the same error
Would this code not create an output file and how can I put the outputted answer in the file
Try to add these two lines in your beginning of codes: (just test and it passed with my revised code) Your code might not be working!
import sys
sys.stdin = open('breedflip.in', 'r')
sys.stdout = open('breedflip.out', 'w')
n = int(input())
a = list(input()) # list
b = list(input())
...........

Problem with reading data from file in Python

EDIT:
Thanks for fixing it! Unfortunatelly, it messed up the logic. I'll explain what this program does. It's a solution to a task about playing cards trick. There are N cards on the table. First and Second are numbers on the front and back of the cards. The trick can only be done, if the visible numbers are in non-decreasing order. Someone from audience can come and swap places of cards. M represents how many cards will be swapped places. A and B represent which cards will be swapped. Magician can flip any number of cards to see the other side. The program must tell, if the magician can do the trick.
from collections import namedtuple
Pair = namedtuple("Pair", ["first", "second"])
pairs = []
with open('data.txt', 'r') as data, open('results.txt', 'w') as results:
n = data.readline()
n = int(n)
for _ in range(n):
first, second = (int(x) for x in data.readline().split(':'))
first, second = sorted((first, second))
pairs.append(Pair(first, second)) # add to the list by appending
m = data.readline()
m = int(m)
for _ in range(m):
a, b = (int(x) for x in data.readline().split('-'))
a -= 1
b -= 1
temp = pairs[a]
pairs[a] = pairs[b]
pairs[b] = temp
p = -1e-9
ok = True
for k in range(0, n):
if pairs[k].first >= p:
p = pairs[k].first
elif pairs[k].second >= p:
p = pairs[k].second
else:
ok = False
break
if ok:
results.write("YES\n")
else:
results.write("NO\n")
data:
4
2:5
3:4
6:3
2:7
2
3-4
1-3
results:
YES
YES
YES
YES
YES
YES
YES
What should be in results:
NO
YES
The code is full of bugs: you should write and test it incrementally instead of all at once. It seems that you started using readlines (which is a good way of managing this kind of work) but you kept the rest of the code in a reading one by one style. If you used readlines, the line for i, line in enumerate(data): should be changed to for i, line in enumerate(lines):.
Anyway, here is a corrected version with some explanation. I hope I did not mess with the logic.
from collections import namedtuple
Pair = namedtuple("Pair", ["first", "second"])
# The following line created a huge list of "Pairs" types, not instances
# pairs = [Pair] * (2*200*1000+1)
pairs = []
with open('data.txt', 'r') as data, open('results.txt', 'w') as results:
n = data.readline()
n = int(n)
# removing the reading of all data...
# lines = data.readlines()
# m = lines[n]
# removed bad for: for i, line in enumerate(data):
for _ in range(n): # you don't need the index
first, second = (int(x) for x in data.readline().split(':'))
# removed unnecessary recasting to int
# first = int(first)
# second = int(second)
# changed the swapping to a more elegant way
first, second = sorted((first, second))
pairs.append(Pair(first, second)) # we add to the list by appending
# removed unnecessary for: once you read all the first and seconds,
# you reached M
m = data.readline()
m = int(m)
# you don't need the index... indeed you don't need to count (you can read
# to the end of file, unless it is malformed)
for _ in range(m):
a, b = (int(x) for x in data.readline().split('-'))
# removed unnecessary recasting to int
# a = int(a)
# b = int(b)
a -= 1
b -= 1
temp = pairs[a]
pairs[a] = pairs[b]
pairs[b] = temp
p = -1e-9
ok = True
for k in range(0, n):
if pairs[k].first >= p:
p = pairs[k].first
elif pairs[k].second >= p:
p = pairs[k].second
else:
ok = False
break
if ok:
results.write("YES\n")
else:
results.write("NO\n")
Response previous to edition
range(1, 1) is empty, so this part of the code:
for i in range (1, 1):
n = data.readline()
n = int(n)
does not define n, at when execution gets to line 12 you get an error.
You can remove the for statement, changing those three lines to:
n = data.readline()
n = int(n)

python IndexError: list index out of range, matrix calc

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()

List : index out of range

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)

List being cleared when used Python

I have been using Python 2.7 for a couple of weeks and need some help on the loop below:
nos_rounds = raw_input("Number of rounds?")
student = stu_input(ui)# links to a function to input a list of strings
for x in range(0,int(nos_rounds)):
student2 = randomList(student)#randomising list function
student2 = partition(student,gs)#partitions the randomised list
fcprint(student2)#prints the student list to the console and a file
The problem I am having is the second time the loop runs the list 'student' is cleared out and made in to an empty list. 'student' is not altered at all by the code. What is going on here? I am new to coding and can't seem to work this out. Any help would be much appreciated!
functions requested are:
def randomList(a): # this creates a random list of students on the course
import random
b = []
for i in range(len(a)):
element = random.choice(a)
a.remove(element)
b.append(element)
return b
def partition(lst, n): # this creates sub list of the student list containing the groups of students
increment = len(lst) / float(n)
last = 0
i = 1
results = []
while last < len(lst):
idx = int(round(increment * i))
results.append(lst[last:idx])
last = idx
i += 1
return results
def fcprint(student):#print to the console and then to an external file
floc = raw_input("Input the name of the file")
f = open(floc +".doc", "w")
for item in range (0,len(student)):
print ""
print "Group",item+1, ":\n", "\n".join(student[item])
print >>f, "\n"
print >>f,"Group: ", item+1
print >>f, "\n".join(student[item])
f.close()
Thanks, I tried the below:
for x in range(0,int(nos_rounds)):
newstu = student[:]
print "top", newstu
student2 = randomList(newstu)# randomises the student list student is reconised on the first run but is empty on second run
print "bottom", newstu
student2 = partition(student2,gs)# creates the groups
fcprint(student)#prints the student list to the console and a file
Still can't get it to work. Output is for print statements:
top ['1', '2', '3', '4', '5']
bottom []
Got this to work with the excellent advice of the forum . Working version is:
def randomList(z): # this creates a random list of students on the course
import random
r = z[:]
b = []
for i in range(len(r)):
element = random.choice(r)
r.remove(element)
b.append(element)
return b
for x in range(0,int(nos_rounds)):
student2 = randomList(student)# randomises the student list student is reconised on the first run but is empty on second run
student2 = partition(student2,gs)# creates the groups
fcprint(student2)#prints the student list to the console and a file
The problem is at randomList():
def randomList(a): # this creates a random list of students on the course
import random
b = []
for i in range(len(a)):
element = random.choice(a)
a.remove(element)
b.append(element)
return b
At this line a.remove(element) you remove elements from the original list until it's gone. So on 2nd iteration it will be empty.
By #loutre: Try doing a copy of your list (e.g a_copy = a[:] and work with this copy inside the function

Categories

Resources