2017-09-12 1 views
0
def search(arr, x): 
    for i in range(len(arr)): 

     if arr[i] == x: 
      return i 

    return -1 



num=input("enter the elements\n") 
input_numbers_list = [int(n) for n in num.split()] 

value=input("enter the element to be searched") 
print(input_numbers_list) 
print(value) 
i = search(num,value) 
if i is -1: 
    print("element not found") 
else: 
    print("element found at specific position "+str(i)) 
+0

당신은 사용할 수 있습니다 ['지수()'(https://docs.python.org/3/library/stdtypes.html#common-sequence-operations) 등 'print (input_number_list.index (int (value)))'도 가능합니다. 값이 존재하지 않는 경우 'ValueError' 예외를 포착해야합니다. –

답변

1

바로 지금 문자열을 검색에 전달합니다. 입력 문자열에서 문자를 반복하고 문자가 두 번째 문자열과 같은지 확인합니다. 이것을 고려하십시오 :

'12345'[2] == '3' 

valueint로 변환 : 검색에

value = int(input('enter the element to be searched')) 

패스 정수가 아닌 입력 :

i = search(input_numbers_list, value) 
+0

@VedantBari 제발, 대답을 수락하는 것을 잊지 마세요. 도움이된다면 답의 점수 아래에 'V'표시가 있습니다. –

0

다닐 멀리 문제와 당신 제곱, 난 그냥 원 당신의 기능을 수행하는 또 다른 방법을 추가하십시오.

for index,item in enumerate(somelist): 
    if item == 'dragon': 
     print('The dragon was found in the following index: {}'.format(index)) 

추가하는 또 다른 것은 당신의 분할 속성입니다 : 당신과 같이 변수에 할당 할 수있는 인덱스 및 항목을 반환하는 열거라는 내장 방법이있다. 어떻게 문자열을 분할 할 것인지 명시해야합니다. 내가 가장 좋아하는 것은 쉼표로 쓰지만 공백도 사용할 수 있습니다.

somelist = input('Enter your items comma separated\n') 
somelist = [ i for i in somelist.split(',') ] 

또는

somelist = input('Enter your items space seperated\n') 
somelist = [ i for i in somelist.split(' ') ] 
관련 문제