3

I have a really really simple question that I struggle with :)

I need to iterate over list of truples in means of lower triangle matrix in python


python code

dataset = #list of truples

for i, left in enumerate(dataset):
  for j, right in enumerate(dataset):
    if j <= i : continue    #fixme there should be a better way
    foo(left,right)

target pseudo code

for( i=0; i<size; i++ )
  for( j=i; j<size; j++ )
    foo(data[i],data[j])

Thank you very very much :)

2
  • Your target pseudo code looks very "C like". Commented Dec 27, 2013 at 21:36
  • I'm a "language surfer" and yup many times I use C and Java. So my notion of "pseudo coding" is bias. Thank you for pointing that out :) Commented Dec 28, 2013 at 8:17

2 Answers 2

5

Based on the pseudo code this should be something like this:

for i in range(0, len(data)):   
  for j in range(i, len(data)):
    foo(data[i],data[j])

also u can do it with one liner:

[foo(data[i],data[j]) for i in range(0, len(data)) for j in range(i, len(data)]
Sign up to request clarification or add additional context in comments.

Comments

0

This is a good place to use itertools.

import itertools

for (left,right) in itertools.combinations(data,2):
    foo(left,right)

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.