我想创建一个函数,它接受一个输入(可以是 int、数组或字符串的形式)并返回它是否是一个自恋数字。
到目前为止,我创建了一个可以接收整数的函数,如果自恋则返回 True,否则返回 False。
def is_narcissistic(num):
total = []
number = len(str(num)) #Find the length of the value
power = int(number) #convert the length back to integer datatype
digits = [int(x) for x in str(num)] #convert value to string and loop through, convert back to int and store in digits
for i in digits:
product = i**power # iterate through the number and take each i to the power of the length of int
total.append(product) # append the result to the list total
totalsum = sum(total)
if totalsum == num:
print (True)
else:
print(False)
print(is_narcissistic(153))
然而,问题是这应该适用于任何类型的输入,如字符串或列表。例如:
输入:(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) --- 输出:真,“所有1位正整数都是自恋的”
输入:(0, 1, 2, 3, 4, 5, 6, 7, 22, 9) ---输出:假,“至少有1个整数不是自恋的”
输入:(“4”)---输出:真,“数字作为字符串是可以的”)
input: ("words") --- output: False, "不是数字的字符串不行")
那么我应该添加什么以便函数也可以接受这些输入?
一个自恋的数字,例如 153。因为当你把每个数字分开并把它取到数字长度(在这种情况下是 3)的幂时,你会得到数字本身。
1^3 + 5^3 + 3^3 = 153
您所要做的就是检查这些特殊情况:
def is_narcissistic(num):
if isinstance(num, str): # is is a string?
if num.isdigit(): # does is consist purely out of numbers?
num = int(num)
else:
return False
if isinstance(num, (tuple,list)):
return all(is_narcissistic(v) for v in num)
# the rest of your code
此外,您必须更改函数的结尾。您不应该打印,而是稍后返回使用该值:
if totalsum == num:
return True
else:
return False
如果您希望能够在没有元组提取括号的情况下调用它,您可以使用:
def is_narcissistic(*args):
if len(args) == 1:
num = args[0]
else:
num = args
# The code from above
现在你可以这样称呼它:
print(is_narcissistic(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) # True
print(is_narcissistic(0, 1, 2, 3, 4, 5, 6, 7, 22, 9)) # False
print(is_narcissistic(0, 1, "2", 3, "4", 5, 6, 7, "22", 9)) #False
完整的代码在这里:
def is_narcissistic(*args):
if len(args) == 1:
num = args[0]
else:
num = args
if isinstance(num, str):
if num.isdigit():
num = int(num)
else:
return False
if isinstance(num, (tuple, list)):
return all(is_narcissistic(v) for v in num)
total = []
number = len(str(num)) # Find the length of the value
power = int(number) # convert the length back to integer datatype
digits = [int(x) for x in str(num)] # convert value to string and loop through, convert back to int and store in digits
for i in digits:
product = i ** power # iterate through the number and take each i to the power of the length of int
total.append(product) # append the result to the list total
totalsum = sum(total)
if totalsum == num:
return True
else:
return False
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句