Finding Cyclops Numbers in Python

Viewed 387

I am working on a problem in which I need to return True or False after checking to see whether a number is a cyclops number or not. A cyclops number is made up of odd number of digits, consists of only one zero and that zero is located in the middle. Here's what I have so far:

def is_cyclops(n):
  strNum = str(n)
  for i, el in enumerate(strNum):
    if(len(strNum) % 2 == 0):
      return False
    else: 
      # find middle number is zero 
      # no other zeros exist 
      # return True 
is_cyclops(0) # True
is_cyclops(101) # True
is_cyclops(1056) # False
is_cyclops(675409820) # False 

How can I find the median number (without using numpy) & ensure it is a zero, and it is the only zero that exists in that number?

2 Answers

This worked for me:

def is_cyclops(num: int) -> bool:
    str_ = str(num)
    if not len(str_) % 2:
        return False
    if not str_.count('0') == 1:
        return False
    mid_index = len(str_) // 2
    if str_[mid_index] == '0':
        return True
    return False

print(
    is_cyclops(0),
    is_cyclops(101),
    is_cyclops(1056),
    is_cyclops(675409820)
)

Output:

True True False False

As it looks like you've had a good attempt here, I'll help out.

def is_cyclops(n):
    strNum = str(n)

    if(len(strNum) % 2 == 0):
      return False
    else:
      middle_index = len(strNum)//2
      if strNum[middle_index] != "0": return False # find middle number is zero 
      if strNum.count("0") > 1: return False # no other zeros exist 
      return True 
is_cyclops(0) # True
is_cyclops(101) # True
is_cyclops(1056) # False
is_cyclops(675409820) # False 
Related