整数转罗马数字 python
Python 整数 罗马数字
2023-09-14 09:15:50 时间
一个容易理解的方法
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
tmp = []
roman = ''
if not num:
raise ValueError
while num >= 1000:
num -= 1000
tmp.append('M')
while num >= 900:
num -= 900
tmp.append('CM')
while num >= 500:
num -= 500
tmp.append('D')
while num >= 400:
num -= 400
tmp.append('CD')
while num >= 100:
num -= 100
tmp.append('C')
while num >= 90:
num -= 90
tmp.append('XC')
while num >= 50:
num -= 50
tmp.append('L')
while num >= 40:
num -= 40
tmp.append('XL')
while num >= 10:
num -= 10
tmp.append('X')
while num >= 9:
num -= 9
tmp.append('IX')
while num >= 5:
num -= 5
tmp.append('V')
while num >= 4:
num -= 4
tmp.append('IV')
while num >= 1:
num -= 1
tmp.append('I')
return roman.join(tmp)
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
tmp = []
hashmap = {'I': 1, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900, 'V': 5,
'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
sort_hashmap = sorted(hashmap.items(), key=lambda _: _[1], reverse=True)
roman = ''
for i in range(len(sort_hashmap)):
while num>=sort_hashmap[i][1]:
num -= sort_hashmap[i][1]
tmp.append(sort_hashmap[i][0])
return roman.join(tmp)
相关文章
- 【Python】python 日期操作
- Python操作Mysql实例代码教程在线版(查询手册)_python
- Python程序 #!/usr/bin/python 的解释
- python map()
- python: 安装DeOldify库:黑白图片上色(Python 3.7.15)
- Python Django 一对多正向查询示例
- 华为OD机试 - 判断一组不等式是否满足约束并输出最大差(Java & JS & Python)
- 华为OD机试 - 路灯照明问题(Java & JS & Python)
- Python之多线程:python多线程设计之同时执行多个函数命令详细攻略
- Python:pmml格式文件的简介、安装、使用方法(利用python将机器学习模型转为Java常用的pmml格式文件)之详细攻略
- Python语言学习之常见语句命令那些事:python和常见语句命令(条件语句、pass语句)使用方法之详细攻略
- Python可视化数据分析01、python环境搭建
- 〖Python自动化办公篇⑳〗 - python实现邮件自动化 - 发送html邮件和带附件的邮件
- python数据处理:对缺失值批量平均值补充
- 从零开始学python | 使用Python映射,过滤和缩减函数:所有您需要知道的
- 【Python成长之路】python 基础篇 -- global/nonlocal关键字使用
- 【华为机试真题 Python实现】将整数倒序输出,剔除重复数据
- 【华为机试真题 Python实现】最少交换次数来组合小于k的整数【2022 Q2 |100分】
- PCA-python实现综合评价求解
- Python编程:shelve模块-持久化python数据
- python里使用enum库--通过它的构造函数来创建枚举类型
- selenium+python自动化测试--登录
- python基础===PEP网站,代码规范指南
- python基础===Python性能优化的20条建议
- python import引入不同路径下的模块
- 【Leetcode刷题Python】343. 整数拆分
- 【Python基础】python爬虫之异步网络爬虫ǃ
- Python&Opencv基于CNN手势识别玩恐龙跳小游戏(完整源码&自定义UI操作界面&视频教程)
- LeetCode:罗马数字转整数(Python版本)