[Python] I'd like to pick three or more elements that came out the most among the randomly generated lists.

Asked 2 years ago, Updated 2 years ago, 18 views

import random

import collections

from collections import Counter

a=Counter()

number_list=list(range(1, 100)

for i in range(10) :

    c= random.sample(number_list, 10)

    a.update(c)

    c.sort()

    print(c)


common=[m[0] for m in a.most_common(6)]

common.sort()

print(common)

=> Out of the 10 repetitions, it's not just the 10 most number I'd like to pick the 10 most out of the 3 or more numbers. And if there are no more than three, I want to make a program that runs from scratch again, but I don't know the corresponding function or command. I just joined Python, so I don't know much. Please give me a kind reply.

python

2022-09-21 18:25

1 Answers

I don't know if it's a kind answer, but there's no function like a silver bullet that results at once.

import random
from itertools import groupby, repeat, chain

number_list=list(range(1, 100))

random_numbers_per_row = (random.sample(number_list, 10) for i in range(10))
flatten_numbers_with_sorted = sorted(chain(*random_numbers_per_row))
groupby_numbers = groupby(flatten_numbers_with_sorted)
groupby_numbers2 = ((list(v)) for k, v in groupby_numbers)
solve_numbers = list(filter(lambda item:len(item) > 2, groupby_numbers2))
print(sorted(solve_numbers, key=len, reverse = True))


[[31, 31, 31, 31, 31], [70, 70, 70, 70, 70], [3, 3, 3, 3], [32, 32, 32, 32], [28, 28, 28], [34, 34, 34], [58, 58, 58], [75, 75, 75]]

The above algorithms are as follows:


2022-09-21 18:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.