Function to take input as string, input parameter to function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • David Aghan
    New Member
    • Aug 2010
    • 2

    Function to take input as string, input parameter to function

    Ok, so I am almost done with this question:
    Write and test a function to take as input a list of strings (each of which
    represents a number) and to return a list of numeric values. For example, if
    the input to the function is [“67”, “8”,”75”] and return [67,8,75]. The input
    should be as a parameter to the function.


    here is the code I have written:
    Code:
    def func( num1, *numtuple):
        print num1
        for num in numtuple:
            print num
    it works fine except for the fact that the input HAS to be as a string. Any help would be great because I am stumped.

    Cheers
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The instructions require the function argument to be a list of strings as in
    Code:
    ['1','2','3']
    This can be done two ways.
    Code:
    def f(*args):
        # Accept a variable number of arguments
        pass
    
    def f(strList):
        # Accept a single argument
        pass
    Your function must return a list of numbers. This can be done several ways, but you must use the return statement as in
    Code:
    def f(*args):
        # Calculate somevalue
        return somevalue
    Assuming the numbers are all integers, here are some examples:
    Code:
    >>> strList = ['1','2','3']
    >>> map(int, strList)
    [1, 2, 3]
    >>> [int(n) for n in strList]
    [1, 2, 3]
    >>> result = []
    >>> for n in strList:
    ... 	result.append(int(n))
    ... 	
    >>> result
    [1, 2, 3]
    >>>
    HTH

    Comment

    Working...