Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PIL import Image, ImageFilter, ImageDraw, ImageFont
- from math import *
- def gen_graph(g, w, h):
- n = len(g)
- white = (255, 255, 255)
- black = (0, 0, 0)
- green = (0, 255, 0)
- img = Image.new('RGB', (w, h), white)
- arr = img.load()
- circle_size = 40
- circle = (0, 0, 40, 40)
- pts = []
- pi = acos(-1)
- for i in range(n):
- x = cos(2 * pi * i / n)
- y = sin(2 * pi * i / n)
- lenx = (w - circle_size) / 2
- x *= lenx
- leny = (h - circle_size) / 2
- y *= leny
- x += w / 2
- y += h / 2
- pts.append((int(x),int(y)))
- draw = ImageDraw.Draw(img)
- print('ok')
- for v in range(n):
- for u in g[v]:
- if type(u) == type(1):
- draw.line([pts[v], pts[u]], fill=black, width=3)
- x, y = pts[u]
- dx = pts[v][0] - pts[u][0]
- dy = pts[v][1] - pts[u][1]
- l = (dx * dx + dy * dy) ** 0.5
- if l == 0:
- continue
- dx /= l
- dy /= l
- K = circle_size / 2
- x += dx * K
- y += dy * K
- sz = 5
- draw.rectangle([x-sz, y-sz, x+sz, y+sz], fill=green, outline=black)
- elif type(u) == type((1,1)):
- w = u[1]
- u = u[0]
- draw.line([pts[v], pts[u]], fill=black, width=3)
- coord = ((pts[v][0] + pts[u][0]) // 2 + 15, (pts[v][1] + pts[u][1]) // 2)
- draw.text(coord, str(w), font=ImageFont.load_default(), fill=black)
- x, y = pts[u]
- dx = pts[v][0] - pts[u][0]
- dy = pts[v][1] - pts[u][1]
- l = (dx * dx + dy * dy) ** 0.5
- if l == 0:
- continue
- dx /= l
- dy /= l
- K = circle_size / 2
- x += dx * K
- y += dy * K
- sz = 5
- draw.rectangle([x-sz, y-sz, x+sz, y+sz], fill=green, outline=black)
- else:
- continue
- index = 0
- for (x, y) in pts:
- index += 1
- x1, y1, x2, y2 = circle
- draw.ellipse([x + x1 - circle_size // 2,
- y + y1 - circle_size // 2,
- x + x2 - circle_size // 2,
- y + y2 - circle_size // 2
- ], fill=white, outline=black)
- draw.text((x, y), str(index), font=ImageFont.load_default(), fill=black)
- img.show()
- def parse_graph(n, s):
- g = [[] for _ in range(n)]
- s = s.split('\n')
- for edge in s:
- if len(edge) == 0:
- continue
- edge = list(map(int, edge.split()))
- f = edge[0] - 1
- t = edge[1] - 1
- if len(edge) == 3:
- w = edge[2]
- g[f].append((t, w))
- else:
- g[f].append(t)
- return g
- s = """1 2 10
- 2 3 5
- 1 3 100
- 3 5 7
- 5 4 10
- 4 3 -18
- 6 1 -1"""
- graph = parse_graph(6, s)
- gen_graph(graph, 500, 500)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement