“Python Roman to Ganzzahlmethode 2” Code-Antworten

Python Roman to Ganzzahl

class Solution:
    def romanToInt(self, s):
 
        values = {'I': 1, 'V': 5, 'X': 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000}   
        result = 0
        for i in range(len(s)):
            if i + 1 < len(s) and values[s[i]] < values[s[i + 1]] : # if current item is not the last item on the string
                                                                    # and current item's value is smaller than next item's value 
                result = result - values[s[i]]                      # then subtract current item's value from result
            else:
                result = result + values[s[i]]                      # otherwise add current item's value to result
        return result

Task = Solution()
print(Task.romanToInt("III"))
print(Task.romanToInt("LVIII"))
print(Task.romanToInt("MCMXCIV"))
Kingsley Atuba

Python Roman to Ganzzahlmethode 2

class Solution:
    def romanToInt(self, s):
 
        values = {'I': 1, 'V': 5, 'X': 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000}   
        result = 0
        for i in range(len(s)):
            if i + 1 == len(s) or values[s[i]] >= values[s[i + 1]] : # if current item is not the last item on the string
                                                                    # or current item's value is greater than or equal to next item's value 
                result = result + values[s[i]]                      # then add current item's value from result
            else:
                result = result - values[s[i]]                      # otherwise subtract current item's value from result
        return result

Task = Solution()
print(Task.romanToInt("III"))
print(Task.romanToInt("LVIII"))
print(Task.romanToInt("MCMXCIV"))
Kingsley Atuba

römisch bis ganzzahlige Python

def romanToInt(rm_letter):
    roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
    i = 0
    num = 0
    while i < len(rm_letter):
        if i+1<len(rm_letter) and rm_letter[i:i+2] in roman:
            num+=roman[rm_letter[i:i+2]]
            i+=2
        else:

            num+=roman[rm_letter[i]]
            i+=1
    return num

roman = input("Enter roman letter: ").upper()
roman=romanToInt(roman)
print(roman)
Akshay Vs

Ähnliche Antworten wie “Python Roman to Ganzzahlmethode 2”

Fragen ähnlich wie “Python Roman to Ganzzahlmethode 2”

Weitere verwandte Antworten zu “Python Roman to Ganzzahlmethode 2” auf Python

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen