Aei
Aei

Reputation: 715

In Python, how can I increment a count conditionallly?

Say I have the list:

list = [a,a,b,b,b]

I'm looping over the list. The variable "count" increments by 1 when the previous letter is the same as the current letter. Below is only part of the code:

for item in list:
    if item == previous:
        count +=1
return count

The example above returns 3, 1 for the repeat a and 2 for the bs. What can I use to make it so count only increases once for each for a total of 2? I tried using a variable "found" that returns True or False depending on whether the letter has been seen before, but this of course doesn't work for something like [a,a,a,c,a,a,a], which returns 1 for the first run of "a"s and not 2, as I want.

Edit: I'm probably making this harder than it needs to be. All I want is for anytime a string is repeated continuously for a count to be incremented by one. [a,b,b,c,a,a,a,a,c,c,c,] should return 3. [a,a,a,a,a,a,a,a] should return 1.

Upvotes: 1

Views: 14617

Answers (7)

eos87
eos87

Reputation: 9353

I hope this works for you.

a = ['a', 'b', 'b', 'c', 'a', 'a', 'a', 'a', 'c', 'c', 'c']
previo = None
counter = 0
temp_l, checked = [], []
for item in a:
    if item != previo:
        temp_l = []

    if not temp_l or item == previo:
        temp_l.append(item)
        previo = item

    if len(temp_l) >= 2 and item not in checked:
        counter += 1
        checked.append(item)

    previo = item

print counter

Upvotes: 1

James
James

Reputation: 1

I'm not sure I understand the question clearly and it's rather old now but for what it's worth is this what you wanted (the number of unique values)?

>>> some_list = ['a', 'a', 'b', 'b', 'b']
>>> len(set(some_list))
2

See also https://docs.python.org/2/tutorial/datastructures.html#sets.

Upvotes: 0

IT Ninja
IT Ninja

Reputation: 6430

import collections
defaultdict=collections.defaultdict
def get_count(string):
    d=defaultdict(int)
    for k in string:
        d[k]+=1
    return max(d.items(),key=lambda a:a[1])

Something like this could work, and you can use it like:

common_character,occurances=get_count("aaaaabbbbbcccdddd")

Upvotes: 0

dnozay
dnozay

Reputation: 24314

def max_contiguous_repeat(data):
   max_repeats = 0
   if data:
      previous = data[0]
      count = 0
      for item in data[1:]:
         if item == previous:
            count += 1
            continue
         max_repeats = max(count, max_repeats)
         previous = item
         count = 0
      max_repeats = max(count, max_repeats)
   return max_repeats

Upvotes: 1

kevintodisco
kevintodisco

Reputation: 5181

If I'm understanding your question correctly, you want to only count the number of letters that are repeated at least twice in a row in the list? You could store a list of letters found. Something like this should accomplish what you need:

l = ['a', 'a', 'b', 'b', 'b']
repeated = []
previous = None
count = 0
for item in l:
    if item == previous and item not in repeated:
        count += 1
        repeated.append(item)
    else:
        repeated = []
    previous = item
return count

Note that DSM has posted a much more python-esque way of accomplishing this.

Upvotes: 0

DSM
DSM

Reputation: 353059

Wild guess: since you want a,a,b,b,b to be 2 and not 3, and you also want a,a,a,c,a,a,a to give two, I think you're trying to count distinct contiguous groups of equal elements of length >= 2. If so, you can use itertools.groupby:

>>> import itertools
>>> seq1 = ['a','a','b','b','b']
>>> [(k, list(g)) for k,g in itertools.groupby(seq1)]
[('a', ['a', 'a']), ('b', ['b', 'b', 'b'])]
>>> seq2 = ['a','a','a','c','a','a','a']
>>> [(k, list(g)) for k,g in itertools.groupby(seq2)]
[('a', ['a', 'a', 'a']), ('c', ['c']), ('a', ['a', 'a', 'a'])]

and thus

>>> sum(len(list(g)) >= 2 for k,g in itertools.groupby(seq1))
2
>>> sum(len(list(g)) >= 2 for k,g in itertools.groupby(seq2))
2

but this is just a guess. It's the only thing I can think of which matches the only two data points you've given, at least assuming that I'm interpreting "1 for the first run of "a"s and not 2, as I want" correctly. That leaves it unclear whether you want the total to be 2 or the contribution from the first run of "a" to be 2.

Upvotes: 1

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

I'm not sure exactly what you want this to produce, but either way, your code is missing a lot.

my_list = ['a', 'a', 'b', 'b', 'b']
previous = None
count = 1
for item in my_list:
    if item == previous:
        count += 1
    else:
        count = 1
    previous = item
print count
  • First, a and b are variables.... 'a' and 'b' are strings.
  • Next, you never initialized previous and count.
  • Next, you were using = (which is assignment) instead of == for comparison.
  • Next, you weren't resetting count if the two were not equal.
  • Finally, you weren't setting previous to item each iteration.

This code produces 3, because there are 3 b's at the end.

Upvotes: 0

Related Questions