0

So I'm trying to implement a function ptt(L:List[int],k:int) that returns a nested list containing partitions of L where each element of the list is itself a list containing exactly k elements (except the last partition which may have fewer than k elements). For example, when L = [1,2,3,4,5,6,7] and k = 2, partition(L, k) returns [[1,2],[3,4],[5,6],[7]]. Here are a few more examples.

assert ptt([1,2,3],2) == [[1,2],[3]]
assert ptt([1,2,3],3) == [[1,2,3]]
assert ptt([1,2,3,4],1) == [[1],[2],[3],[4]]
assert ptt([1,2,3,4],2) == [[1,2],[3,4]]

Here is my attempt at the code...

def ptt(L, k):
    if (L == 0 or k == 0 or k > L):
        return 0
    if (k == 1 or k == L):
        return 1
    return (k * ptt(L - 1, k) +
                ptt(L - 1, k - 1))

However, this doesn't work at all... what changes to my code should I make to make sure it works??

  • You should start by showing us what `countP` is. – Mark Ransom Nov 25 '21 at 03:34
  • 1
    If `L` is a list as you described in the question, then things like `L == 0`, `k > L` or `L - 1` do not make sense. – j1-lee Nov 25 '21 at 03:38
  • @MarkRansom my bad, changed the function name but not the name inside it, already edited it btw – jordan parker Nov 25 '21 at 03:38
  • What happens when you run your code? Do you get any errors? If so, I suggest googling the error message to get some tips on how to fix it. If not, what is the result? If you don't get the result you want, then you need to debug your code. [This article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) has some great tips to get you started. – Code-Apprentice Nov 25 '21 at 03:40
  • So it's a recursive function? If so the name is still wrong. – Mark Ransom Nov 25 '21 at 03:40
  • yep its a recursive one – jordan parker Nov 25 '21 at 03:42

2 Answers2

1

Sorry this going to sound harsh, but since you are learning to program, you should learn to use your best resource on the internet...google searches. Most initial forays into programming tasks have already been solved (many times) and the solutions are readily available.

A simple query "partition a list to sublists python" yields several sources. Try: Split a python list into other "sublists" i.e smaller lists

The solution there is

chunks = [data[x:x+k] for x in range(0, len(data), k)]

Jim Parker
  • 1,095
  • 11
  • 16
0

This code is very different from your approach, but it produces the result you're looking for:

def partition(nums, k):
    result = []
    for i in range(0, len(nums), k):
        result.append(nums[i:i+k])
    return result
Tyler Liu
  • 989
  • 1
  • 6
  • 7