This question already has answers here:
Is there an elegant way to cycle through a list N times via iteration (like itertools.cycle but limit the cycles)?
(6 answers)
Closed 3 years ago.
I know that python 3 range no longer produces a list, but a range object.
Is there a best way to do the following in python 3?
for i in range(3) * 2:
print(i)
# 0
# 1
# 2
# 0
# 1
# 2
One way to do it without making a list is to use chain.from_iterable and repeat from the itertools module. This uses O(1) extra space.
>>> from itertools import chain, repeat
>>> for i in chain.from_iterable(repeat(range(3), 2)):
... print(i)
...
0
1
2
0
1
2
Just make a list from the range:
for i in list(range(3)) * 2:
print(i)
Result:
0
1
2
0
1
2
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Here's what I want to do:
import random
a = 1
b = 2
# choose between these 2 variables (a and b) with probability
# 50% to choose one
print(# the function that chooses)
output: either 1 or 2
Some people suggested me to use random.choice, but that doesn't work.
Others said random.random, but it doesn't work either.
Is there a probability module or something??
random.choice() works, you just need to pass the choices as a tuple or a list:
>>> a = 5
>>> b = 3
>>> random.choice((a, b))
5
>>> random.choice((a, b))
3
>>> random.choice((a, b))
3
>>> random.choice((a, b))
5
random.choice() definitely works:
The choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple or any other kind of sequence.
import random
#100 cases
for i in range(100):
k = random.choice((1, 2))
print(k)
Output:
2
1
2
2
2
2
1
2
2
2
1
1
2
1
2
1
...
You just weren't passing the options into a list/tuple.
You can also utilize random.randint:
However, if you were to use this to pick between larger numbers like 1 and 100, it would not work:
The randint() method returns an integer number selected element from the specified range. (Inclusive)
import random
#100 cases
for i in range(100):
k = random.randint(1, 2)
print(k)
Output:
2
1
2
1
2
1
2
1
1
2
2
2
1
2
1
1
1
...
Given a list with numbers between 0 and 5. I want every possible result of two numbers in this list that returns true for (a ** 2 + b ** 2) < 12.
My code for this is:
from random import choices
from math import factorial
nodes = list(range(0,6))
lis = []
for e in range(0,factorial(5)):
nodesf = choices(nodes, k= 2)
if not nodesf in lis:
if (nodesf[0]**2 + nodesf[1]**2) <= 12:
print(nodesf)
lis.append(nodesf)
lis.append(nodesf[::-1])
print(lis)
else:
lis.append(nodesf)
But, as you can see, this is probably a horrible way to solve this.
If you see a more clear and efficient code to solve this, please, help me.
You can try the combinations_with_replacement() method from the built-in module, itertools:
from itertools import combinations_with_replacement
for a, b in combinations_with_replacement(range(6), 2):
if (a ** 2 + b ** 2) < 12:
print(a, b)
Output:
0 0
0 1
0 2
0 3
1 1
1 2
1 3
2 2
The combinations_with_replacement() method is similar to the combinations() method, except the combinations_with_replacement() method allows one element to be used in the same combination more than once.
Do note that it does not include 1 0 as a solution as there already exists 0 1 in the results. If you want to include such, you can use the product() method:
from itertools import product
for a, b in product(range(6), repeat=2):
if (a ** 2 + b ** 2) < 12:
print(a, b)
Output:
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
3 0
3 1
What's wrong with your code ?
Iterating through range(0, factorial(5)) does not make a lot of sense to me : you're going to do 120 iterations. To solve this, you just need two compare each elements of nodes with the whole list, hence two for loops on your nodes : only 25 iterations.
Why using choices to pick elements from nodes ? It's a stochastic operation, you won't be sure to go through every elements of the list.
Simple solution
If you care about permutation, i.e. you want to get both (0, 1) and (1, 0) for example, a simple list comprehension should do the trick.
[ (a, b) for a in nodes for b in nodes if a**2+b**2<12 ]
Otherwise, just take a look at the perfect Ann Zen's answer using the itertools module :)
This question already has answers here:
Numpy mask to count number of elements satisfying a condition
(3 answers)
Closed 3 years ago.
I have an array as follow:
a = [1 2 5 3 8 7 2 9 8]
and a constant number b=4
How can I count the occurrence c of a being inferior to b?
So in this example c=4
Using numpy:
np.sum(a < 4)
Or a sum on generator:
sum(num < 4 for num in a)
If you mean "less than" by "inferior", you can use a list comprehension
c = len([x for x in a if x < b])
If you're worried about space constraints, you can use a generator like Alexander's answer.
sum(1 if num < b else 0 for num in a)
This question already has answers here:
Scope of python variable in for loop
(10 answers)
Closed 3 years ago.
I want to print i and k till i is less than or equal to k.
in C++ the code can be given as:
for(i=0;i<k;i++){
cout<<i<<k;
k--;
}
I am not getting the correct output.
this is my code
k=5
for i in range(k):
print(i,k)
k-=1
the output i get is:
0 5
1 4
2 3
3 2
4 1
but i want to get:
0 5
1 4
2 3
is there someway to use the range() function for this?
For loops in Python are really for-each and suboptimal for your needs. Use while instead:
i = 0; k = 5
while i < k:
print(i,k)
i += 1
k -= 1
k=5
for i in range(k):
print(i,k)
if k<=i:
break
k-=1
This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Use two or more relational operators in one sentence in python
(2 answers)
Closed 4 years ago.
Running python v3.6.5 PyCharm
I have a simple for loop with an if and else statement with it:
for i in range(10):
if i > 3 < 5:
print(i, "first")
else:
print(i, "second")
The output I get is:
0 second
1 second
2 second
3 second
4 first
5 first
6 first
7 first
8 first
9 first
but shouldn't the output be:
0 second
1 second
2 second
3 second
4 first
5 second
6 second
7 second
8 second
9 second
Try it yourself. It doesn't make sense to me. Why is it doing this?
Don't really need to know
I know you might be thinking, why didn't you just say
if i == 4
but this is just a simplified problem in my program.
Thanks in advance
Hugo
A chain of operators like i > 3 < 5 is interpreted as
i > 3 and 3 < 5
where the "middle" operand(s) are repeated for the left and right operator. You want
3 < i and i < 5
, which can be abbreviated (using the reverse of the previous interpretation) as 3 < i < 5.
The correct syntax is:
if 3 < i < 5:
Be aware that Python is special here, and this construct won't work in most other languages (where you'd have to say something like 3 < i and i < 5 instead).