Exercise 3 Adv: Answer not working
My code for E3A gives the correct answer every time, but the test always fails on 2/5 with error codes that reference lines that are way outside of my code:
(I know that my answer is correct because the same code with minimal changes worked for the Advanced task and all the plots it gives out are correct)
import math
import random
w = [random.random()/3, random.random()/3, random.random()/3]
h = [1.+math.sin(1+x/6.)*w[0]+math.sin(-.3+x/9.)*w[1]+math.sin(-.2+x/30.)*w[2] for x in range(100)]
h[0] = 0.0; h[99] = 0.0
def climb(x, h):
summit = False
while not summit:
summit = True
if h[x + 1] > h[x]:
x = x + 1
summit = False
elif h[x - 1] > h[x]:
x = x - 1
summit = False
return x
def main(h):
x0 = random.randint(1, 98)
x = climb(x0, h)
print("Venla started at %d and got to %d" % (x0, x))
return x0, x
main(h)
The error message I get:
File "/usr/local/lib/python3.12/unittest/case.py", line 58, in testPartExecutor
yield
File "/usr/local/lib/python3.12/unittest/case.py", line 634, in run
self._callTestMethod(testMethod)
File "/usr/local/lib/python3.12/unittest/case.py", line 589, in _callTestMethod
if method() is not None:
^^^^^^^^
File "/app/test/test_main.py", line 39, in test_answer_three
x0, x = main(h)
^^^^^^^
File "/app/src/main.py", line 35, in main
x = climb(x0, h)
^^^^^^^^^^^^
File "/app/src/main.py", line 22, in climb
if h[x + 1] > h[x]:
~^^^^^^^
Error: list index out of range
Example solution
def climb(x, h):
# keep climbing until we've found a summit
summit = False
while not summit:
summit = True # stop unless there's a way up
if h[x + 1] > h[x] and h[x+1]:
x = x + 1 # right is higher, go there
summit = False # and keep going
elif h[x - 1] > h[x]:
x = x - 1 # left is higher, go there
summit = False # and keep going
return x