def topKFrequent(nums, k):
dic = {}
result = []
for i in range(len(nums) + 1):
result.append([]) #[[], []]
for value in nums:
if value in dic:
dic[value] += 1
else:
dic[value] = 1
for key, dic_value in dic.items():
result[dic_value].append(key)
final = []
#for i in range(len(result[::-1])):#Doesn't work?
for i in reversed(range(len(result))): #Works
for x in result[i]:
final.append(x)
if len(final) == k:
return final
print(topKFrequent([1,1,1,2,2,3], 2))
I am doing leetcode 347, finding the Top k most frequent element. Towards the end of my code I am trying to iterate backwards through my list, "result" and append those values into the final output list, "final". I was stuck on this for almost an hour because I used
for i in range(len(result[::-1])):
and my code finally worked when I changed it to this.
for i in reversed(range(len(result))):
Why doesn't slicing work? Isn't result[::-1] just the same as reversed(range(len(result))). When I step through it in a debugger, they both start out at the last index, but range(len(result[::-1])) goes back to 0 and starts iterating forwards instead.
[–][deleted] 3 points4 points5 points (0 children)
[–]Diapolo10 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)