ALAN
ALAN

Reputation: 41

Sum integer list when next integer is the same value

So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

input1 = [int(i) for i in str(1234441122)]
x= 0

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2. I do not know any way to do that.

Upvotes: 0

Views: 143

Answers (7)

Anshul Goyal
Anshul Goyal

Reputation: 21

You are simply iterating on string and converting character to integer. You need to iterate and compare to next character.

a = str(1234441122)
sum = 0
for i,j in enumerate(a[:-1]):
    if a[i] == a[i+1]:
        sum+=int(a[i])
print(sum)

Output

11

Upvotes: 2

Stefan Pochmann
Stefan Pochmann

Reputation: 28626

No need for that list. You can remove the "non-repeated" digits from the string already:

>>> n = 1234441122
>>> import re
>>> sum(map(int, re.sub(r'(.)(?!\1)', '', str(n))))
11

Upvotes: 2

user2390182
user2390182

Reputation: 73470

The following will work. Zip together adjacent pairs and only take the first elements if they are the same as the second ones:

>>> lst = [1, 2, 3, 4, 4, 4, 1, 1, 2, 2]
>>> sum(x for x, y in zip(lst, lst[1:]) if x == y)
11

While this should be a little less [space-]efficent in theory (as the slice creates an extra list), it still has O(N) complexity in time and space and is well more readable than most solutions based on indexed access. A tricky way to avoid the slice while still being concise and avoiding any imports would be:

>>> sum((lst[i] == lst[i-1]) * lst[i] for i in range(1, len(lst)))  # Py2: xrange
11

This makes use of the fact that lst[i]==lst[i-1] will be cast to 0 or 1 appropriately.

Upvotes: 8

Transhuman
Transhuman

Reputation: 3547

Another way using itertools.groupby

l = [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]
from itertools import groupby
sum(sum(g)-k for k,g in groupby(l))
#11

Upvotes: 4

timgeb
timgeb

Reputation: 78750

Here's a slightly more space efficient version of @schwobaseggl's answer.

>>> lst = [1, 2, 3, 4, 4, 4, 1, 1, 2, 2]
>>> it = iter(lst)
>>> next(it) # throw away first value
>>> sum(x for x,y in zip(lst, it) if x == y)
11

Alernatively, using an islice from the itertools module is equivalent but looks a bit nicer.

>>> from itertools import islice
>>> sum(x for x,y in zip(lst, islice(lst, 1, None, 1)) if x == y)
11

Upvotes: 1

Vasilis G.
Vasilis G.

Reputation: 7844

Try this one too:

input1 = [int(i) for i in str(1234441122)]
x= 0
res = [input1[i] for i in range(len(input1)-1) if input1[i+1]==input1[i]]
print(res)
print(sum(res))

Output:

[4, 4, 1, 2]
11

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71461

You can try this:

s = str(1234441122)
new_data = [int(a) for i, a in enumerate(s) if i+1 < len(s) and a == s[i+1]]
print(new_data)
final_data = sum(new_data)

Output:

[4, 4, 1, 2]
11

Upvotes: 2

Related Questions