How to check if all the digits of a number are odd in python?

前端 未结 4 910
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 17:41

I was told to solve a problem in which I would have to find out the number of 4-digit numbers which are all composed of odd digits. I tried the following python code:

         


        
相关标签:
4条回答
  • 2021-01-26 18:23

    You could try something like this

    def isAllOdd(num):
      if num < 10: return num % 2 == 1;
      return isAllOdd(num % 10) and isAllOdd(int(num / 10))
    
    0 讨论(0)
  • 2021-01-26 18:28

    I believe something like this would work if you're looking to model what you already have, but I echo the comment by yotommy that some intuitive multiplication would do the trick.

     for a in range(1111,10000):
           allOdd = True
           for b in str(a):
               if int(b) % 2 == 0:
                   allOdd = False
           if(allOdd):
              new_list.append(a)
    
    0 讨论(0)
  • 2021-01-26 18:32
    for i in range(1000,3001):
      s=str(i)
      if (int(s[0])%2==0 and int(s[1])%2==0 and int(s[2])%2==0 and int(s[3])%2==0):
          print(i,end=",")
    
    0 讨论(0)
  • 2021-01-26 18:40

    A 4 digit number that is composed only of odd digits can only use the digits 1, 3, 5, 7 and 9. That gives you 5 to the power 4 is 625 different numbers. That didn't require trying them all out.

    You can still do that of course, using itertools.product() for example:

    from itertools import product
    
    print sum(1 for combo in product('13579', repeat=4))
    

    because product('13579', repeat=4) will produce all possible combinations of 4 characters from the string of odd digits.

    Your code needs to test if all digits are odd; break out early if any digit is not odd:

    new_list =[] # A list which holds the numbers
    for a in range(1111,10000):
        for b in str(a):
            if int(b) % 2 == 0:
                break
        else:
            # only executed if the loop wasn't broken out of
            new_list.append(a)
    

    You could use the all() function with a generator expression for that test too:

    new_list = []
    for a in range(1111,10000):
        if all(int(b) % 2 == 1 for b in str(a)):
            new_list.append(a)
    

    which then can be collapsed into a list comprehension:

    new_list = [a for a in range(1111,10000) if all(int(b) % 2 == 1 for b in str(a))]
    
    0 讨论(0)
提交回复
热议问题