📌  相关文章
📜  Python - 不同的正整数总和为 K

📅  最后修改于: 2022-05-13 01:55:42.036000             🧑  作者: Mango

Python - 不同的正整数总和为 K

给定一个总和 K,然后提取达到总和的不同正数。

方法#1:使用循环

在此,我们取可以达到 K 的最小可能值,对于最后一个值,我们从求和值中减去 K 中的剩余值,直到该点。

Python3
# Python3 code to demonstrate working of
# Distinct Positive Integers Sum to K
# Using loop
  
# initializing K
K = 19
  
# printing K
print("The value of K : " + str(K))
  
res = []
idx = 0
for ele in range(1, K):
    idx += ele
      
    # checking for last element point 
    if K - idx < ele + 1:
          
        # appending initial elements
        res.extend(list(range(1, ele)))
          
        # appending last element left
        res.append(K - idx + ele)
        break
  
# printing result 
print("The Required elements : " + str(res))


Python3
# Python3 code to demonstrate working of
# Distinct Positive Integers Sum to K
# Using combinations() + sum()
from itertools import combinations
  
# initializing K
K = 19
  
# printing K
print("The value of K : " + str(K))
  
res = []
flag = 0
for idx in range(K - 1, 0, -1):
      
    # forming combinations
    for sub in combinations(range(1, K), idx):
        if sum(sub) == K and flag == 0:
            res.extend(list(sub))
            flag = 1
            break
        else:
            continue
        break
  
# printing result
print("The Required elements : " + str(res))


输出
The value of K : 19
The Required elements : [1, 2, 3, 4, 9]

方法#2:使用组合() + sum()

在这种情况下,我们使用组合()获取元素,并使用求和检查总和,这不会以贪婪而是随机的方式执行以获得所需的总和。

蟒蛇3

# Python3 code to demonstrate working of
# Distinct Positive Integers Sum to K
# Using combinations() + sum()
from itertools import combinations
  
# initializing K
K = 19
  
# printing K
print("The value of K : " + str(K))
  
res = []
flag = 0
for idx in range(K - 1, 0, -1):
      
    # forming combinations
    for sub in combinations(range(1, K), idx):
        if sum(sub) == K and flag == 0:
            res.extend(list(sub))
            flag = 1
            break
        else:
            continue
        break
  
# printing result
print("The Required elements : " + str(res))
输出
The value of K : 19
The Required elements : [1, 2, 3, 4, 9]