Python 3 - Find the Mode of a List

2024/11/17 22:32:42
def mode(L):shows = []modeList = []L.sort()length = len(L)for num in L:count = L.count(num)shows.append(count)print 'List = ', LmaxI = shows.index(max(shows))for i in shows:if i == maxI:if modeList == []:mode = L[i]modeList.append(mode)print 'Mode = ', modeelif mode not in modeList:mode = L[i]modeList.append(mode)print 'Mode = ', modereturn modemode(L)  

I can't seem to iterate through my list properly... I can successfully get the first Mode to return Mode = 87 using the 2nd for-loop however, I can't get it to search the rest of the list so that it will also return Mode = 92

I've deleted my attempts at Mode = 92, can someone help fill in the blanks?

Answer

The first issue with your code is that you have a return statement inside your loop. When it is reached, the function ends and the rest of the iterations never happen. You should remove return mode and instead put return modeList at the top level of the function, after the loop ends.

The second issue is that you have very broken logic regarding the counts, indexes and values in your last loop. It works some of the time because the input you're testing with tends to have counts which are also valid indexes, but it gets it right almost by chance. What you want to do is find the maximum count, then find all the values that have that count. If you zip your input list L together with the shows list, you can avoid using indexes at all:

max_count = max(shows)
for item, count in zip(L, shows):if count == max_count and item not in modeList:print("mode =", item)modeList.append(item)return modeList

While that should addresses the immediate issue you're having, I feel I should suggest an alternative implementation which will be a bit faster and more efficient (not to mention requiring much less code). Rather than using list.count to find the number of appearances of each value in the list (which is requires O(N**2) time), you can use a collections.Counter to count in O(N) time. The rest of the code can be simplified a bit as well:

from collections import Counterdef mode(L):counter = Counter(L)max_count = max(counter.values())return [item for item, count in counter.items() if count == max_count]
https://en.xdnf.cn/q/120150.html

Related Q&A

Create list of sublists [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

Python error - list index out of range?

Anyone help me see why I keep getting "list index out of range" as an error ?? def printInfo(average):average.sort() # sorts the list of tuples average.reverse() # reverses the list of tu…

Access strings inside a list

A Python list has [12:30,12:45] and I want to access the 12:30 for the first iteration, and on the second iteration I should get 12:45.my_list=[12:30,12:45] for each_value in my_list:print(each_value[0…

How do I install NumPy under Windows 8.1?

How do I install NumPy under Windows 8.1 ? Similar questions/answers on overflow hasnt helped.

Design In-Memory File System - Python - Trie - Leetcode Error

I am trying to solve the below leetcode problem Design a data structure that simulates an in-memory file system. Implement the FileSystem class: FileSystem() Initializes the object of the system. List …

OpenTurns Error when trying to use kernel build [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to write data to excel with header using Pandas?

I want to write the excel file with the header isI have data and I want to fill out the excel file. Then the expected result isThis is my code but it does not show as my expected. Could you help me to …

Cooldown format in days discord.py

Im currently making a command which has a cooldown of 5 days, and Im currently using this code for the cooldown. def better_time(self, cd:int):time = f"{cd}s"if cd > 60:minutes = cd - (cd …

From scraper_user.items import UserItem ImportError: No module named scraper_user.items

I am following this guide for scraping data from instagram: http://www.spataru.at/scraping-instagram-scrapy/ but I get this error:mona@pascal:~/computer_vision/instagram/instagram$ ls instagram scrap…

Correct way of coding a Guess the Number game in Python [closed]

Closed. This question is off-topic. It is not currently accepting answers.Want to improve this question? Update the question so its on-topic for Stack Overflow.Closed 11 years ago.Improve this questio…