Welcome, guest | Sign In | My Account | Store | Cart

Let be a number of buckets, containing each, a variable number of items. This function return all combinations possible of one item picked out of each bucket

example, with three buckets {ba, be, bi}, {ka, ko, ku, ke} and {to, ty}, the function enumerate as such:

 0. ba-ka-to
 1. ba-ka-ty
 2. ba-ko-to
 3. ba-ko-ty
 4. ba-ku-to
 5. ba-ku-ty
 6. ba-ke-to
 7. ba-ke-ty
 8. be-ka-to
 9. be-ka-ty
10. be-ko-to
11. be-ko-ty
12. be-ku-to
13. be-ku-ty
14. be-ke-to
15. be-ke-ty
16. bi-ka-to
17. bi-ka-ty
18. bi-ko-to
19. bi-ko-ty
20. bi-ku-to
21. bi-ku-ty
22. bi-ke-to
23. bi-ke-ty
Python, 16 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/env python3

def of_bucket(lst, depth=0) :
	""" return all combinations of items in buckets """
	#dbg print("of_bucket({0}, {1})".format(lst, depth))
	for item in lst[0] :
		if len(lst) > 1 :
			for result in of_bucket(lst[1:], depth+1) :
				yield [item,] + result
		else :
			yield [item,]

if __name__ == '__main__' :
	bucket_lst = [["ba", "be", "bi"], ["ka", "ko", "ku", "ke"], ["to", "ty"]]
	for n, combination in enumerate(of_bucket(bucket_lst)) :
		print("{0:2d}. {1}".format(n, '-'.join(combination)))
Created by yota on Sat, 5 Sep 2015 (GPL3)
Python recipes (4591)
yota's recipes (13)

Required Modules

  • (none specified)

Other Information and Tasks