Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.
Trending now
This is a popular solution!
Step by step
Solved in 5 steps with 5 images
Is it possible to do it with this Method
def canConstruct(ransomNote: str, magazine: str) -> bool:
if len(ransomNote) > len(magazine):
return False
magazinedict = dict()
for letter in magazine:
if letter not in magazinedict:
magazinedict[letter] = 1
else:
magazinedict[letter] += 1
for letter in ransomNote:
if letter not in magazinedict:
return False
if letter in magazinedict and magazinedict[letter] <= 0:
return False
magazinedict[letter] -= 1
return True
with open('lab1_input.txt') as text:
for line in text.readlines():
strings = list(map(str,line.split()))
print(strings, end="\t")
ransomNote = strings[0]
magazine = strings[1]
output = canConstruct(ransomNote,magazine)
print('-\t'+str(output))
outfile = open('lab1_output.txt', 'a')
outfile.write(str(output)+'\n')
outfile.close()