You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

阿拉伯数字转罗马数字代码优化及Erlang实现方案咨询

嘿,我来帮你优化这段Python代码,同时给你写一个Erlang版本的实现,让你能直观对比理解函数式语言的处理思路~

优化后的Python实现

先看看原代码里可以精简的点:那个sub函数完全是冗余的(它返回的就是传入的第二个参数),还有一堆重复的elif分支也完全没必要。咱们可以用有序的数值-罗马符号对列表来循环处理,把重复逻辑统一起来,代码一下子就清爽了。

优化后的代码如下:

def int_to_roman(num):
    # 定义从大到小排列的数值-罗马符号对,覆盖所有特殊组合
    roman_pairs = [
        (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
        (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
        (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
    ]
    result = []
    for value, symbol in roman_pairs:
        # 只要当前数字还能减下这个值,就重复添加对应符号
        while num >= value:
            result.append(symbol)
            num -= value
        if num == 0:
            break
    return ''.join(result)

if __name__ == "__main__":
    print("Converting the Numbers into Roman:")
    num = int(input("Enter the number: "))
    print(int_to_roman(num))

这次改动后,代码逻辑更清晰,维护性也强——以后要是需要调整罗马数字规则,直接修改这个列表就行,不用改一堆分支。

Erlang实现方案

Erlang是函数式编程语言,所以咱们用递归+模式匹配来实现,这也是Erlang处理这类问题的典型方式,核心思路和Python一致,但写法更贴合函数式风格。

-module(roman_converter).
-export([int_to_roman/1]).

% 对外暴露的入口函数
int_to_roman(Num) ->
    int_to_roman(Num, [
        {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},
        {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"},
        {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}
    ], []).

% 递归终止条件:数字减到0,把收集的符号拼接成字符串返回
int_to_roman(0, _, Accumulator) ->
    lists:flatten(Accumulator);

% 匹配当前最大的数值:如果数字够减,就把符号加入收集器,递归处理剩余数字
int_to_roman(Num, [{Value, Symbol} | RestPairs], Accumulator) when Num >= Value ->
    int_to_roman(Num - Value, [{Value, Symbol} | RestPairs], [Symbol | Accumulator]);

% 当前数值不够大,跳过它,处理下一个更小的数值对
int_to_roman(Num, [_ | RestPairs], Accumulator) ->
    int_to_roman(Num, RestPairs, Accumulator).

你可以这样测试这个模块:

% 先编译模块
c(roman_converter).
% 调用转换函数
roman_converter:int_to_roman(1994). % 会返回 "MCMXCIV"

这个实现用Erlang的模式匹配替代了Python的循环判断,每个递归子句负责一种场景,逻辑非常直观,完全符合函数式语言“用递归替代循环”的风格。

内容的提问来源于stack exchange,提问作者SUBARAM RAM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:34:04