Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132930 views
License: OTHER
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
4
5
def print_arr(a):
6
for line in a:
7
print(line)
8
9
10
def initialise(n):
11
array = [[0 for j in xrange(0, n)] for i in xrange(0, n)]
12
return array
13
14
15
def spiral_fill(a):
16
n = len(a)
17
x = y = n/2
18
number = 1
19
# r u l o
20
order = [(1, 0), (0, 1), (-1, 0), (0, -1)]
21
i_order = 0
22
length = 1
23
a[y][x] = number
24
while not (x == (n-1) and y == 0):
25
for j in xrange(0, length):
26
xAdd, yAdd = order[i_order]
27
x += xAdd
28
y += yAdd
29
number += 1
30
a[y][x] = number
31
if x == (n-1) and y == 0:
32
break
33
if i_order == 1 or i_order == 3:
34
length += 1
35
i_order = (i_order+1) % 4
36
return a
37
38
39
def diagonal_sum(a):
40
n = len(a)
41
sum = -1 # you will have the element in the middle (1) twice
42
for i in xrange(0, n):
43
sum += a[i][i]
44
sum += a[n-i-1][i]
45
return sum
46
47
if __name__ == "__main__":
48
import argparse
49
50
parser = argparse.ArgumentParser(description="ProjectEuler: 28")
51
parser.add_argument("-n", metavar='N', type=int,
52
help="length of the spiral", required=True)
53
parser.add_argument("-d", action="store_true", default=False,
54
help="display the spiral")
55
args = parser.parse_args()
56
array = initialise(args.n)
57
array = spiral_fill(array)
58
if args.d:
59
print_arr(array)
60
print diagonal_sum(array)
61
62