Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

How to reduce length of a for loop, if it is possible.

B
Bianchi (320 points)
2 3 5
in HW1 optional by (320 points)
Hi guys!

When testing my homework i noticed that when the function reaches the lasts indexes of the list, it starts over. Indeed, it "scans" the same items multiple times . In particular, this for loop works on the range of the length of the list of integers; but under precise condition, the list is reduced. I want to reduce the for loop accordingly to the trend of the function, but I don't know if it is possible.
274 views

3 Answers

GabrielAlexandru (7760 points)
2 4 29
by (7.8k points)

I think the problem is related to the range function, because it’s not dynamically changed as the list changes. Here they suggest using a while loop instead of a for loop

Excale (490 points)
0 0 6
by (490 points)
A while loop could be better. I don't know what you're trying to do, but instead of reducing the list, you could skip items by increasing the counter.
andrea.sterbini (207940 points)
756 1270 2377
by (208k points)
Are you modifying your list in-place? This normally produces difficult-to-recognize errors in loops.

Try to use a copy of the list to get the elements while you change the original (or vice versa)
Luigi Pizza (6120 points)
15 20 65
by (6.1k points)
I'm telling you the solution I have implemented in my script. I've implemented it with a while, but it should work the same with a for. You don't want to use a range: you can't easily change the positions you want to consider. Try using an accumulator instead, reducing it whenever you reduce the list, so that you won't skip any elements, and neither will you loop over the same elements.

Let me know if I was clear, and if I was don't forget to pin this as the best comment. Thank you!