Reputation: 373
after learning a lot about python I moved to solve some programming problem. I am ok with writing normal scripts but when it comes to programing problems I ruined. After trying some problem and getting runtime-error I thought there would be a problem with code but soon I started Google and found there is problem with input that how it is taken. I searched and view some question on stackoverflow but that doesn't help.
Now taking about a particular problem I am trying to solve the below problem.
You are given an array A of size N, and Q queries to deal with. For each query, you are given an integer X, and you're supposed to find out if X is present in the array A or not.
Input: The first line contains two integers, N and Q, denoting the size of array A and number of queries. The second line contains N space separated integers, denoting the array of elements Ai. The next Q lines contain a single integer X per line.
Output: For each query, print YES if the X is in the array, otherwise print NO.
Sample input
5 6
50 40 30 20 10
10
20
30
40
50
100Sample Output YES
YES
YES
YES
YES
NO
(this is neither my homework nor I am getting reward)
this is the solution i tried.
import sys
p=[]
A=[]
file_name=sys.argv[1]
f= open(file_name)
user_args= f.read()
user_input=user_args.split()
N,n=int(user_input[0]), int(user_input[1])
for i in range(2,N+2):
A.append(int(user_input[i]))
for i in range(N+2,n+N+2):
p.append(int(user_input[i]))
for i in range(0,int(n)):
linearsearch(A, p[i])
sys.exit()
#and then writing the linearsearch(A,p) for checkign the element.
that I tried and got compilation-log ok with runtime-error. Everything is ok if i run this code on my machine but when i submit it then this runtime error.
I also searched for this error but no idea why am I getting this?
Here some user are suggesting the solution. what I want is feedback on code I have already written and as I tried in this to read the input from a file via command line.Where am I mistaking? Am I lacking some basics?
Upvotes: 0
Views: 706
Reputation: 79
You should use raw_input for reading data. For example my solution is:
N,Q = map(int, raw_input().split(' '))
arr = map(int, raw_input().split(' '))
arr = set(arr)
for i in xrange(Q):
N = int(raw_input())
if N in arr:
print("YES")
else:
print("NO")
Upvotes: 0
Reputation: 77281
Your problem is that you are supposed to read from stdin, not from a file - this will not work:
file_name=sys.argv[1]
f= open(file_name)
The skeleton of the solution should be something like this:
n, q = raw_input().split()
a = raw_input().split()
for query in sys.stdin:
query.strip()
if test_if_query_in(a):
print "YES"
else:
print "NO"
Have fun writing test_if_query_in
. The solution is very easy in Python because there is a builtin collection type with O(1) search.
Upvotes: 1