Reputation: 11
I want to divide a list into n sub-lists and print all possible sub-lists. n is integer input by user. length of list can be anything 1<=n<=len(list)
For example
if list = [1,2,3,4]
and n=1
solution = [1,2,3,4]
if n=2
solution=([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])
if n=3
solution=([1],[2],[3,4]),([1,2],[3],[4]),([1],[2,3],[4])
Note:- brackets do not represent tuple or any other data type output can be in any form. Ps:-This is not a code but stackoverflow forced me to format it as such This is what I tried
''''python
lst=[]
lst1=[]
lst4=[]
for i in range(0,10000):
element=int(input())
lst.append(element)
print("If you want to continue adding list press y else press n")
choice=input()
if choice=='y':
continue
elif choice=='n':
break
else:
print("please enter a valid choice")
print("Enter division size")
N=int(input())
maxchunk=len(lst)-N+1
for j in range(maxchunk,0,-1):
rchunk=(len(lst)-j)//(N-1)
lst2=lst[0:j]
lst1.append(lst2)
chunksize=((len(lst)-j)+1)//(N-1)
print(chunksize)
for k in range(j,len(lst),chunksize):
lst3=lst[k:k+chunksize]
lst1.append(lst3)
lst4.append(lst1)
lst1=[]
print(lst4)
''''
Upvotes: 0
Views: 656
Reputation: 101
Here is an alternative approach using a recursive generator function that yields all the desired partitions for a given array and number of partitions.
def partition(arr, n):
if n == 1:
yield (arr,)
else:
for i in range(1, len(arr)):
for other in partition(arr[i:], n-1):
yield (arr[:i],) + other
You can call this like
for item in partition([1,2,3,4], 3):
print(item)
Which shows
([1], [2], [3, 4])
([1], [2, 3], [4])
([1, 2], [3], [4])
Or alternatively, if you want to access everything at once
print(list(partition([1,2,3,4], 3)))
Showing
[([1], [2], [3, 4]), ([1], [2, 3], [4]), ([1, 2], [3], [4])]
Upvotes: 0
Reputation: 3883
You can use itertools.combinations
to iterate over all the ways to choose n-1
split points of your list:
from itertools import combinations
lst = [10, 20, 30, 40, 50]
n = 3
result = []
# n-1 split points:
for indices in combinations(range(1, len(lst)), n-1):
# indices are the indices of split points
splits = []
start = 0
for stop in indices:
splits.append(lst[start : stop])
start = stop
splits.append(lst[start : ])
result.append(splits)
result
:
[[[10], [20], [30, 40, 50]],
[[10], [20, 30], [40, 50]],
[[10], [20, 30, 40], [50]],
[[10, 20], [30], [40, 50]],
[[10, 20], [30, 40], [50]],
[[10, 20, 30], [40], [50]]]
Upvotes: 1