Kee
Kee

Reputation: 163

Find most numbers occurrences in lists

def print_most_numbers_occurrences(numbers_str):
    number_list = list(numbers_str)
    for i in number_list:
        i=max(number_list,key=number_list.count)
    print(i)

def test_print_most_numbers_occurrences():
    print_most_numbers_occurrences('2 3 40 1 5 4 3 3 9  9')
    print_most_numbers_occurrences('9 30 3 9 3 1 4')
    print_most_numbers_occurrences('19 30 13 4 9 3 1 4')


def main():
    print(test_print_most_numbers_occurrences())


main()

output

None

It works when I try this way:

>>> lst = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 545, 56, 6, 7, 67]
>>> max(lst,key=lst.count)
4

I want to identify the number that occurred the highest number of times. I'm not sure where i did wrong for first def function.

Upvotes: 3

Views: 859

Answers (5)

Darkstarone
Darkstarone

Reputation: 4730

You first need to parse your input correctly. You can't just use split(" ") on its own since one of your inputs had a double space.

Secondly, you don't need a loop since max does the looping for you.

def print_most_numbers_occurrences(numbers_str):
    number_list = [int(x) for x in numbers_str.split()]
    i=max(number_list,key=number_list.count)
    print(i)

Since you were looping I took the liberty to assume you were trying to deal with the case where multiple numbers might have equal occurrences (e.g: '2 3 40 1 5 4 3 3 9 9 9'). In that case, the following code would get all maximums:

def print_most_numbers_occurrences(numbers_str):
    print(numbers_str.split(" "))
    number_list = [int(x) for x in numbers_str.split()]
    most_occurances = []
    for i in set(number_list):
        occurances = number_list.count(i)
        if len(most_occurances) == 0:
            most_occurances.append(i)
        elif most_occurances[0] < occurances:
            most_occurances = [i]
        elif most_occurances[0] == occurances:
            most_occurances.append(i)
    print(most_occurances)

Here's a more concise version that uses slightly more complex code:

def print_most_numbers_occurrences(numbers_str):
    number_list = [int(x) for x in numbers_str.split()]
    result = {i : number_list.count(i) for i in set(number_list)}
    highest = max(result.values())
    most_occurances = [k for k, v in result.items() if v == highest]
    print(most_occurances)

If you need highly efficient code, it is wise to use collections Counter:

from collections import Counter

def print_most_numbers_occurrences(numbers_str):
    number_list = [int(x) for x in numbers_str.split()]
    result = Counter(number_list)
    highest = max(result.values())
    most_occurances = [k for k, v in result.items() if v == highest]
    print(most_occurances if len(most_occurances) > 1 else most_occurances[0])

Upvotes: 3

Jared Goguen
Jared Goguen

Reputation: 9010

Use can use str.split() to break your string into a list. Then, you can use map to convert the strings into integer. A collections.Counter can be used to count the occurrence of each integer in a relatively efficient manner. Finally, max with a lambda argument to key over the number of occurrences can be used to pull out the target value.

string_list = '2 3 40 1 5 4 3 3 9  9'.split()
int_list = map(int, string_list)

from collections import Counter

counter = Counter(int_list)
target_value, occurrence_count = max(counter.items(), key=lambda t: t[1])

Note that no argument is provided to str.split and the use of list.count is avoided (which is quite inefficient in this scenario). If you want to get all of the target values with the maximum number of occurrences, you can abandon that last line and use:

max_occurrences = max(counter.values())
target_values = [k for k, v in counter.items() if v == max_occurrences]

Upvotes: 1

Gahan
Gahan

Reputation: 4213

You can simply write your code as:

>>> import re
>>> x
'2     3   40    1  5 4  3  3 9  9'
>>> list = re.sub(' +', ' ', x).split(' ')
>>> list
['2', '3', '40', '1', '5', '4', '3', '3', '9', '9']
>>> max(list, key=list.count)
'3'
>>> x = '19 30 13 4 9 3 1 4'
>>> list = re.sub(' +', ' ', x).split(' ')
>>> list
['19', '30', '13', '4', '9', '3', '1', '4']
>>> max(list, key=list.count)
'4'
>>> 

so your function should be as:

def fun(num_string):
    num_list = re.sub(' +', ' ', num_string).split(' ')
    print(max(num_list, key=num_list.count))  # you can write print but I prefer you should use return max(num_list, key=num_list.count)

Upvotes: 0

Neil
Neil

Reputation: 14313

There are actually a couple issues with the code as it currently stands. You seem to be printing the result of a function that returns None and you're not splitting your string properly:

def print_most_numbers_occurrences(numbers_str):
    number_list = [int(number) for number in numbers_str.split(' ') if number != ""]
    for i in number_list:
        i=max(number_list,key=number_list.count)
    print(i, number_list.count(i))

def test_print_most_numbers_occurrences():
    print_most_numbers_occurrences('2 3 40 1 5 4 3 3 9  9')
    print_most_numbers_occurrences('9 30 3 9 3 1 4')
    print_most_numbers_occurrences('19 30 13 4 9 3 1 4')


def main():
    test_print_most_numbers_occurrences()


main()

Upvotes: 0

Ben Langlois
Ben Langlois

Reputation: 86

Use .split(' ') instead of list()

string = '9 30 3 9 3 1 4'
lst = map(int, filter(None, string.split(' ')))
print(max(lst, key = lambda x: lst.count(x)))
# returns 9

Upvotes: 2

Related Questions