#!/usr/bin/python # coding: utf-8 n = 3; k = 2; def toFlatString(todo1, curr_k, callevel, a = None): if a is None: a = [] for i in todo1: if isinstance(i, list): toFlatString(i, None, callevel + 1, a) else: a.append(str(i)) if callevel == 1: a.append(str(curr_k)) return ", ".join(a) todo_list = [[0, []]] while todo_list: todo = todo_list.pop() local_n = todo[0] + 1; for curr_k in range(k + 1): if local_n == n: print toFlatString(todo[1], curr_k, 1) else: todo_list.append([local_n, [todo[1], curr_k]])