Python Program to get K length groups with given summation

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

When it is required to get ‘K’ length groups with a given summation, an empty list, the ‘product’ method, the ‘sum’ method and the ‘append’ method can be used.

Example

Below is a demonstration of the same

from itertools import product

my_list = [45, 32, 67, 11, 88, 90, 87, 33, 45, 32]
print("The list is : ")
print(my_list)

N = 77
print("The value of N is ")
print(N)
K = 2
print("The value of K is ")
print(K)

my_result = []
for sub in product(my_list, repeat = K):
if sum(sub) == N:
my_result.append(sub)

print("The result is : " )
print(my_result)

Output

The list is :
[45, 32, 67, 11, 88, 90, 87, 33, 45, 32]
The value of N is
77
The value of K is
2
The result is :
[(45, 32), (45, 32), (32, 45), (32, 45), (45, 32), (45, 32), (32, 45), (32, 45)]

Explanation

• The required packages are imported into the environment.

• A list is defined and is displayed on the console.

• A value for N and K is defined and is displayed on the console.

• An empty list is defined.

• The product of elements in the list is determined, and it is checked to see if it is equivalent to N.

• If yes, this is appended to the empty list.

• This is displayed as output on the console.

Updated on 21-Sep-2021 08:16:34