Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何求一个数的所有除数之和,而不包括它_Python_Python 3.x - Fatal编程技术网

Python 如何求一个数的所有除数之和,而不包括它

Python 如何求一个数的所有除数之和,而不包括它,python,python-3.x,Python,Python 3.x,我写了一个函数,它只返回一个数的所有除数的列表 print(func(6)) # Should be 1+2+3=6 print(func(12)) # Should be 1+2+3+4+6=16 所以我不确定这正是你想要的。但是您可以在python中使用sum()获得列表的和,因此您的函数如下所示 def func(num): add=[] for i in range(1,num-1): if num%i==0: add.appen

我写了一个函数,它只返回一个数的所有除数的列表

print(func(6)) # Should be 1+2+3=6
print(func(12)) # Should be 1+2+3+4+6=16

所以我不确定这正是你想要的。但是您可以在python中使用sum()获得列表的和,因此您的函数如下所示

def func(num):
    add=[]
    for i in range(1,num-1):
        if num%i==0:
            add.append(i)
    print(add)
这将返回正确的输出,其中包含

def func(num):
    add=[]
    for i in range(1,num-1):
        if num%i==0:
            add.append(i)
    return sum(add)
它也可以这样写为一个列表

print(func(6)) # Should be 1+2+3=6
print(func(12)) # Should be 1+2+3+4+6=16

您可以这样做:

def func(num):
    add = []
    total_sum = 0
    for i in range(1, num - 1):
        if num % i == 0:
            add.append(str(i))
            total_sum += i

    return "{}={}".format("+".join(add), total_sum)
该守则规定:

def func(num):
    add = [i for i in range(1, num-1) if num % i == 0]
    return sum(add)

返回除数之和:

print(func(6))  # Should be 1+2+3=6
print(func(12)) # Should be 1+2+3+4+6=16
def和除数(n):
总和=0
x=1
而n!=0和x
我不确定我是否理解你的要求。我需要编写一个函数func,使输出打印(func(6))#应该打印出1+2+3=6我不需要计算一些除数,我只需要打印它。func(6)的输出将是1+2+3=6@AnnaTum那么您希望输出为字符串吗?是的,它应该类似于stringTypeError:序列项0:预期的str实例,int found
print(func(6))  # Should be 1+2+3=6
print(func(12)) # Should be 1+2+3+4+6=16
def sum_divisors(n):
  sum = 0
  x = 1
  while n != 0 and x < n :
      
    if n % x == 0  :
      sum += x
    else:
      sum += 0
    x += 1    
  
  return sum