-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-solution.py
More file actions
68 lines (45 loc) · 1.81 KB
/
01-solution.py
File metadata and controls
68 lines (45 loc) · 1.81 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
import numpy as np
def ImportData(filename):
# function to import data from a text file
data = np.loadtxt(filename)
return data
#input the problem data as sonar
sonar = ImportData("input/01")
# for part 1
# turn sonar into a 2d array.
# Column 0 will be all the sonar values in order, starting from the 1st value (ie skip the 0th)
# Column 1 will be all the sonar values in order, starting from the 0th value and skipping the final value
# Then glue them together as a 2d array with each row being [ sonar[i] , sonar[i-1] ]
a = np.column_stack((sonar[1:], sonar[:-1]))
# make a variable to count how many times depth increases
count = 0
#iterate over the elements of a. if a sonar element x[0] is greater than the preceeding sonar element x[1], increase the count by one
for x in a:
if x[0] > x[1]:
count += 1
# return the answer to part 1
print("Answer to part one using for loop")
print(count)
# try using list comprehension instead
steps = [(p, q) for [p, q] in np.column_stack((sonar[1:], sonar[:-1])) if p > q ] # use list comprehension to make a list containing only pair where p > q
print("Answer to part one using list comp")
print(len(steps))
# part 2
# get the length of sonar
n = sonar.shape[0]
x = 0
count = 0
while x < (n - 3):
sum1st = sonar[x] + sonar[x+1] + sonar[x+2]
sum2nd = sonar[x+1] + sonar[x+2] + sonar[x+3]
if sum1st < sum2nd:
count += 1
x += 1
# I now realise I could've just tested if sonar[i] < sonar[i+3]
# return the answer to part 2
print("Answer to part two using while loop")
print(count)
# try using listcomp
steps = [(p, q) for [p, q] in np.column_stack((sonar[3:], sonar[:-3])) if p > q ] # use list comprehension to make a list containing only pair where x_i+3 > x_i
print("Answer to part two using list comp")
print(len(steps))