Search code examples
pythoncompression

I dont know why my code isn't counting the last 2 values


I'm trying to make a code (for school) that compresses and counts the number of adjacent characters that are the same. in this example it would be 4(1) 4(0) 2(1) 2(0). it is supposed to output: 4 4 2 2 but for some reason, it leaves out the last 2.

does anyone know how to fix this or make my code more optimised?

my code:

val = "111100001100"  #the value
count1 = 0  #counts how many repeated values there are
count0 = 0
num = 0
char = val[num]
char_count = 0
length = len(val)
l1 = length - 1 

for char in range(l1):
  if val[char + 1] == val[char]:
    count1 += 1
    char_count + 1
  elif val[char + 1] != val[char]:
    x = str(count1 + 1)
    print(x)
    count1 = 0
    char_count + 1*

the output: 4 4 2


Solution

  • You could use itertools.groupby.

    To see how it works, here is what it does to your val:

    print([(k, list(v)) for k,v in itertools.groupby(val)])
    
    [('1', ['1', '1', '1', '1']),
     ('0', ['0', '0', '0', '0']),
     ('1', ['1', '1']),
     ('0', ['0', '0'])]
    

    To get your desired output, we only need to get the length of the list for each group.

    print(*[len(list(v)) for k,v in itertools.groupby(val)])
    
    4 4 2 2
    

    If you want it to do it your way, I made some little changes to make it work. You could add an extra condition to check if it is the last element in the list and then print the current value of count1.

    val = "111100001100"  #the value
    
    count1 = 0  #counts how many repeated values there are
    length = len(val) # 12
    
    for char in range(length):
        if not char==length-1:
            if (val[char + 1] != val[char]):
                x = str(count1 + 1)
                print(x)
                count1 = 0
            elif val[char+1] == val[char]:
                count1 += 1
        else:
            x = str(count1 + 1)
            print(x)
    
    4 4 2 2