-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprob0011.py
More file actions
84 lines (65 loc) · 2.37 KB
/
Copy pathprob0011.py
File metadata and controls
84 lines (65 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""Project Euler Problem 11. https://projecteuler.net/problem=11
problem involves a 20x20 grid of two-digit numbers printed on the
problem webpage. This solution retrieves the numbers from the website"""
import requests
import bs4
def get_page():
"""
gets the problem page from the web, saves to the same folder as this file.
only need to run once, then just get info locally
:return: none
"""
res = requests.get("https://projecteuler.net/problem=11")
f = open('prob11.txt', 'w')
f.write(res.text)
f.close()
def get_grid():
"""
takes the 20x20 grid of numbers found on the webpage and puts it into a list of lists
:return: 20-item list of 20-item lists
"""
# get the html text from the file saved above
f = open('prob11.txt', 'r')
content = f.read()
f.close()
# turn it into a soup
soup = bs4.BeautifulSoup(content, "lxml")
# use the class that gets just the numbers
grid = soup.select('.monospace.center')
# keep only the text
numbers = grid[0].text
# turn it into a list
number_list = numbers.split()
# make the string numbers into integers
for i in range(400):
number_list[i] = int(number_list[i])
# turn into grid
number_grid = []
for i in range(20):
number_grid.append(number_list[i*20:i*20+20])
return number_grid
def calc_products():
grid = get_grid()
greatest_product = 0
# check rows of 4
for line in grid:
for i in range(17):
product = line[i]*line[i+1]*line[i+2]*line[3]
greatest_product = max(greatest_product, product)
# check columns of 4
for i in range(20):
for j in range(17):
product = grid[i][j]*grid[i][j+1]*grid[i][j+2]*grid[i][j+3]
greatest_product = max(greatest_product, product)
# check NW to SE diagonals
for i in range(17):
for j in range(17):
product = grid[i][j]*grid[i+1][j+1]*grid[i+2][j+2]*grid[i+3][j+3]
greatest_product = max(greatest_product, product)
# check SW to NE diagonals
for i in range(17):
for j in range(17):
product = grid[i+3][j]*grid[i+2][j+1]*grid[i+1][j+2]*grid[i][j+3]
greatest_product = max(greatest_product, product)
print(greatest_product)
calc_products()