0

I'm trying to do something like scrabble solver.

letters = ['s','w','r','a']
line_of_dic= ['s','w','r','a','a']


# printing original lists
print("Original list : " + str(line_of_dic))
print("Original sub list : " + str(letters))

# using all() to
# check subset of list
flag = 0
if (all(x in line_of_dic for x in letters)):
    flag = 1

# printing result
if (flag):
    print("Yes, the word can be created")
else:
    print("No, the word cant be.")

This is the part of code that I'm unable to repair, word can't be created, but it prints yes. Is it possible to check if all the letters are in line_of_dic, but if elements are doubled or tripled to check this? Also, is it possible to do without fancy libraries?

martineau
  • 119,623
  • 25
  • 170
  • 301
seur30
  • 11
  • 3

3 Answers3

1

You can use dictionary structure. To create dictionary from list you can write a simple code:

letterDict = {}
lineDict = {}

for item in letters:
    if item not in letterDict:
        letterDict[item] = 1
    else:
        letterDict[item] += 1
        
for item in line_of_dic:
    if item not in lineDict:
        lineDict[item] = 1
    else:
        lineDict[item] += 1

After that point, you can simply compare two dictionary:

if letterDict == lineDict:
    print("Yes, the word can be created")
else:
    print("No, the word cant be.")
Angerato
  • 156
  • 5
0

You need to count the number of each character in each word and then compare the values. You can do this with a dictionary.

ltrs = {}
lod = {}

for char in letters:
    ltrs[char] = ltrs.get(char,0) + 1

for char in line_of_dic:
    lod[char] = lod.get(char,0) + 1

Then you can see if there are enough of each character to make the word.

In [3]: ltrs
Out[3]: {'a': 1, 'r': 1, 's': 1, 'w': 1}

In [4]: lod
Out[4]: {'a': 2, 'r': 1, 's': 1, 'w': 1}

collections.Counter can make those dictionaries for you.

import collections
ltrs = collections.Counter(letters)
lod = collections.Counter(line_of_dic)

In [6]: ltrs
Out[6]: Counter({'a': 1, 'r': 1, 's': 1, 'w': 1})

In [7]: lod
Out[7]: Counter({'a': 2, 'r': 1, 's': 1, 'w': 1})

Subtracting the Counters you can see if there are enough.

In [31]: lod-ltrs
Out[31]: Counter({'a': 1})

lod has one more 'a' than ltrs.

wwii
  • 23,232
  • 7
  • 37
  • 77
0

This can be done on one line by comparing the count of each letter:

flag = 0
if all(line_of_dic.count(char) == letters.count(char) for char in line_of_dic):
    flag = 1

Rather than checking if the letter is present, this checks if the count matches.

Random Davis
  • 6,662
  • 4
  • 14
  • 24