def count_gold(pyramid): """ Function: count the max gold total possible at each position moving from the top down in the pyramid Parameter: pyramid is a tuple made up of tuples of integer values. Prints: a string of the pyramid gold sums Returns: max integer of bottom row of values """ pyr_dct={(row,column):pyramid[row][column] for row in range(len(pyramid)) for column in range(len(pyramid[row]))} key_table=[(row,column) for row in range(len(pyramid)) for column in range(row+1)] pyr_path={} for i in key_table: row,column=i if row==0: pyr_path[i]=pyr_dct[i] continue if column==0: pyr_path[i]=pyr_dct[i] + pyr_path[(row-1,column)] continue if column==row: pyr_path[i]=pyr_dct[i] + pyr_path[(row-1,column-1)] continue pyr_path[i] = pyr_dct[i] + max(pyr_path[row-1, column],pyr_path[row-1,column-1]) pyramid_sums = '' for i in sorted(pyr_path.keys()): pyramid_sums += '{}{}'.format(pyr_path[i],('\n' if i[0]==i[1] else ',')) print(pyramid_sums) return max(pyr_path.values()) assert count_gold(( (1,), (2, 3), (3, 3, 1), (3, 1, 5, 4), (3, 1, 3, 1, 3), (2, 2, 2, 2, 2, 2), (5, 6, 4, 5, 6, 4, 3) )) == 23, "First example" assert count_gold(( (1,), (2, 1), (1, 2, 1), (1, 2, 1, 1), (1, 2, 1, 1, 1), (1, 2, 1, 1, 1, 1), (1, 2, 1, 1, 1, 1, 9) )) == 15, "Second example" assert count_gold(( (9,), (2, 2), (3, 3, 3), (4, 4, 4, 4) )) == 18, "Third example"
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question