Search code examples
pythoncloopspython-3.7

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 !


Solution

  • you can use the same logic you did with the c code, meaning that j will start from i:

    A = [1,2,3,4,5]
    for i in range(len(A)):
            for j in range(i, len(A)):
                try:
                    print(A[i],A[j+1])
                except IndexError:
                    pass
    

    another elegant solution is using itertools module:

    from itertools import combinations
    
    A = [1,2,3,4,5]
    comb = combinations(A, 2)
    for c in comb:
        print(c)