Check if given integer has only 1s and 0s in it and not another number without loops or functions

Viewed 47

Example:

  • num_1 = 1010
  • num_2 = 1234
  • num_3 = 1034

Here num_1 is the only valid number since it has both 1s and 0s.

num_2 is invalid because it does not have any 1s or 0s.

num_3 should also be invalid since it has digits other than 0s and 1s which are 2 and 4.

Note: you cannot use any for loops or while loop or any python function or method or string methods or built-in python methods all you can use are if elif and else.

All I can use are Conditional statements if, if-else and if-elif-else Simple variable assignment ,Binary operators like and, or and not. I am not supposed to use Any Python method or function. Any Python loop structure. Any list, array, set, or dictionary object.

How can we solve this to find the number which has only 1s and 0s in it?

The given integer can be in between the range 0 and 10000.

2 Answers

Given the significant set of restrictions:

if num == 0: return True
elif num == 1: return True
elif num == 10: return True
elif num == 11: return True
elif num == 100: return True
elif num == 101: return True
elif num == 110: return True
elif num == 111: return True
elif num == 1000: return True
elif num == 1001: return True
elif num == 1010: return True
elif num == 1011: return True
elif num == 1100: return True
elif num == 1101: return True
elif num == 1110: return True
elif num == 1111: return True
elif num == 10000: return True
else: return False

Because the number has a range, you can inline the while loop:

def only_one_or_zero(num):
    if num == 0: return True
    last = num % 10
    if last != 0 and last != 1: return False
    num //= 10
    if num == 0: return True
    last = num % 10
    if last != 0 and last != 1: return False
    num //= 10
    if num == 0: return True
    last = num % 10
    if last != 0 and last != 1: return False
    num //= 10
    if num == 0: return True
    last = num % 10
    if last != 0 and last != 1: return False
    num //= 10
    if num == 0: return True
    last = num % 10
    return last == 0 or last == 1

Test:

>>> all(only_one_or_zero(i) == ({'0', '1'} >= set(str(i))) for i in range(100001))
True
Related