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

B
Bianchi (320 points)
2 3 5
asked Oct 26, 2021 in HW1 optional by Bianchi (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.
123 views

3 Answers

GabrielAlexandru (7760 points)
2 4 29
answered Oct 26, 2021 by GabrielAlexandru (7,760 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
commented Oct 26, 2021 by Excale (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 (172780 points)
514 935 1789
answered Oct 26, 2021 by andrea.sterbini (172,780 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)
11 20 65
answered Oct 26, 2021 by Luigi Pizza (6,120 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!