Home > Enterprise >  Wrong result on LeetCode problem due to Variable Scope (probably)
Wrong result on LeetCode problem due to Variable Scope (probably)

Time:04-13

So I finished solving this problem on LeetCode : Convert a Decimal number into a Roman Numeral Convert a Decimal into a Roman Numeral, and the code that i wrote in Python works for the test cases they provide directly from the site, works in VS code, Jupyter Notebooks...

But upon trying to officially submit the code, it gives a wrong answer : Submit Wrong Answer

After some research, many many errors like these happen because people misuse global class variable like :

class DisjointSet:
    set = {}
    lst = []

And the good way is to do it like this :

class DisjointSet:
    # default constructor, init all member data.
    def __init__(self):
        self.sets = {}     # This is init for each test case.
        self.longest = 0   # This is init for each test case.

but the thing is in my code I'm doing something similar and i'm still getting the error:

class Solution(object):
    def __init__(self):
        self.Roman = []     # This is init for each test case.
        self.Declist = []   # This is init for each test case.
   
 def intToRoman(self, num):
        strDec = str(num)
        dico_regular = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        dico_special = {4: 'IV', 9: 'IX', 40: 'XL', 90: 'XC', 400: 'CD', 900: 'CM'}
        keys = list(dico_regular.keys())
        values = list(dico_regular.values())

        '''This part under is just a way of putting, let's say 3724 in a list [3000, 700, 20, 4]'''
        for v,i in enumerate(strDec[::-1]):
            self.Declist.insert(0, int(i) * (10 ** v))
        
        #--------------------------------------------------------------------------------------
        for item in self.Declist:
            x = item
            if item in dico_special: 
                self.Roman.append(dico_special[item])
                continue
                
            if item > 1000 :
                self.Roman.append("M"* (item//1000))
                continue

            while x != 0:
                for i in range(1,len(values)):
                    if values[i-1] <= x < values[i]:
                        x -= values[i-1]
                        self.Roman.append(keys[i-1]) 

        return "".join(self.Roman)

CodePudding user response:

As suggested by @ThierryLathuille you need to remove the references to self.Declist and self.Roman and make them local variables.

Copy/Paste this code to LeetCode

class Solution(object): 
    def intToRoman(self, num):
        Roman = [] 
        Declist = []
        
        strDec = str(num)
        dico_regular = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        dico_special = {4: 'IV', 9: 'IX', 40: 'XL', 90: 'XC', 400: 'CD', 900: 'CM'}
        keys = list(dico_regular.keys())
        values = list(dico_regular.values())

        '''This part under is just a way of putting, let's say 3724 in a list [3000, 700, 20, 4]'''
        for v,i in enumerate(strDec[::-1]):
            Declist.insert(0, int(i) * (10 ** v))
        
        #--------------------------------------------------------------------------------------
        for item in Declist:
            x = item
            if item in dico_special: 
                Roman.append(dico_special[item])
                continue
                
            if item > 1000 :
                Roman.append("M"* (item//1000))
                continue

            while x != 0:
                for i in range(1,len(values)):
                    if values[i-1] <= x < values[i]:
                        x -= values[i-1]
                        Roman.append(keys[i-1]) 

        return "".join(Roman)

Then you can test that the code works doing:

a = Solution()
print(a.intToRoman(58))

and it correctly prints LVIII for 58

CodePudding user response:

Yep, just found out the problem. First of all, I was submitting my answer in LeetCode under Python and not Python3, which is why I had all those weird errors, and Second of all, my solution had an error in it (Yes, i'm sorry @Thierry Lathuille, you were right in the end..) which was this line if item > 1000: which is supposed to be if item >= 1000:. So in the end my solution got submitted and alas everything ended well! also big thanks to everyone involved in this thread, you were great help!

  • Related