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
Related
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())
...........
I am working on a question about partitioning of integers.
So far, I have been able to collect all the possible combinations, however my sets are not in a "readable" format. I have been struggling to fix this, any help is appreciated!!
My code (in Python):
input = 4
maxLen = 2
def numToArray(input):
arr = []
for num in range(1, input+1):
arr.append(num)
return arr
print(numToArray(input))
def partitions(num):
if num == 1:
return [1]
possiblePerms = []
for i in range(1, num):
possiblePerms.append([i] + partitions(num-i))
possiblePerms.append([num])
# print("num:", num, "possiblePerms:", possiblePerms)
return possiblePerms
output = partitions(input)
for item in output:
print(item)
Traceback (most recent call last): IndexError: list index out of range
from sys import argv, exit
import csv
import sys
def main ():
if len(sys.argv) < 3:
print("Usage: python dna.py data.csv sequence.txt")
exit(1)
# open csv_file contain the database
with open(sys.argv[1]) as csvfile:
r = csv.reader(csvfile)
# open txt_file contain the DNA sequence
with open(sys.argv[2]) as txtfile:
x = txtfile.read()
y = [v for v in [max_substring(x, seq) for seq in next(r)[1:]] if v >= 0]
print_match(r, y)
# count the maximum substring
def max_substring(x, sub_str):
if not x and not sub_str:
return -1
sub_repeat = len(x)*[0]
for s in range(len(x) - len(sub_str), -1, -1):
a = s + len(sub_str)
if x[s: a] == sub_str:
b = len(x) - 1
c = 1 + sub_repeat[a - 1]
sub_repeat[s] = 1 if a > b else c
return max(sub_repeat)
# Make some assertions
assert max_substring('abcabbcab', 'ab') == 1
assert max_substring('', '') == -1
assert max_substring('abcabbcab', 'abcabbcab') == 1
# print the result
def print_match(r,y):
for line in r:
if [int(val) for val in line[1:]] == y:
print(line[0])
return
print("No match")
# run the functions & class
if __name__ == "__main__" :
main()
Traceback (most recent call last): IndexError: list index out of range
[new output error
[1]: https://i.stack.imgur.com/lKKD8.png
You error can happen in two cases.
Empty Inputs
Just try calling: max_substring('', '') to reproduce the error (i.e. both parameters to the function are the empty string).
In that case:
len(x) and len(sub_str) are both 0; therefore, len(x) - len(sub_str) is 0, and sub_repeat ends up being another empty string.
list(range(0, -1, -1)) is just [0]
Therefore, in the expression a = s + len(sub_str), s is 0, and so is a.
x[s: a], being x[0:0] is the empty string. Therefore [s: a] == sub_str is True, and the if statement is entered.
In the expression c = 1 + sub_repeat[a], since a is 0, it is trying to access the first index of sub_repeat. But because sub_repeat is an empty string, this results in the IndexError.
Non-Empty Input
Repeat this for non-empty parameter values, and you will see that when the substring occurs at the very end, sub_repeat[a] doesn't exist because the length of sub_repeat is only a-1. I don't know if you want to change it to c = 1 + sub_repeat[a - 1] or sub_repeat = (1 + len(x))*[0], but both of those would get rid of the error.
Possible Solution
To avoid the error, you can add a check to prevent this case of both a and sub_str both being empty, and conditionally return the expected value for that edge case, and also avoid the second edge case above (by changing to c = 1 + sub_repeat[a - 1] or sub_repeat = (1 + len(x))*[0]). I'm not sure which one is appropriate, without knowing the purpose of this function.
if not x and not sub_str:
return -1
sub_repeat = len(x)*[0]
for s in range(len(x) - len(sub_str), -1, -1):
a = s + len(sub_str)
if x[s: a] == sub_str:
b = len(x) - 1
c = 1 + sub_repeat[a - 1]
sub_repeat[s] = 1 if a > b else c
return max(sub_repeat)
# Make some assertions
assert max_substring('abcabbcab', 'ab') == 1
assert max_substring('', '') == -1
assert max_substring('abcabbcab', 'abcabbcab') == 1
The calling code will need to handle this new return value and ignore those cases where both inputs where empty:
y = [v for v in [max_substring(x, seq) for seq in next(r)[1:]] if v >= 0]
Note that by the time print_match(r, y) is called, that r will have no more items left to iterate over, due to the list comprehension, so you may have another problem.
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
I tried running the following code. I tried returning value of j also but it just doesn't work.
def reverse(n):
j=0
while(n!=0):
j=j*10
j=j + (n%10)
n=n/10
print(j)
reverse(45)
Here is a program to reverse a number
def reverse(n):
v = []
for item in reversed(list(str(n))):
v.append(item)
return ''.join(v)
print(reverse("45"))
returns
54
The reverse() function creates an array, adds each digit from the input to said array, and then prints it as plain text. If you want the data from that as an integer then you can replace the return command to this at the end of the function
return int(''.join(v))
Actually, you made one mistake only: for Python 3 you need to use an integer division: n = n // 10.
Here is the correct code without str and list:
def reverse(n):
j = 0
while n != 0:
j = j * 10
j = j + (n%10)
n = n // 10
print(j)
reverse(12345)
Here is the correct code for Python 3:
import sys
def reverse(x):
while x>0:
sys.stdout.write(str(x%10))
x = x//10 # x = x/10 (Python 2)
print() # print (Python 2)
number = 45
int(str(number)[::-1])
a = 1234
a = int("".join(reversed(str(a))))
print a
This will give a = 4321
reversed functions returns an iterable object. If we do :
a = list(reversed(str(a)))
it will return [“3”,”2″,”1″]. We have then joined it and converted into int.