Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one compare items in a list sequentially?

I'm VERY new to coding and am playing through some toy problems to learn but have hit a wall with this one. (yes, I know I don't make good variable names).

I am trying to find the sum of all digits that match the next digit in the list. I got it to look at the items in sequence but it seems to get tripped up when it hits a duplicate. I ran the following code to check my progress:

code_string = "9511484596541141557316984781494999"
list(code_string)
for n in code_string:
   nextn = code_string[code_string.index(n)+1]
   if n == nextn:
      print(n)

and all I get is:

1
1
1
1
1
1
1

Why is it jumping around in my list rather than moving onto the next in sequence? Does it have something to do with converting a string to a list? I want to do eventually do this with a MUCH larger list.

like image 333
Lisi Avatar asked May 02 '26 16:05

Lisi


1 Answers

index returns the first index of the digit in the string and performs a O(n) lookup on the string. You don't want to use that.

Either use enumerate to yield the index & the value (but you have to test if the index is not the last one else this +1 will make your program crash) or interleave (zip) the string with a sliced version lacking the first element: this provides an item and its successor.

Then you can compare:

code_string = "9511484596541141557316984781494999"
for d1,d2 in zip(code_string,code_string[1:]):
   if d1==d2:
      print(d1)

outputs:

1
1
5
9
9

finding the sum of those numbers can be achieved in a classic way, or in one line using sum and a generator comprehension (convert the digit to integer prior to summing):

result = sum(int(d1) for d1,d2 in zip(code_string,code_string[1:]) if d1==d2)

(which is 25)

like image 109
Jean-François Fabre Avatar answered May 04 '26 05:05

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!