If your role receives ai
and i
as parameters, the least we can expect is that the expression that will define the next value depends on these two values.
By the examples it is clearer that the values of the parameters are directly linked to the result.
next(1, 1) = 0 ... 1 - 1 = 0
next(-1, 4) = 3 ... -1 + 4 = 3
next(-4, 10) = 6 ... -4 + 10 = 6
...
And by that connection we can see that i
is odd, we subtract the two values to obtain the next term of the sequence; if i
is par, just add them up.
Soon:
def next(ai, i):
signal = 1 if i % 2 == 0 else -1
return ai + signal * i
assert next(1, 1) == 0
assert next(-1, 4) == 3
assert next(-4, 10) == 6
If you’re not a fan of if
to define the signal, you can make the equivalent expression using potentiation, because (-1)**i
will be negative for i
odd and positive for i
par:
def next(ai, i):
return ai + (-1)**i * i
lucasbbs, please edit your question by entering the code you tried to do and specifying your difficulties.
– Solkarped
@Solkarped, okay... I already edited the code The problem is in the last test case
– lucasbbs
I don’t know if I understood the criteria, but finally, my guess: https://ideone.com/jG2qE9 - Changing the subject, I don’t know this platform, but I don’t like it anymore. It mixes 2 problems: one is programming itself, the other is trying to guess the crazy rule that generates the numbers. If one were to teach only programming, the correct - in my opinion - would be to explain the rule, because then one focuses only on writing the algorithm. But by turning it into a little guessing game, I think it hurts learning (but I don’t know, I’m not a teacher, I might be wrong...)
– hkotsubo
I agree with you @hkotsubo... Even more it is clear that my solution also satisfies the problem
– lucasbbs