PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] What changes to my code should I make so that my code would work?

 July 10, 2022     list, python, reference     No comments   

Issue

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??


Solution

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


Answered By - Tyler Liu
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing