How to find the index of value in python list?

Considering large inputs, where could the possible bottleneck for this Python code be?

  • The following Python code is counting the frequency of given integers and prints the integer which has the highest frequency. Working for small input takes where n < 1000, while TLE for n > 10000 #No of testcases t=int(raw_input().strip()) #Loop through the test cases for i in range (0,t): #take number of values n=int(raw_input().strip()) #split and store them in list named 'num' num=raw_input().strip().split(' ') #Another list named 'count' initialized with zero. count = [0] * (int(max(num))+1) #Loop over the numbers entered to and check their frequencies for j in num: count[int(j)]+=1 #enumerate over the list 'count' and reverse it to get orignal index for duplicate frequency for w, x in reversed(list(enumerate(count))): if x == max(count): print w, print Can anyone help me find the bottleneck in the python solution ? Input: 3 5 1 2 2 2 2 6 1 2 2 3 3 4 14 1 1 1 1 1 1 1 5 5 5 5 5 5

  • Answer:

    I'd change you code slightly to this: #!usr/bin/python t = int(raw_input().strip()) for i in range (0,t): n = int(raw_input().strip()) num = [int(i) for i in raw_input().strip().split(' ')] count = {} for j in num: if j in count: count[j] += 1 else: count[j] = 1 maxn = num[0] maxf = count[num[0]] for x in count: if count[x] > maxf: maxf = count[x] maxn = x print maxn

Anonymous at Quora Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.