
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program to get K length groups with given summation
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.
- Related Articles
- Python program to omit K length Rows
- Program to get maximum length merge of two given strings in Python
- Program to reverse linked list by groups of size k in Python
- Python program to remove K length words in String
- Program to find maximum number of K-sized groups with distinct type items are possible in Python
- Program to group a set of points into k different groups in Python
- Program to find array of length k from given array whose unfairness is minimum in python
- Get the trace of a matrix with Einstein summation convention in Python
- Python program to reverse an array in groups of given size?
- Python Program to Group Strings by K length Using Suffix
- Program to find maximum length of k ribbons of same length in Python
- Program to find length of longest sublist with given condition in Python
- Python Program to Get K initial powers of N
- Python program to find ways to get n rupees with given coins
- Program to count k length substring that occurs more than once in the given string in Python

Advertisements