如何让我的函数接受不同类型的输入?

史蒂夫

我想创建一个函数,它接受一个输入(可以是 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

接受不同类型的JSON数组输入?

如何动态接受不同类类型的RequestBody

如何使函数接受指向不同类的指针?

如何在同一函数中接受不同类型的切片?

在PostgreSQL中,如何声明一个接受不同类型参数的可变参数函数?

使tqdm等函数在Python中接受不同类型的参数

我应该向对象声明什么类型,以使其接受来自不同类的不同构造函数

Matlab函数具有许多不同类型的输入

我如何更改以下界面以接受不同类型的邮件系统的参数。任何设计模式?

我如何使用FirebaseCloud sendNotification函数发送不同类型的Notificaton

我如何编写单个函数以与不同类型一起使用

如何在java中处理不同类型的输入

如何对不同类型的输入使用相同的功能?

如何从不同的行添加相同类型的输入值?

如何处理不同类型的算法输入?

函数返回不同类型

TypeScript Map类构造函数,其初始值不接受2种不同类型

Coq 构造函数不能接受两个不同类型的参数?

如何实现接收不同类型scala的通用函数

如何正确调用不同类型的函数 addEventListeners

如何编写处理不同类型列表的函数

如何在不同类型的函数上推广Rust宏?

Delphi-如何从函数返回不同类型

如何概括作用于不同类型向量的函数?

如何专门设计用于返回不同类型的模板函数?

如何使函数返回不同类型的两列(R)?

我如何在Fullcalendar中进行不同类型的事件?

一个 JavaScript 函数可以处理不同类型的 HTML 输入类型吗?

从cin读取不同类型的输入