2020年9月11日 ☀
今天是刷力扣的第2天。
希望通过刷力扣学点python编程思想和知识。不是最合适的答案,但是是自己想出的解决思路。如有更好的建议,欢迎指正~
第3题:罗马数字转整数
- 难度:简单
- 题目要求:
答案 (python):
class Solution:
def romanToInt(self, s: str) -> int:
dict = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
special = {"IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900}
num = 0
i = 0
while i in range(0,len(s)):
j = i+2
if s[i:j] in special.keys():
num += special[s[i:j]]
i += 2
else:
num += dict[s[i]]
i +=1
return num
PyCharm调试:
class Solution:
def romanToInt(self, s: str) -> int:
dict = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
special = {"IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900}
num = 0
i = 0
while i in range(0,len(s)):
j = i+2
if s[i:j] in special.keys():
num += special[s[i:j]]
i += 2
else:
num += dict[s[i]]
i +=1
return num
if __name__ == "__main__":
r = Solution()
res = r.romanToInt("III")
print(res)
拓展:
- 使用
in
判断字典中是否存在某个key
:
in
理解示例:
>>> dict = {"name":"apple", "age": 1}
>>> s = "name"
>>> s in dict.keys()
True
- 使用
in
判断字典中是否存在某个value
:
in
理解示例:
>>> dict = {"name":"apple", "age": 1}
>>> s = "apple"
>>> s in dict.values()
True
- 在for循环体内修改i值,并使其对下次循环有效:使用
while 替换 for
即可。实际上,在for循环内修改i值,只会对当前一次的循环体内有效。
每天积累一小点。–该图片来源网络,如有侵权,请告知删除。