# How to express the following algorithm in python

• Hi,

Recently I am trying to use the python to rewrite my cpp-algorithm. And I found the python's for loop is really inconvenient. For example, I still have not found an elegant way translate my algorithm (Written by CPP) into python. Is there anyone has some advices? Thank you.

``````class Solution {
public:
string intToRoman(int num) {
string str;
string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int value[]=    {1000,900,500,400, 100, 90,  50, 40,  10, 9,   5,  4,   1};
for(int i=0;num!=0;++i)
{
while(num>=value[i])
{
num-=value[i];
str+=symbol[i];
}
}
return str;
}
};
``````

Cheers!

• ``````class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
ma = {}
ma[1] = 'I'
ma[5] = 'V'
ma[10] = 'X'
ma[50] = 'L'
ma[100] = 'C'
ma[500] = 'D'
ma[1000] = 'M'
res = ""
i = 10;
while(num != 0):
x = num % 10
if(x >=1 and x <= 3):
res = x*ma[i/10] + res
elif(x == 4):
res = ma[i/10] + ma[i/2] + res
elif(x >=5 and x <= 8):
res = ma[i/2] + (x-5)*ma[i/10] + res
elif(x == 9):
res = ma[i/10] + ma[i] + res
i = i *10
num = num /10
return res``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.