Pyramid Slide Down (Codewars 4kyu Python)

题目:

Lyrics…
Pyramids are amazing! Both in architectural and mathematical sense. If you have a computer, you can mess with pyramids even if you are not in Egypt at the time. For example, let’s consider the following problem. Imagine that you have a pyramid built of numbers, like this one here:

   /3/
  \7\ 4 
 2 \4\ 6 
8 5 \9\ 3

Here comes the task…
Let’s say that the ‘slide down’ is the maximum sum of consecutive numbers from the top to the bottom of the pyramid. As you can see, the longest ‘slide down’ is 3 + 7 + 4 + 9 = 23
Your task is to write a function longestSlideDown (in ruby: longest_slide_down) that takes a pyramid representation as argument and returns its’ largest ‘slide down’. For example,
longestSlideDown([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]) => 23

By the way…
My tests include some extraordinarily high pyramids so as you can guess, brute-force method is a bad idea unless you have a few centuries to waste. You must come up with something more clever than that.

我的思路:

从第二行开始,一行一行往下刷新,每一行的第i个等于自己加上自己上一行的第i个和第(i-1)个里最大的那个,如果数字最左边,那只能加上上一行的第i个,因为没有第(i-1)个,同理,最后一个也只能加上上一行的最后一个。

循环到最后一层,把结果放到一个list中,取max。

我的解答:

def longest_slide_down(pyramid):
    pyramid[0][0] = [pyramid[0][0]]
    for i in range(1,len(pyramid)):
        for j in range(len(pyramid[i])):
            if j == 0:
                last_list = pyramid[i-1][j]
            elif j == len(pyramid[i]) - 1:
                last_list = pyramid[i-1][j-1]
            else:
                last_list = pyramid[i-1][j] + pyramid[i-1][j-1]
            new_list = []
            last = max(last_list)
            new_list.append(last + pyramid[i][j])
            pyramid[i][j] = new_list
    final = []
    for i in pyramid:
        for j in i:
            for k in j:
                final.append(k)
    return max(final)

Most Clever:

做完题目看一下题后投票clever最多的答案:

def longest_slide_down(p):
    res = p.pop()
    while p:
        tmp = p.pop()
        res = [tmp[i] + max(res[i],res[i+1])  for i in range(len(tmp))] 
    return res.pop()

这个答案是从下往上循环,从倒数第二行开始,每个数字在下一行的i和(i+1)位置选一个较大的和自己相加。从下到上有一个好处,就是不用判断i和(i+1)位置是否存在。

总结:

思路基本一致,Most Clever少了一个判断的过程。另外,我在做题的时候,先用了一个比较笨的方法,提交的时候超时了。然后才想到后来的方法,所以改动之后代码及其不优雅,而且最后还得把三维list展开。建议朋友们想清楚再开始敲代码。

你可能感兴趣的:(刷题,#,Codewars,算法,python)