HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Shortest code to generate a full mesh of elements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fullshortestelementsmeshgeneratecode

Problem

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))

Solution

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)

Code Snippets

from itertools import combinations

def mesh(L):
    return ["->".join(map(str, comb)) for comb in combinations(L, 2)]
['1->2', '1->3', '2->3']
for x in mesh([1, 2, 3]):
    print(x)

Context

StackExchange Code Review Q#139072, answer score: 4

Revisions (0)

No revisions yet.