By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,767 Members | 1,987 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,767 IT Pros & Developers. It's quick & easy.

Writting a function

P: n/a
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
Oct 14 '10 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
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(s0) 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:
Expand|Select|Wrap|Line Numbers
  1. >>> n = 1234567890
  2. >>> list(str(n))
  3. ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
  4. >>> map(int, list(str(n)))
  5. [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
  6. >>> [int(i) for i in list(str(n))]
  7. [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
  8. >>> set([int(i) for i in list(str(n))])
The other way is a loop using divmod():
Expand|Select|Wrap|Line Numbers
  1. def numtodigits(n):
  2.     output = []
  3.     while True:
  4.         a,b = divmod(n, 10)
  5.         output.insert(0, b)
  6.         n = a
  7.         if not a: return output
  8. '''
  9. >>> numtodigits(1230)
  10. [1, 2, 3, 0]
  11. >>> 
  12. '''
Oct 14 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.