How could one find the length of longest row of same elements in a list. For example if i have a list

list = [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1]

and i need to find the the length of longest row of 0's. In this case it would be 7, cause there are 7 zeros starting with list[6] up to list[12]

Recommended Answers

All 6 Replies

ok i managed it myself:

for i in list:
    if(list[i] == 1):
        x += 1
    if(list[i] == 0):
        if(size < x):
            size = x
        x = 0

Hint, don't use list as a variable name. It is a Python function name. Use something like mylist.

Did you test out your approach? There are a few things missing.

well i just found out that if the longest row is in the end of the list it doesn't count it. i'm thinking of adding another "if" after "for" finishes its work. maybe there's some better way to do it but i didn't fid it out yet.

ok i modified it a bit. now it's working like it is supposed to.

size = 0
x = 0
         for element in blist:
            if(element == 0):
               x += 1
               if(size < x):
                  size= x
            else:
               x = 0

Fix your indentations and you are in business. Fine work!

FWIW, a more generic solution using a list to keep track of the maximum's value and the number of times it occurs.

def find_the_max(blist):
    ## a list containing the value and the number of times it appears
    max_group = [blist[0], 0]
    this_group = [blist[0], 0]
    for el in blist:
        if el == this_group[0] :
            this_group[1] += 1
        else:
            ## test for a new max
            if this_group[1] > max_group[1]:
                max_group = this_group[:]
            this_group = [el, 1]

    ## allow for the final group to be the longest
    if this_group[1] > max_group[1]:
        max_group = this_group[:]
    print max_group


blist = [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1]
find_the_max(blist)
clist = [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2]
find_the_max(clist)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.