Python Forum

Full Version: frequency of largest number group
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

i have a list e.g
a=[112211121112222121122111]
i want to find the frequency of the largest group of '1' and '2'

e.g in 'a' for number 2: '22' is the largest group and its frequency= 2
and for number 1: '111' is the largest group and its frequency=3

Thank you,
this is a list with jut one element. Is this really what you work with?
why the expected output for 2 is 22? There is group 2222.
sorry, my mistake, please ignore '2222' rest of the question is same,

Thank you
Hello,

i have a list e.g

a=[112211121112121122111]

i want to find the frequency of the largest group of '1' and '2'

e.g in 'a' for number 2: '22' is the largest group and its frequency= 2
and for number 1: '111' is the largest group and its frequency=3

Thank you,
a = [112211121112121122111] is a list with only one element.
The answer to your question is effortless because there is only one element in your list.

I guess you mean a sequence like this:
a = [1, 1, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 1, 2, 1, 1, 2, 2, 1, 1, 1]
The items in the list are Integers, but they could also be str or something else.

Make a function, which saves the last_value, start_index and current index.
If there is a difference between last and current value, you've to add the last value with start_index, end_index to a list. Then you assign the current_value to last_value and the start_index. After your loop is done, you've to add the last remaining group.

Then you have a list with items where one value is the value itself, start_index and end_index.
You can get the shortest and longest group with a key function.

So if you save the groups like this pattern:
(value, start_index, end_index)
You can get the longest and shortest distance by calculating it.

def by_distance(element):
    value, start, end = element
    return end - start


result = [(42, 4, 22), (33, 22, 25)]
print("Shortest")
print(min(result, key=by_distance))
print("Longest")
print(max(result, key=by_distance))
Just brute force :-)

from itertools import groupby

a = [1, 1, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 1, 2, 1, 1, 2, 2, 1, 1, 1]

for item in set(a):
    print(f'{item}: {max(len([*streak]) for el, streak in groupby(a) if item == el)}')

# will output something like that (sets are unordered):
1: 3
2: 4