I'm trying to figure out how I can take a list of integers and return all the items in that list into another list as their max value, but with their index.
So I need to be able to do this without using enumeration, lambda, numpy, or anything of that sort. It has to be really basic methods for lists. Basically, things like append, max, etc. . . If for statements are fine too.
To clarify what I'm trying to do, say I have a list: [4, 34, 0, 0, 6, 34, 1]
I want it to return [1, 5]
Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we find the maximum out of it.
Given a list, the task is to find the number of occurrences of the largest element of the list. Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list.
If you want to get the indices of the three largest values, you can just slice the list. It also supports sorting from smallest to largest by using the parameter rev=False .
Simplest approach:
in [24]: a = [4, 34, 0, 0, 6, 34, 1]
In [25]: j=0
In [26]: M=[]
In [27]: m = max(a)
In [28]: for i in a:
if i==m:
M.append(j)
j+=1
....:
In [29]: M
Out[29]: [1, 5]
Using list-comprehension and enumerate, the above can be shortened to:
In [30]: [i for i, x in enumerate(a) if x == max(a)]
Out[30]: [1, 5]
A "fully manual" approach, using none of those pesky standard library functions:
def get_max_indices(vals):
maxval = None
index = 0
indices = []
while True:
try:
val = vals[index]
except IndexError:
return indices
else:
if maxval is None or val > maxval:
indices = [index]
maxval = val
elif val == maxval:
indices.append(index)
index = index + 1
What it loses in brevity, it gains in... not much.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With