码迷,mamicode.com
首页 > 编程语言 > 详细

Euler_problem_18 for python

时间:2014-06-07 01:28:18      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:python

如下所示 给出2个解法

def euler_problem_18_1():

    """
    this problem spend my half-day but noting to finished ,so bad


    """
    rows = ‘‘‘
    3
    7 4
    2 4 6
    100 5 9 3
    ‘‘‘
    rows = reversed([map(int, row.split())
                     for row in rows.strip().split(‘\n‘)])
                      #  first deal with string
    totals = None
    for row in rows:
        totals = [
            value + (max(totals[i], totals[i + 1]) if totals else 0)
            for i, value in enumerate(row)
        ]
        print totals
    #  assert totals[0] == 1074
    print totals




def euler_problem_18_2():
    """
    using recursion
    """
    rows = []
    with open(‘a.txt‘) as f:
        for line in f:
            rows.append([int(i) for i in line.rstrip(‘\n‘).split(‘ ‘)])
    result = rec_sum_row(rows, len(rows) - 2)
    print result




def rec_sum_row(row_data, row_num):
    #  iterate over the given row
    for i in range(len(row_num)):
        #  add the largest of values below-left or below-right
        row_data[row_num][i] += max([row_data[row_num + 1][i], row_data[row_num + 1][i + 1]])
    # base case
    if len(row_data[row_num]) == 1:
        return row_data[row_num][0]
    else:
        return rec_sum_row(row_data, row_num - 1)

Euler_problem_18 for python,布布扣,bubuko.com

Euler_problem_18 for python

标签:python

原文地址:http://blog.csdn.net/zouyee/article/details/27342963

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!