Reputation: 33
This is from an interview that I had to recreate the Wallstreet spelling bee puzzle. Each puzzle consists of seven distinct letters, (first one being a key letter) come up with as many words as possible obeying the following rules.
EXAMPLE
input:
Explanation
So I had 75 min to solve it and I got pretty far but wasn't able to figure out a critical step. Where I couldn't get the score to show up properly and I could only manually sort through the word list. I tried adding some counters but couldn't get them working.
test_list = ["apple","pleas","please"]
puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]
puzzles_list = ["a","e","l","p","s","x","y"]
def check_words(letters,words):
i = 1
score = 0
letters = list(letters)
for word in words:
if all(x in set(letters) for x in word) and letters[0] in word:
#this checks if the word contains any letter from the word and the first letter(aka key letter)
print("test passed")
score +=1
print(word,letters,i)
print(score)
return
#here we have to add a value to a counter to show for that set of letters how many words it can spell.
if all(x in set(word) for x in letters):
#only if the puzzle and the word match exactly aka apple would have to only have a,p,l,e in the test
print(word,letters)
else:
return
else:
print("no matching letters and or not matching key letter.")
return
def spelling_bee_solutions(wordlist,puzzles):
for puzzle in puzzles:
puzzle = list(puzzle)
check_words(puzzle,wordlist)
# check_words(puzzles_list,test_list)
spelling_bee_solutions(test_list,puzzles)
I wanted to add the score to a dict or appended to a list but i ran out of time. I mostly just want to see what the real solution would be.
so far it just prints
no matching letters and or not matching key letter.
test passed
apple ['a', 'e', 'l', 'p', 'x', 'y', 'z'] 1
1
test passed
apple ['a', 'e', 'l', 'p', 's', 'x', 'y'] 1
1
no matching letters and or not matching key letter.
no matching letters and or not matching key letter.
Upvotes: 3
Views: 61
Reputation: 106553
You can use a list comprehension to map each puzzle to a sum of a generator expression that iterates over the word list and outputs 1 if the set of characters in the puzzle is a superset of the set of the characters in the word, and that the first character in the puzzle is in the word:
[sum(set(p) >= set(w) and p[0] in w for w in wordlist) for p in puzzles]
This returns:
[0, 1, 3, 2, 0]
You can further optimize it by converting the list of words to a list of sets of characters first, so that the set conversion does not have to be done per iteration:
wordsets = list(map(set, wordlist))
[sum(w.issubset(p) and p[0] in w for w in wordsets) for p in puzzles]
Upvotes: 1