Leetcode Roman to Integer Python 计算罗马数字对应的十进制数字, for in 倒叙遍历逆循环参数设置

Leetcode 13 Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3
Example 2:

Input: "IV"
Output: 4
Example 3:

Input: "IX"
Output: 9
Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

题目大意: 计算罗马数字对应的十进制数字。有一个特例,4的表达方式是IV,即V-I。 其他类似。

思想用遍历的思想。从后往前遍历。

for i in range(len(s)-2,-1,-1): 倒叙遍历

上代码:

class Solution:
    def romanToInt(self, s: str) -> int:
        roman = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        result = roman[s[-1]] #结果先设置成字符串最后一个
        for i in range(len(s)-2,-1,-1): #从倒数第二个开始遍历
            if roman[s[i]] < roman[s[i+1]]:
                result -= roman[s[i]]
            else:
                result += roman[s[i]]
        return result

这里牵扯到一个for in 的逆循环参数遍历:

for i in range(6,-1,-1):
    print(i)
6
5
4
3
2
1
0

range(6,-1,-1):
6意思是,0到6。 中间的-1,代表着从-1开始遍历。右边的-1代表着遍历的位置每次减1。
所以多举几个例子:

for i in range(6,-1,-2):
    print(i)
6
4
2
0-1开始,遍历的位置每次-2.
for i in range(6,-2,-1):
    print(i)
6
5
4
3
2
1
0
-1-2位置开始,-2位置本来没有,所以即镜像的位置。

正常用法:

for i in range(0,6,2):
    print(i)
0
2
4
06,每两个遍历一个。

14/04/2020
疫情中的英国,
加油!


版权声明:本文为weixin_43860294原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。