问题
I have been programming for a total of three weeks. I am stuck on this problem right now:
We will pass you 2 inputs:
A list of numbers
A number, N, to look for
Your job is to loop through the list and find the number specified in the second input. Output the list element index where you find the number.
If N is not found in the list, output -1.
This is what I have so far:
import and N were provided
import sys
N= int(sys.argv[2])
this is also provided
numbers= []
for i in sys.argv[1].split(","):
if(i.isdigit()):
numbers.append(int(i))
mycode
for i in numbers:
if N in numbers:
print(i)
elif N not in numbers:
print(-1)
This outputs the following for the random number inputs:
Program Failed for Input: 1,3,11,42,12 2 Expected Output: -1 Your Program Output: -1 -1 -1 -1 -1
This is not working and returns -1 for every number N that is not in the list numbers. I have tried using a break statement before and after print, but that stops it from printing at all. Any suggestions?
回答1:
Thank you for your comments and answers. After messing around with it a bit, this is what ended up providing the proper output:
My Code:
if N in numbers:
print (numbers.index(N))
if N not in numbers:
print(-1)
Output:
Program Output
Input: 1,3,11,42,12 42 Your Output: 3 Challenge Feedback
Well done!
回答2:
import sys
N= int(sys.argv[2])
print "\n"
numbers= []
for i in sys.argv[1].split(","):
if(i.isdigit()):
numbers.append(int(i))
print i
i = 0
for num in numbers:
if num == N:
print "number found at index %d " % (i)
i+=1
run this with python program_name.py [,x,y,z,l,m,n,] N
where x,y,z,l,m,n are the numbers in the list and N is the number you search ( note the [,
and ,]
)
回答3:
if N in numbers :
for num in range(len(numbers)) :
if numbers[num] == N :
print(num)
else :
print(-1)
来源:https://stackoverflow.com/questions/47381225/python-using-a-loop-to-search-for-n-number-and-return-index