-1

I need to iterate through a string using characters instead of indices. For instance, for the string s. it would be something like:

for n in s:
   .........
   .........

where n is a character in the string. Is there any way I can refer to the next immediate character (from this string) in this 'for' loop, without making use of its index?

Context: This is for the problem in LeetCode to convert Roman numerals into numbers, for which I wrote the code as follows:

class Solution:
    def romanToInt(self, s: str) -> int:
        '''
        Logic: 
        1. Create two cases: non on right is lesser than no on left and vice versa 
        2. If right > left, subtract left from right and add to value. Skip one position in loop. 
        3. If left > right, simply add value of left to total, and move to next in loop.     
        
        '''
        roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        val = 0 # value of roman numeral 
        
        for n in s:
            if roman[n] > roman[n+1]:
                val += roman[n]
                n = n + 1
                return n 
            elif roman[n] < roman[n+1]:
                val += roman[n+1]-roman[n]
                n = n + 2
                return n 
            return val 

which obviously returns an error every time I try to add a character n to an integer 1. Which is why I am looking for a way to iterate chracterwise rather than using the indices.

Thank you!

K2G
  • 27
  • 1
  • 9
  • I think both answers does not answer what you are looking for. Which means, your question needs some clarification. If I get you right, you want to access i+1'th (or i-1'th) element of the string in the for loop where i is the current index. Correct ? – Alp Dec 18 '20 at 09:09
  • yep, that's what I'm looking for. – K2G Dec 18 '20 at 09:23

2 Answers2

0

You could create a new string with the characters offset by 1, zip that with the original string, then iterate over the resulting list of tuples.

for this_char, next_char in zip(s, list(a)[1:] + [None]):
    # next_char will be None in the last iteration
    pass

Explanation

# convert the string to a list
offset_string = list(a)

# shift the list by one via slicing
offset_string = offset_string[1:]

# since the list is 1 element shorter than the string, add a `None` to the end so we still can have the last character
offset_string = offset_string + [None]

for this_char, next_char in zip(s, offset_string):
    pass
dogman288
  • 613
  • 3
  • 9
0

I dont think what you are looking for is making any sense... The best approach i can think of is like this..

for i, n in enumerate(s):
    next_char = s[min((i+1, len(s)-1))]
    # do your stuff
adir abargil
  • 5,495
  • 3
  • 19
  • 29