3
\$\begingroup\$

I am trying to find the shortest code that generates a full mesh of the elements fed into it in graphviz format e.g. the full mesh of [0, 1, 2] is:

  • 2 -> 0

  • 2 -> 1

  • 1 -> 0

I have the code below and I think there might be a way to combine the if and for loops, and avoid needing to directly create the empty string

def graph(l):
 if not l:
 return ""
 i = l.pop()
 out = ""
 for z in l:
 out += " {}->{}\n".format(i, z)
 return out + graph(l)
print graph(range(3))
Mathieu Guindon
75.5k18 gold badges194 silver badges467 bronze badges
asked Aug 18, 2016 at 18:03
\$\endgroup\$
2
  • \$\begingroup\$ Did you hear about meshpy ? Does it help you ? \$\endgroup\$ Commented Aug 18, 2016 at 18:11
  • \$\begingroup\$ I'm not trying to generate a mesh in the model sense but a mesh in the network topology sense where every node is connected to every other node, mostly I want to see how mutch smaller I can make the code \$\endgroup\$ Commented Aug 18, 2016 at 18:13

1 Answer 1

4
\$\begingroup\$

If I get it correctly, the shortest way that I can think of is by using itertools.combinations. Basically, you want all unique combinations, so:

from itertools import combinations
def mesh(L):
 return ["->".join(map(str, comb)) for comb in combinations(L, 2)]

Which will return:

['1->2', '1->3', '2->3']

For: mesh([1, 2, 3])

If you then want to print them as above, just:

for x in mesh([1, 2, 3]):
 print(x)
answered Aug 18, 2016 at 18:26
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.