I am trying to figure out how to count up to a certain integer (as a range) alternating between two different numbers like 2 and 3. So that the output would be 2 5 7 10 12 15 etc.
I started off trying to alter a simple while loop like the following to take two values:
a = 0
while a < 100:
a = a + 2 + 3
print(a, end=' ')
But it just ends up counting up to 100 by 5.
I have tried number ranges and for loops and modules like itertools to try and figure out a way to do this and I am completely stumped.
I have performed search after search on this and all I can find is counting up by a single number with loops and ranges.
If you want to count multiple items in a list, you can call count() in a loop. This approach, however, requires a separate pass over the list for every count() call; which can be catastrophic for performance. Use couter() method from class collections , instead.
Unfortunately, the built-in str. count function doesn't support doing counts of multiple characters in a single call.
Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
You can use itertools.cycle
for this
import itertools
a = 0
it = itertools.cycle((2,3))
while a < 100:
a += next(it)
print(a)
Output
2
5
7
10
...
95
97
100
The itertools.cycle
generator will just continuously loop back over the tuple as many times as you call it.
You need to print the content of a
after adding two, and after adding three:
a = 0
while a < 100:
a = a + 2
print(a, end=' ')
if a < 100:
a = a + 3
print(a, end=' ')
That being said, you can better construct a generator, that iteratively adds two and three interleaved:
def add_two_three(a):
while True:
a += 2
yield a
a += 3
yield a
You can then print the content of the generator until it hits 100 or more:
from itertools import takewhile
print(' '.join(takewhile(lambda x: x < 100,add_two_three(0))))
You have to increment a
with different value each time (2 and 3). You can just swap the two values being used to increment a
on each iteration to achieve this.
a = 0
inc1 = 2 # values being used to increment a
inc2 = 3
while a < 100:
a = a + inc1
inc1, inc2 = inc2, inc1 # swap the values
print(a, end=' ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With