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!