我想创建一个接受输入的函数(可以是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,29,9)---输出:False,"至少1个整数不自恋"
输入:(" 4")---输出:True,"数字作为字符串是好的")
输入:("单词")---输出:False,"不是数字的字符串不正常")
那么我应该添加什么以便该函数也可以接受这些输入?
例如153的自恋数字。 因为当你将每个数字分开并将其取为数字长度(在这种情况下为3)时,你就得到了数字。
1 ^ 3 + 5 ^ 3 + 3 ^ 3 = 153
答案 0 :(得分:3)
您需要做的就是检查这些特殊情况:
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