3

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 !

3
  • 1
    In C, an array declared as A[N] has N entries, A[0] through A[N-1]. Accessing A[N] invokes undefined behaviour, which is going to be hard to replicate exactly in Python... Commented Dec 13, 2019 at 7:59
  • 1
    print(*(f'{j} {k}' for i, j in enumerate(a) for k in a[i + 1:]), sep='\n') cough Commented Dec 13, 2019 at 8:05
  • Pythonic way ! <3 @deceze Commented Dec 13, 2019 at 8:08

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

This solution is much more pythonic (although your indentationis off on your print statement).
Thx, @Alexander, apparently I overlooked several issues because I was in a rush.
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.