[SOLVED] Alphabet Soup -Determine if you can write your message with the letters found in your bowl of soup

Issue

I have been given a task to solve in python, need a help as I am not able to get an output, below is the question: –

Everyone loves alphabet soup. And of course, you want to know if you can construct a message from the letters found in your bowl.

Your Task:

Write a function that takes as input two strings:

  1. The message you want to write
  2. All the letters found in your bowl of alphabet soup

Assumptions:

  • It may be a very large bowl of soup containing many letters
  • There is no guarantee that each letter occurs a similar number of times – indeed some letters might be missing entirely
  • The letters are ordered randomly

The function should determine if you can write your message with the letters found in your bowl of soup. The function should return True or False accordingly.

Try to make your function efficient. Please use Big-O notation to explain how long it takes your function to run in terms of the length of your message (m) and the number of letters in your bowl of soup (s).

Below is the code I have tried but it is not working as per the task:-

def sol(alpha):
    srt = sorted(list(alpha))
    lwcase = sorted(list(alpha.lower()))
    upcase = []
    result = ''
    for i in srt:
        if i.isupper():
            upcase.append(i)

    for e in lwcase:
        if upcase.count(e.upper()) != 0:
            result += e.upper()
            upcase.pop(upcase.index(e.upper()))
        else:
            result += e
    return result

it = input("Enter a word please")
print(sol(it))

Solution

Here’s my solution (see comment):

def validate_soup(s: str, chars: str)-> bool:
    d = {}
    for c in chars:
        count = d.get(c, 0)
        d[c] = count + 1
    for c in s:
        count = d.get(c, 0)
        if count <= 0:
            return False
        d[c] = count - 1
    return True

Answered By – William Bradley

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.