Writting a function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fernando T

    Writting a function

    How would i write a function that prints all numbers in the range a to b(inclusive) that have all digits belonging to the set (1,3,4,8,9). The function takes two integer arguments:A and B...


    I understood the question and i have seen an example with the (dictionary.txt ), but it was to check vowels in words. So for this one i don't know how i would check for those numbers in the range which the user wishes....Lets say from 10000 to 1,000,000
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The first hurdle is to convert the number to a list of the individual digits and create a set object from the list. Then you can do set1.issubset(s 0) to determine if all the digits are in the set (1,3,4,8,9). There are a couple of ways to do this off the top of my head. This is probably the easiest:
    Code:
    >>> n = 1234567890
    >>> list(str(n))
    ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    >>> map(int, list(str(n)))
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    >>> [int(i) for i in list(str(n))]
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    >>> set([int(i) for i in list(str(n))])
    The other way is a loop using divmod():
    Code:
    def numtodigits(n):
        output = []
        while True:
            a,b = divmod(n, 10)
            output.insert(0, b)
            n = a
            if not a: return output
    '''
    >>> numtodigits(1230)
    [1, 2, 3, 0]
    >>> 
    '''

    Comment

    Working...