0

consider

a = [1,2,3,4]

i = 0

j = 1

for i in range(len(a)):

       for j in range(len(a)):

          d = (a[i]-a[j])
          j = j + 1
          print i, j, d
       i = i + 1

Output

0 1 0

0 2 -1 

0 3 -2

0 4 -3

1 1 1

1 2 0

1 3 -1

1 4 -2

2 1 2

2 2 1

2 3 0

2 4 -1

3 1 3

3 2 2

3 3 1

3 4 0

I am trying to iterate through my array so that I can only get numbers that are non-zero for d and that I do not go over the same i and j (ex: if i = 0,j=1 or i=1, j=0). Its just like doing a combination problem for which I am looking the number of pairs in my array and the d that goes for it.

2
  • Do you have a question? Commented Feb 21, 2013 at 18:14
  • 1
    Also, i=0 and j=0 doesn't do anything. Iterating through the for i in range(len(a)) starts out i as 0. And iterating for j in range(len(a)) starts j as 0. To iterate from j=1 to len(a), do: for j in range(1, len(a)). Commented Feb 21, 2013 at 18:20

3 Answers 3

1

I am trying to iterate through my array so that I can only get numbers that are non-zero for d

Unless this is a home work I would advise you to use itertools.combinations with a reverse sorted list or itertools.permutations for your problem

>>> list((a,b) for a,b in itertools.permutations(a, 2) if a > b)
[(2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
>>> list(itertools.combinations(sorted(a, reverse = True), 2))
[(4, 3), (4, 2), (4, 1), (3, 2), (3, 1), (2, 1)]
Sign up to request clarification or add additional context in comments.

Comments

1

Just use permutations from itertools:

import itertools
a = [1,2,3,4]
for permutation in itertools.permutation(a, 2):
    print permutation

outputs

(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
...
...

If you also want the distances you can do

a = [1,2,3,4]
for permutation in itertools.permutation(a, 2):
    print permutation, permutation[1] - permutation[0]

(1, 2) 1
(1, 3) 2
(1, 4) 3
(2, 1) -1

1 Comment

Thanks! Actually using combinations from itertools was precisely what I was looking for. This led me to it though.
0

Try this:

a = [1,2,3,4]

i = 0

j = 1

for i in range(len(a)):

    for j in range(len(a)):

        d = (a[i]-a[j])
        j = j + 1
        if i != j and d != 0:
            print i, j, d
    i = i + 1

Output:

>>> 
0 2 -1
0 3 -2
0 4 -3
1 3 -1
1 4 -2
2 1 2
2 4 -1
3 1 3
3 2 2

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.