DEV Community

Discussion on: Algorithms Problem Solving: Ransom Note

Collapse
amrmonier profile image
AmrMonier

this my solution, i didn't want to match any character again if i already know that it's n't in the ransom note.
i think this would be a good solution in case the magazines string is huge.
but i have a question for huge strings (would it be better if we sorted the strings first ?)

class RansomNote:
    def __init__(self, note: str, mags: str) -> bool:
        self.note = note
        self.mags = mags
        if self.checkValidInput():
            if(self.canBeConstructed()):
                print('Message Can Constructed')
            else:
                print('Can\'t be constructed')
        else:
            print('Can\'t be constructed')

    def checkValidInput(self) -> bool:
        if(len(self.mags) < len(self.note)):
            return False
        return True

    def isInRansom(self, letter) -> bool:
        pos = self.note.find(letter)
        if pos != -1:
            self.note = self.note[:pos] + self.note[pos+1:]
            return True
        else:
            return False

    def canBeConstructed(self) -> bool:
        for letter in self.mags:
            if len(self.note) == 0:
                return True
            else:
                if(not self.isInRansom(letter)):
                    self.mags = self.mags.replace(letter, '')

        return False