-1

Complete 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'.

Note that the words will always be in lower case!

You 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 A[i]==int:
            return A[i]
        elif A[i]==str:
            return int(A[i])

And its not working. ! can anyone help with the code!

Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
  • 1
    Why does it supposed to work? What output are you expecting to get from `int('forty-seven')`? Common way to check if variable belongs to some type is to call function [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance), also you can get type from variable instance using [`type()`](https://docs.python.org/3/library/functions.html#type). – Olvin Roght Jan 23 '22 at 18:21
  • `==` is used to check for equality between two things. `A[i]` will never be equal to `int` or to `str`. Instead of `A[i]==int`, use either `isinstance(A[i], int)` or `type(A[i]) == int`. – Stef Jan 23 '22 at 19:19

2 Answers2

1

Due to this seemingly being a homework question I'll try to avoid giving you a full answer, and try to aim you in the right direction.

If we take a look at the given problem, we can see we have 3 input cases:

  1. An Integer
  2. A String of digits
  3. A String of letters representing a number

You've already tried to solve parts 1/2 but you haven't done the 3rd case yet. This one is especially tricky.

One way of solving this would be to generate the strings representing all the numbers from 1-99 ("one", "two"... "ninety-nine") and put them as the keys in a dictionary, with the values being the integer value they represent.

The names of numbers 1-19 must be each manually typed due to english being weird, but there are repeating patterns from 20-99, see if you can figure out what these patterns are and if you can create the strings for those numbers from them.

Once you have this dictionary of strings and integers, you can simply check if an input exists within the dictionary, then grab the value from the dictionary.

Ewan Brown
  • 640
  • 3
  • 12
0

Your code doesn't distinguish between the two types of string representations of numbers (the second and third types listed in the problem description). Trying to convert elements like twelve or forty-two via Python's int built-in function isn't going to work. For a suggestion for handling such elements, see here.

atrocia6
  • 319
  • 1
  • 8