Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to make word1 from the letters of word2 in Python

word1 = input() 
word2 = input()
a = len(word2)
b = len(word1)
count = b
while (word2[a-1] == word1[b-1]):
    count-=1
    a -= 1
    if count == 0:
        break
    else:
        print('it cant be made')
b-=1
print('it can be made')  

What I am trying to do is compare the last letter of word2 to the last letter of word 1 and if they are equal, – the count by 1 and move down a letter in word 2 until the count is == to 0 therefore suggesting the word can be made.
if the 2 letters aren’t equal it should just move onto the next letter of word1 and repeat the process. if the the count doesn’t reach 0 then the word can’t be made because it is the Len of the word you are trying to make.

This is what happens when I run the code:

bru
kinn
it can be made
>>> 
= RESTART: /Users/nicksuciu/Documents/python work/section b make word from word2.py
bru
kibun
it can be made
>>> 
= RESTART: /Users/nicksuciu/Documents/python work/section b make word from word2.py
bru
kibun
it can be made
>>> 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In all of your test cases, the while loop immediately exits because the last letters aren’t equal. The way your code is written, the result after finishing the while is to print "it can be made" before exiting, regardless of what happened inside the loop, so you will always get that output.

Solving this problem by doing a single iteration through both words together is difficult because presumably the letters might be in different orders; you’re likely to "miss" a letter in many cases. The simpler solution is to use dicts to count up the letters in each word and then compare the counts. Here’s an example using collections.Counter:

from collections import Counter

word1 = Counter(input())
word2 = Counter(input())
if all(word2[char] >= word1[char] for char in word1):
    print('it can be made')
else:
    print('it cant be made')
>python test.py
bru
kibun
it cant be made

>python test.py
bru
kribun
it can be made
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading