在Python中查找独眼巨人数

2024-05-20 09:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在解决一个问题,在检查一个数字是否是独眼巨人的数字后,我需要返回True或False。一个独眼巨人数字由奇数个数字组成,只有10个,零位于中间。以下是我目前掌握的情况:

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 

我如何找到中位数(不使用numpy)&;确保它是零,并且它是该数字中唯一存在的零


Tags: infalsetrueforreturnisdef情况
2条回答

这对我很有用:

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)
)

输出:

True True False False

看来你在这里做了很好的尝试,我会帮你的

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 

相关问题 更多 >