St Tebb
St Tebb

Reputation: 69

Logic error - checking if one word can be formed from another

Code works in most cases, but gives wrong answer when a word with more than one character that is the same...

first = input('Enter first word: ')

second = input('Enter second word: ')

isIn = 0

for i in first:
    for j in second:
        if i == j:
            isIn += 1
            break


if isIn == len(first):
    print('Word one can be formed from word two')

else:
    print('Word one can\'t be formed from word two')

Upvotes: 0

Views: 328

Answers (4)

Funpy97
Funpy97

Reputation: 337

def formed_by(w1, w2):
    return bool(sorted(w1)==sorted(w2))

It returns True if w1 is formed by w2 and vice versa, else it returns False.

Upvotes: 0

Paul M.
Paul M.

Reputation: 10809

The e in meat is getting counted twice.

from collections import Counter

first_word = "meet"
second_word = "meat"

first_counter = Counter(first_word)
second_counter = Counter(second_word)

for key, value in first_counter.items():
    if second_counter[key] != value:
        print(f"You cannot construct \"{first_word}\" from \"{second_word}\"")
        break
else:
    print(f"You can construct \"{first_word}\" from \"{second_word}\"")

Upvotes: 1

PYB
PYB

Reputation: 533

You are checking if each letter in first can be found in second. The problem is that if there is at least 1 letter in second, no matter how many of that letter is found in first, isIn will always be incremented. You need find a way to keep count of how many of one letters is found in both variables and develop a logic around that.

There are multiple approaches possible, you may look into COUNT() and SORTED() among other functions.

Upvotes: 0

AlecBrooks
AlecBrooks

Reputation: 520

A simple way to check if two words are anagrams of each other is to sort the strings first, so that they will be the same if they contain the same letters. This will handle the case that you've encountered where one word contains multiple letters that is required in the second or visa versa.

sorted(first) == sorted(second)

Upvotes: 2

Related Questions