2

The given method called solve which takes as parameter a list A.

This list contains the following types of values:

integers (between 1 and 99, both inclusive)

numbers in form of strings (between 1 and 99, both inclusive) eg, '37', '91'

word form of numbers (between 1 and 99, both inclusive) eg, 'twenty', 'seventeen', 'forty-two'.

plz Note that the words will always be in lower case!

have to generate a list with all the values in integer form and return it. The list must be in ascending sorted order.

Example

Input:

[1, 3, '4', '1', 'three', 'eleven', 'forty-seven', '3']

Output:

[1, 3, 4, 11, 47]

Code:

def solve(A):
    for i in A:
        if type(A[i])==int:
            return A.extend(A[i])
        elif type(A[i])==str:
            return int(A[i])

we even need to use sets to remove the duplicates And its not working. ! can anyone help with the code!

meera jain
  • 23
  • 3

1 Answers1

4

Here's how to do it below I explain with code comments.

def solve(lst):
    # Dictionary of words to numbers
    NUMBERS_DIC = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90}
    
    # list to be returned 
    retLst = []
    for num in lst:
        # if num is an int
        if type(num)==int: # type() tells you the type of the variable
            retLst.append(num)
        # if num is a string that is numeric
        elif num.isnumeric():
            retLst.append(int(num)) # Turn to int
        # if num is a string word such as forty-seven"
        else:
            # turns "forty-seven" -> ["forty","seven"]
            word_values_lst = num.split("-")
            val = 0
            for word in word_values_lst:
                val+=NUMBERS_DIC[word] # Get value from NUMBERS_DIC
            retLst.append(val) 
            
                
    
    # Sort lst
    retLst.sort() 
    
    
    return list(set(retLst)) # removes duplicates


lst = [1, 3, '4', '1', 'three', 'eleven', 'forty-seven', '3']
retLst = solve(lst)

print(retLst)


carlosdafield
  • 1,479
  • 5
  • 16
  • If I helped you out. Can you help me out by accepting the answer by pressing the green check mark next to the question. Yeah and have nice day – carlosdafield Jan 24 '22 at 05:13
  • Instead of `retLst.sort(); return list(set(retLst))`, you should use `return sorted(set(retLst))`. Sorting before converting to `set` is not guaranteed to work. Because `set` isn't guaranteed to retain order. – Stef Jan 24 '22 at 11:19