programming challenge: how does this algorithm (tied to Number Theory) work?

2024/11/23 22:41:45

In order to work on my python skills, I am sometimes doing various challenges on the internet (eg on hackerrank). Googling for something else, I found this problem, and the accompanying solution on the internet, and it caught my attention:

The Grandest Staircase Of Them All

With her LAMBCHOP doomsday device finished, Commander Lambda is preparing for her debut on the galactic stage - but in order to make a grand entrance, she needs a grand staircase! As her personal assistant, you've been tasked with figuring out how to build the best staircase EVER.

Lambda has given you an overview of the types of bricks available, plus a budget. You can buy different amounts of the different types of bricks (for example, 3 little pink bricks, or 5 blue lace bricks). Commander Lambda wants to know how many different types of staircases can be built with each amount of bricks, so she can pick the one with the most options.

Each type of staircase should consist of 2 or more steps. No two steps are allowed to be at the same height - each step must be lower than the previous one. All steps must contain at least one brick. A step's height is classified as the total amount of bricks that make up that step. For example, when N = 3, you have only 1 choice of how to build the staircase, with the first step having a height of 2 and the second step having a height of 1: (# indicates a brick)

#
##
21

When N = 4, you still only have 1 staircase choice:

#
#
##
31

But when N = 5, there are two ways you can build a staircase from the given bricks. The two staircases can have heights (4, 1) or (3, 2), as shown below:

#
#
#
##
41#
##
##
32

Write a function called answer(n) that takes a positive integer n and returns the number of different staircases that can be built from exactly n bricks. n will always be at least 3 (so you can have a staircase at all), but no more than 200, because Commander Lambda's not made of money!

https://en.wikipedia.org/wiki/Partition_(number_theory)

def answer(n):# make n+1 coefficientscoefficients = [1]+[0]* n#go through all the combosfor i in range(1, n+1):#start from the back and go down until you reach the middlefor j in range(n, i-1, -1):print "add", coefficients[j-i], "to position", jcoefficients[j] += coefficients[j-i]print coefficientsreturn coefficients[n] - 1

Now I tried to understand the above solution, by walking manually through an example. For example, for

answer(10)

the options are:

1 2 3 4
1 2 7
1 3 6
1 9
1 4 5
2 3 5
2 8
3 7
4 6

So there are nine options total, that add up to 10. When I run the program, the final few lists are:

        add 1 to position 10[1, 1, 1, 2, 2, 3, 4, 5, 6, 7, 9]add 1 to position 9[1, 1, 1, 2, 2, 3, 4, 5, 6, 8, 9]add 1 to position 10[1, 1, 1, 2, 2, 3, 4, 5, 6, 8, 10]9

So the result is correct, but I don't understand what the final list, or all lists, have to do with the solution. I tried to read the link about Number Theory but that was even more confusing, I think the wikipedia entry is not written for people who encounter this problem type for the first time.

Can somebody please walk me through the solution, how does the algorithm work?

Answer

Regarding the answer function you posted:

At the end of each iteration of the outer loop, coefficients[x] is the number of staircases you can make with height at most i, having used a total of x blocks. (including staircases with only one stair or zero stairs).

coefficients is initialized to [1,0,0...] before the loop, indicating that there is only one staircase you can make with height at most 0. It is the one with no stairs, so you will have consumed 0 blocks to make it.

In each iteration of the loop, the coefficients array is transformed from representing max height i-1 to representing max height i, by incorporating the possibility of adding a step of height i to any shorter staircase that leaves you with at least i blocks.

finally it returns the number of ways you can get to the end after having used all n blocks, minus one since the single stair of height n is invalid.

This algorithm is an example of "dynamic programming".

https://en.xdnf.cn/q/120606.html

Related Q&A

Running total for list of dict

Have a python list of dict as following:Dict1 = [{date: 1, name: xyz, qty: 100},{date: 1, name: xyz, qty: 200},{date: 1, name: xyz, qty: 300},{date: 1, name: xyz2, qty: 30},{date: 2, name: xyz, qty: 10…

How to convert CSV file to a specific JSON format with nested objects?

I want to populate my json message with data from a CSV file. I want each row to be a "new" json object. I am using Python and will connect the the code to an API once done. Some of the data …

How do I repeat the program? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

How to parse json data in Python? [duplicate]

This question already has answers here:How can I parse (read) and use JSON in Python?(5 answers)Closed 10 years ago.Please help me to parse this json in python.{ "IT" : [ { "firstName…

Why did they opt for the message most recent call last? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed last month.Improve …

AttributeError: NoneType object has no attribute current

class LoginScreen(Screen):def __init__(self,**kwargs):super(LoginScreen, self).__init__(**kwargs)print self,self.parent.currentclass AppScreenManager(ScreenManager):pass#Base Class class AppBaseClass(A…

Python urllib2 or requests post method [duplicate]

This question already has answers here:Submitting to a web form using python(3 answers)Closed 8 years ago.The community reviewed whether to reopen this question 9 months ago and left it closed:Original…

How to fix Django NoReverseMatch Error

I have built a simple blog app with Django and I have had some issue with NoReverseMatch. Here are my problem screenshots: https://prnt.sc/imqx70 https://prnt.sc/imqwptHere is my code on Github: https:…

Selenium NoSuchElementException with driver.find_element_by_xpath

First question: How do I make python minimize chrome? Second question: When getting to the end page using the next button how do I tell python to go on.. and not give me an error?driver.get("htt…

Traverse Non-Binary Tree [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…