USACO Code Submission Problem - Output File Missing - python

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

Related

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)

how to create a list and then print it in ascending order

def list():
list_name = []
list_name_second = []
with open('CoinCount.txt', 'r', encoding='utf-8') as csvfile:
num_lines = 0
for line in csvfile:
num_lines = num_lines + 1
i = 0
while i < num_lines:
for x in volunteers[i].name:
if x not in list_name: # l
f = 0
while f < num_lines:
addition = []
if volunteers[f].true_count == "Y":
addition.append(1)
else:
addition.append(0)
f = f + 1
if f == num_lines:
decimal = sum(addition) / len(addition)
d = decimal * 100
percentage = float("{0:.2f}".format(d))
list_name_second.append({'Name': x , 'percentage': str(percentage)})
list_name.append(x)
i = i + 1
if i == num_lines:
def sort_percentages(list_name_second):
return list_name_second.get('percentage')
print(list_name_second, end='\n\n')
above is a segment of my code, it essentially means:
If the string in nth line of names hasn't been listed already, find the percentage of accurate coins counted and then add that all to a list, then print that list.
the issue is that when I output this, the program is stuck on a while loop continuously on addition.append(1), I'm not sure why so please can you (using the code displayed) let me know how to update the code to make it run as intended, also if it helps, the first two lines of code within the txt file read:
Abena,5p,325.00,Y
Malcolm,1p,3356.00,N
this doesn't matter much but just incase you need it, I suspect that the reason it is stuck looping addition.append(1) is because the first line has a "Y" as its true_count

I dont know what is wrong with my code (just started 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)

HackerRank Dynamic Array Problem - Runtime Error in the code

I am trying to solve this Dynamic Array problem on HackerRank. This is my code:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'dynamicArray' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER n
# 2. 2D_INTEGER_ARRAY queries
#
def dynamicArray(n, queries):
lastAnswer = 0
a = []
array_result = []
for k in range(n):
a.append([])
for i in queries:
x = i[1]
y = i[2]
if i[0] == 1:
seq = ((x ^ lastAnswer) % n)
a[seq].append(y)
elif i[0] == 2:
seq = ((x ^ lastAnswer) % n)
lastAnswer = a[seq][y]
array_result.append(lastAnswer)
return array_result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
q = int(first_multiple_input[1])
queries = [] # 1 0 5, 1 1 7, 1 0 3, ...
for _ in range(q):
queries.append(list(map(int, input().rstrip().split())))
result = dynamicArray(n, queries)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
I am getting a runtime error:
Traceback (most recent call last):
File "Solution.py", line 50, in
fptr.write('\n'.join(map(str, result)))
TypeError: 'NoneType' object is not iterable
Can anyone help me with this, I can't seem to find a solution.
This is the input:
2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1
Thanks.
Update: It seems like this input is working now, thanks to #cireo but the code is not working for other test cases. What the problem with this code?
you can try this, it works totally fine.(no runtime error)
Replace your dynamicArray function with this code. Hopefully this will be helpful for you (^_^).
def dynamicArray(n, queries):
col = [[] for i in range(n)]
res = []
lastanswer = 0
for q in queries:
data = (q[1]^lastanswer)%n
if q[0] == 1:
col[data].append(q[2])
elif q[0] == 2:
ind_x = q[2]%len(col[data])
lastanswer = col[data][ind_x]
res.append(lastanswer)
return res
The answer to your question lies in the boilerplate provided by hackerrank.
# The function is expected to return an INTEGER_ARRAY.
You can also see that result = dynamicArray(n, queries) is expected to return a list of integers from map(str, result), which throws the exception.
In your code you do print(lastAnswer), but you probably want
+ ret = []
...
- print(lastAnswer)
+ ret.append(lastAnswer)
+ return ret
instead.
Since you do not return anything, the function returns None by default, which cannot be iterated over by map.
def dynamicArray(n, queries):
# Write your code here
arr=[[]for i in range(0,n)]
lastAnswer=0
answers=[]
for query in queries:
if query[0]==1:
idx= (query[1]^lastAnswer)%n
arr[idx].append(query[2])
if query[0]==2:
idx= (query[1]^lastAnswer)%n
lastAnswer= arr[idx][query[2]% len(arr[idx])]
answers.append(lastAnswer)
return answers

Why does the following python code throw a Memory error?

Here is the code:
import itertools
num_cases = int(input())
answer_list = []
while num_cases>0:
live_ans = []
question_list = []
nums = int(input())
d1 = int(input())
d2 = int(input())
sample_space= {d1, d2}
temp = []
no_cases = 2**(nums-1)
combs = itertools.product(sample_space, repeat = nums-1)
for i in combs:
temp.append(i)
for i in temp:
if sum(i) not in live_ans:
live_ans.append(sum(i))
else:
pass
live_ans.sort()
answer_list.append(live_ans)
num_cases -= 1
for i in answer_list:
finalans = " ".join(map(str, i))
print(finalans)
For small inputs like:
1
3
1
2
The program works just fine. Where as for a relatively larger input like:
1
58
69
24
It gives a memory error. I dont cite any reason for this as the code doesn't look memory consuming at all. Isn't it?
Look at your following lines:
no_cases = 2**(nums-1)
combs = itertools.product(sample_space, repeat = nums-1)
for i in combs:
temp.append(i)
2**58 = 2.8823038e+17
You do the math on why it gets a memory error from here

Categories

Resources