Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C to Python : For loop

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 !

like image 924
CURVX Avatar asked Feb 13 '26 16:02

CURVX


1 Answers

That's not the way of doing it:

  • try / except blocks are costly, and there's actually no need for them here
  • That form of for isn't very Pythonic

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
like image 72
CristiFati Avatar answered Feb 16 '26 06:02

CristiFati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!