1

Say I specified the number of keys to be 5 (so that the keys are 0,1,2,3, and 4 etc.) and I wanted the number of values to be random per key, where each value is 0,1,2,3, or 4, with no repeated values in each key. I am trying to make a Random Complete Graph if that means anything to you. Ex of output:

dict = { "0": ["3"],
         "1": ["4"],
         "2": ["3","4"],
         "3": ["0","2"],
         "4": ["1","2"]
       }
Jason M Gray
  • 161
  • 1
  • 5

2 Answers2

2
import random

number_of_nodes = 5
graph = dict()

for i in range(number_of_nodes):
    graph[i] = random.sample(range(0, number_of_nodes), random.randint(0, number_of_nodes))
mohammad
  • 2,232
  • 1
  • 18
  • 38
0

You can try creating the dictionary from two lists, keys, which are your integers from 0 to 4, and values, which are random picks (random.choice(seq)) from a list containing every possible combination(of any length) of your numbers, and that's exactly what the initials for loops are there(check this answer). Notice the final dictionary's values are tuples, it's not hard to output them the way you need changing the code from here on. Also notice that since we already are importing itertools the construction of the dictionary can be coded using dict(itertools.izip(keys,values)), and that seems to be a more economical approach in a big lists scenario.

import random
import itertools

n = 5
keys = range(n)
numbers = [0,1,2,3,4] #or simply numbers = range(n), if that's what you need
values = []
possibleValues = []

for L in range(0, len(numbers)+1):
  for subset in itertools.combinations(numbers, L):
    possibleValues.append(subset)

for i in range(len(numbers)):
    values.append(random.choice(possibleValues))

dictionary = dict(zip(keys, values))
Community
  • 1
  • 1
Vinícius Figueiredo
  • 6,300
  • 3
  • 25
  • 44