Issue
I’m writing a Python program to find the position of the second occurrence(index) of a given number in a given list of numbers.
The function will take as input a list of numbers as the first argument and a numeric variable as the second argument. This function should return the index where the given variable value occurs in the list for the second time. If the number does not occur for the second time in the input list or if the number does not exist, the function should return 0.
def getIndex(listOfIntegers,NumericVariable):
inp=int(NumericVariable)
for i in listOfIntegers:
if i==inp:
b=(listOfIntegers.index(i))
c=b+1
if c<len(listOfIntegers):
y=listOfIntegers[c:]
for j in y:
if j == inp:
d=(y.index(j))
res=d+c
return res
continue
else:
return 0
if __name__ =='__main__':
l1=[]
size=int(input())
for i in range(size):
l1.append(int(input()))
num=int(input())
output=getIndex(l1,num)
print(output)
This is the code I used although I get the results as expected, it says some of the test cases failed. Please suggest to me what could have gone wrong or how can I improve this code.
Thank You
Solution
Other version:
def getIndex(listOfIntegers, NumericVariable):
occurrence = 0
for index, number in enumerate(listOfIntegers):
if number == NumericVariable:
occurrence += 1
if occurrence == 2:
return index
return 0
Answered By – Domarm
Answer Checked By – Clifford M. (BugsFixing Volunteer)