Reputation: 2753
What would be the python equivalent implementation for this C++ code:
char x[10];
for (int i=0; i < 10; i++) {
for (int j=i; j < 10; j++) {
calc_something(x[i], x[j])
}
}
Thank you
Upvotes: 2
Views: 4732
Reputation: 32300
Here are some solutions that don't use imports, and assuming that x
is already declared as a list containing 10 elements:
for i in range(10): # xrange in Python 2
for j in range(i, 10):
calc_something(x[i], x[j])
Or using the enumerate
function:
for i, el in enumerate(x):
for j in x[i:]:
calc_something(el, j)
Upvotes: 2
Reputation: 88997
This is done simply with itertools.combinations()
:
import itertools
...
for i, j in itertools.combinations(x, 2):
calc_something(i, j)
This gives what you want. Specifically, it will return the elements in this order:
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9),
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9),
(2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9),
(3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9),
(4, 5), (4, 6), (4, 7), (4, 8), (4, 9),
(5, 6), (5, 7), (5, 8), (5, 9),
(6, 7), (6, 8), (6, 9),
(7, 8), (7, 9),
(8, 9)]
Upvotes: 6
Reputation: 1
simplest would be :
for i in range(1,10):
for j in range(1,10):
calc_something( list[i],list[j])
instead of hard coding (1,10)
you can say
for i in list:
for j in list:
Upvotes: 0