Ad

Maximum Collatz Length In Python, But Output Is Not Correct

- 1 answer

This is my first time posting to Stackoverflow.

I'm trying to solve this problem here: https://codingbat.com/prob/p270692?parent=/home/[email protected]/all

When looking at all hailstone sequences from 1 to z, maxHail(z) will return the starting number that creates the longest sequence. In other words, maxHail(n) looks at hailLen(1), hailLen(2) ... hailLen(n) and returns the number from 1-n that had the largest hailstone sequence. You should look at the hailLen() problem before working on this. You should use your solution from the hailLen() problem. ( http://codingbat.com/author/p264289 ) since hailLen(3) is larger than the hailLen of 4 or 5, maxHail of 3,4,5 all return 3. Since 6 has a longer sequence, maxHail(6) gives us 6. remember: Use the hailLen function you already wrote!

Here's my code and the output: enter image description here

However, I'm not sure where this goes wrong - I checked line-by-line and couldn't see anything wrong. Could anyone help me fix this? Thank you!

Ad

Answer

I see what is wrong - hailLen returns lenght of sequence and the question is about index for which the sequence is the longest. Just store it in variable

if (res := hailLen(i)) > counter: # it's python 3.8 syntax
    counter = res
    index = i
return index
Ad
source: stackoverflow.com
Ad