So I have this code in C which outputs the following :
Code :
scanf("%ld",&N);
long long A[N];
for(i=1;i<=N;i++)
scanf("%lld", &A[i]);
for(i=1;i<N;i++)
for(j=i;j<=N-1;j++) {
printf("%d %d\n", A[i], A[j+1]);
Input :
5
1 2 3 4 5
Output :
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
How do I get the same output using python 3.7.x ?
Tried :
A = [1,2,3,4,5]
for i in range(len(A)):
for j in range(len(A)):
try:
print(A[i],A[j+1])
except IndexError:
pass
Tried Output :
1 2
1 3
1 4
1 5
2 2
2 3
2 4
2 5
3 2
3 3
3 4
3 5
4 2
4 3
4 4
4 5
5 2
5 3
5 4
5 5
This is the output that I am getting which is just traversing each loop, printing the value out and so getting the repeated pairs.
Help appreciated, thank you !
That's not the way of doing it:
You should try to replicate as close as possible the C loop. For that, [Python 3. Docs]: Built-in Functions - enumerate(iterable, start=0) comes in handy (allows working on element indexes). Also, sequence slicing was used.
>>> a = [1, 2, 3, 4, 5] >>> >>> for idx0, elem0 in enumerate(a): ... for elem1 in a[idx0 + 1:]: ... print(f"{elem0} {elem1}") ... 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 4 5
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