📚 The CoCalc Library - books, templates and other resources
cocalc-examples / martinthoma-latex-examples / presentations / Programmieren-Tutorium / Tutorium-04 / euler28.py
132930 viewsLicense: OTHER
#!/usr/bin/python1# -*- coding: utf-8 -*-234def print_arr(a):5for line in a:6print(line)789def initialise(n):10array = [[0 for j in xrange(0, n)] for i in xrange(0, n)]11return array121314def spiral_fill(a):15n = len(a)16x = y = n/217number = 118# r u l o19order = [(1, 0), (0, 1), (-1, 0), (0, -1)]20i_order = 021length = 122a[y][x] = number23while not (x == (n-1) and y == 0):24for j in xrange(0, length):25xAdd, yAdd = order[i_order]26x += xAdd27y += yAdd28number += 129a[y][x] = number30if x == (n-1) and y == 0:31break32if i_order == 1 or i_order == 3:33length += 134i_order = (i_order+1) % 435return a363738def diagonal_sum(a):39n = len(a)40sum = -1 # you will have the element in the middle (1) twice41for i in xrange(0, n):42sum += a[i][i]43sum += a[n-i-1][i]44return sum4546if __name__ == "__main__":47import argparse4849parser = argparse.ArgumentParser(description="ProjectEuler: 28")50parser.add_argument("-n", metavar='N', type=int,51help="length of the spiral", required=True)52parser.add_argument("-d", action="store_true", default=False,53help="display the spiral")54args = parser.parse_args()55array = initialise(args.n)56array = spiral_fill(array)57if args.d:58print_arr(array)59print diagonal_sum(array)606162