Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python program to find all possible pairs with given sum
Next article icon

Python Program to get K length groups with given summation

Last Updated : 21 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list, our task is to write a Python program to extract all K length sublists with lead to given summation. 

Input : test_list = [6, 3, 12, 7, 4, 11], N = 21, K = 4

Output : [(6, 6, 6, 3), (6, 6, 3, 6), (6, 3, 6, 6), (6, 7, 4, 4), (6, 4, 7, 4), (6, 4, 4, 7), (3, 6, 6, 6), (3, 3, 3, 12), (3, 3, 12, 3), (3, 3, 4, 11), (3, 3, 11, 4), (3, 12, 3, 3), (3, 7, 7, 4), (3, 7, 4, 7), (3, 4, 3, 11), (3, 4, 7, 7), (3, 4, 11, 3), (3, 11, 3, 4), (3, 11, 4, 3), (12, 3, 3, 3), (7, 6, 4, 4), (7, 3, 7, 4), (7, 3, 4, 7), (7, 7, 3, 4), (7, 7, 4, 3), (7, 4, 6, 4), (7, 4, 3, 7), (7, 4, 7, 3), (7, 4, 4, 6), (4, 6, 7, 4), (4, 6, 4, 7), (4, 3, 3, 11), (4, 3, 7, 7), (4, 3, 11, 3), (4, 7, 6, 4), (4, 7, 3, 7), (4, 7, 7, 3), (4, 7, 4, 6), (4, 4, 6, 7), (4, 4, 7, 6), (4, 11, 3, 3), (11, 3, 3, 4), (11, 3, 4, 3), (11, 4, 3, 3)]

Explanation : All groups of length 4 and sum 21 are printed.

Input : test_list = [6, 3, 12, 7, 4, 11], N = 210, K = 4

Output : []

Explanation : Since no 4 size group sum equals 210, no group is printed as result.

Method : Using sum() + product() + loop 

In this all possible sublists of length K are computed using product(), sum() is used to compare the sublist's sum with the required summation. 

Python3
# Python3 code to demonstrate working of # K length groups with given summation # Using sum + product() from itertools import product  # initializing list test_list = [6, 3, 12, 7, 4, 11]               # printing original list print("The original list is : " + str(test_list))  # initializing Summation  N = 21  # initializing size  K = 4  # Looping for each product and comparing with required summation res = [] for sub in product(test_list, repeat = K):   if sum(sub) == N:     res.append(sub)          # printing result print("The sublists with of given size and sum : " + str(res)) 

Output:

The original list is : [6, 3, 12, 7, 4, 11]

The sublists with of given size and sum : [(6, 6, 6, 3), (6, 6, 3, 6), (6, 3, 6, 6), (6, 7, 4, 4), (6, 4, 7, 4), (6, 4, 4, 7), (3, 6, 6, 6), (3, 3, 3, 12), (3, 3, 12, 3), (3, 3, 4, 11), (3, 3, 11, 4), (3, 12, 3, 3), (3, 7, 7, 4), (3, 7, 4, 7), (3, 4, 3, 11), (3, 4, 7, 7), (3, 4, 11, 3), (3, 11, 3, 4), (3, 11, 4, 3), (12, 3, 3, 3), (7, 6, 4, 4), (7, 3, 7, 4), (7, 3, 4, 7), (7, 7, 3, 4), (7, 7, 4, 3), (7, 4, 6, 4), (7, 4, 3, 7), (7, 4, 7, 3), (7, 4, 4, 6), (4, 6, 7, 4), (4, 6, 4, 7), (4, 3, 3, 11), (4, 3, 7, 7), (4, 3, 11, 3), (4, 7, 6, 4), (4, 7, 3, 7), (4, 7, 7, 3), (4, 7, 4, 6), (4, 4, 6, 7), (4, 4, 7, 6), (4, 11, 3, 3), (11, 3, 3, 4), (11, 3, 4, 3), (11, 4, 3, 3)]

Time Complexity: O(n*n)
Auxiliary Space: O(n)

Approach#2: Using recursion: The approach uses backtracking to generate all possible groups of length K with sum N. It starts with an empty group and recursively tries to add numbers from the given list to form a group. If the group becomes of length K and its sum is N, it is added to the list of groups.

  1. Define a backtrack function that takes curr_group, remaining_sum, and remaining_len as parameters.
  2. Check if remaining_sum is equal to 0 and remaining_len is equal to 0. If yes, return the current group as a list of list.
  3. Check if remaining_sum is less than 0 or remaining_len is less than 0. If yes, return an empty list.
  4. Initialize an empty list of groups to store all possible groups.
  5. Loop through the given list test_list using the enumerate() function.
  6. Add the current number to the current group to form a new group and reduce the remaining_sum and remaining_len accordingly.
  7. Recursively call the backtrack function with the new group, new_sum, new_len, and remaining_list.
  8. Append the returned groups to the groups list.
  9. Return the final groups list.
Python3
# Python program for the above approach  # Function to get the K length groups def get_k_length_groups(test_list, N, K):     # Function to recursively find the states     def backtrack(curr_group, remaining_sum, remaining_len):         if remaining_sum == 0 and remaining_len == 0:             return [curr_group]         if remaining_sum < 0 or remaining_len < 0:             return []         groups = []          # Update the group and call recursively         for i, num in enumerate(test_list):             new_group = curr_group + [num]             new_sum = remaining_sum - num             new_len = remaining_len - 1             remaining_list = test_list[i:]             groups += backtrack(new_group, new_sum, new_len)          # Return the groups         return groups      # Backtrack the current state     groups = backtrack([], N, K)      # Return the resultant groups     return groups   # Driver Code test_list = [6, 3, 12, 7, 4, 11] N = 21 K = 4 print(get_k_length_groups(test_list, N, K)) 

Output
[[6, 6, 6, 3], [6, 6, 3, 6], [6, 3, 6, 6], [6, 7, 4, 4], [6, 4, 7, 4], [6, 4, 4, 7], [3, 6, 6, 6], [3, 3, 3, 12], [3, 3, 12, 3], [3, 3, 4, 11], [3, 3, 11, 4], [3, 12, 3, 3], [3, 7, 7, 4], [3, 7, 4, 7], [3, 4, 3, 11], [3, 4, 7, 7], [3, 4, 11, 3], [3, 11, 3, 4], [3, 11, 4, 3], [12, 3, 3, 3], [7, 6, 4, 4], [7, 3, 7, 4], [7, 3, 4, 7], [7, 7, 3, 4], [7, 7, 4, 3], [7, 4, 6, 4], [7, 4, 3, 7], [7, 4, 7, 3], [7, 4, 4, 6], [4, 6, 7, 4], [4, 6, 4, 7], [4, 3, 3, 11], [4, 3, 7, 7], [4, 3, 11, 3], [4, 7, 6, 4], [4, 7, 3, 7], [4, 7, 7, 3], [4, 7, 4, 6], [4, 4, 6, 7], [4, 4, 7, 6], [4, 11, 3, 3], [11, 3, 3, 4], [11, 3, 4, 3], [11, 4, 3, 3]]

Time Complexity: O(N^K), because we are generating all possible groups of length K with sum N, and each number in the list, can either be included or excluded in a group.

Space Complexity: O(K) because we are using the curr_group list to store the current group, and its length is at most K. Additionally, the recursion depth can go up to K, so the space complexity is O(K).


Next Article
Python program to find all possible pairs with given sum
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python Program to Group Strings by K length Using Suffix
    Given Strings List, the task is to write a Python program to group them into K-length suffixes. Input : test_list = ["food", "peak", "geek", "good", "weak", "sneek"], K = 3 Output : {'ood': ['food', 'good'], 'eak': ['peak', 'weak'], 'eek': ['geek', 'sneek']} Explanation : words ending with ood are f
    5 min read
  • Python program to find all possible pairs with given sum
    Given a list of integers and an integer variable K, write a Python program to find all pairs in the list with given sum K. Examples: Input : lst =[1, 5, 3, 7, 9] K = 12 Output : [(5, 7), (3, 9)] Input : lst = [2, 1, 5, 7, -1, 4] K = 6 Output : [(2, 4), (1, 5), (7, -1)] Method #1: Pythonic Naive This
    7 min read
  • Python program to find the group sum till each K in a list
    Given a List, the task is to write a Python program to perform grouping of sum till K occurs. Examples: Input : test_list = [2, 3, 5, 6, 2, 6, 8, 9, 4, 6, 1], K = 6 Output : [10, 6, 2, 6, 21, 6, 1] Explanation : 2 + 3 + 5 = 10, grouped and cumulated before 6. Input : test_list = [2, 3, 5, 6, 2, 6, 8
    3 min read
  • Python Program for Count pairs with given sum
    Given an array of integers, and a number 'sum', find the number of pairs of integers in the array whose sum is equal to 'sum'. Examples: Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : 3 Pairs with sum 6 are
    3 min read
  • Python3 Program to Find the subarray with least average
    Given an array arr[] of size n and integer k such that k <= n. Examples : Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3Output: Subarray between indexes 3 and 5The subarray {20, 10, 50} has the least average among all subarrays of size 3.Input: arr[] = {3, 7, 5, 20, -10, 0, 12}, k = 2Output: Su
    3 min read
  • Python - Pairs with Sum equal to K in tuple list
    Sometimes, while working with data, we can have a problem in which we need to find the sum of pairs of tuple list. And specifically the sum that is equal to K. This kind of problem can be important in web development and competitive programming. Lets discuss certain ways in which this task can be pe
    6 min read
  • Python - Extract Dictionary Items with Summation Greater than K
    Given dictionary with value lists, extract all those items with values summing over K. Input : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3], "geeks" : [1, 2, 3, 4]}, K = 10 Output : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3],
    5 min read
  • Python program to get all subsets of given size of a Set
    We are given a set, and our task is to get all subsets of a given size. For example, if we have s = {1, 2, 3, 4} and need to find subsets of size k = 2, the output should be [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]. Using itertools.combinationsWe can use itertools.combinations(iterable, r) t
    3 min read
  • Python | Grouped summation of tuple list
    Many times, we are given a list of tuples and we need to group its keys and perform certain operations while grouping. The most common operation is addition. Let's discuss certain ways in which this task can be performed. Apart from addition, other operations can also be performed by doing small cha
    10 min read
  • Python - Summation of consecutive elements power
    Given a List, the task is to write a Python program to compute summation of power of consecutive elements occurrences frequency. Examples: Input : test_list = [2, 2, 2, 3, 3, 3, 3, 4, 4, 5] Output : 110 Explanation : 2^3 + 3^4 + 4^2 + 5 = 110 Input : test_list = [2, 2, 2, 3, 3, 3, 3, 4, 4] Output :
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences