Posts

Showing posts with the label loops

How can I get next few elements in an array but jump back to the start when passing the last element?

6 1 Imagine I have the following simple array: const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"]; Now I want to get the next for instance 3 elements after "el5" (index 4). As you can see there are only 2 elements left in the array. When hitting last index in the array I want to go back to the start and continue there. This should be the expected output when the start is "el5" (index 4): ["el6", "el7", "el1"] . And this is what I've tried so far. const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"]; let output = []; const followingElementsCount =...

Back and forth loop Python

I want to create an infinite loop that counts up and down from 0 to 100 to 0 (and so on) and only stops when some convergence criterion inside the loop is met, so basically something like this: for i in range(0, infinity): for j in range(0, 100, 1): print(j) # (in my case 100 lines of code) for j in range(100, 0, -1): print(j) # (same 100 lines of code as above) Is there any way to merge the two for loops over j into one so that I don't have write out the same code inside the loops twice? Use the chain method of itertools import itertools for i in range(0, infinity): for j in itertools.chain(range(0, 100, 1), range(100, 0, -1)): print(j) # (in my case 100 lines of code) As suggested by @Chepner, you can use itertools.cycle() for the infinite loop: from itertools import cycle, chain for i in cycle(chain(range(0, 100, 1), range(100, 0, -1))): .... As well as the other answers you can use a bit of maths: while(True): for i in range...