from sys import argv from sys import exit from random import randint ### # Dictionary format: { key: [(city, cost), ... ] } ### def readfile(hashtable,filename): s=open(filename).read().split('\n')[:-1] for edge in s: a,b,c=edge.split(',') a,b=a[1:-1],b[1:-1] register(hashtable,a,b,int(c)) register(hashtable,b,a,int(c)) def register(hashtable,key,value,cost): if key in hashtable: hashtable[key].append((value, cost)) else: hashtable[key]=[(value, cost)] def search(d): cost = 0 start = d.keys()[randint(0, len(d)-1)] path = [start] length = randint(1, len(d)) for k in range(length): last = path[-1] poss = [k for k in d[last] if k[0] not in path] if len(poss) <= 0: break next = poss[randint(0, len(poss)-1)] path.append(next[0]) cost += next[1] return ",".join(path) + ":" + str(cost) d = {} p = [] readfile(d, 'files/romania2.csv') if len(argv) > 1: count = int(argv[1]) else: print "No argument provided. Please provide the number of paths to be written." exit(0) out = open("files/map.data", "w") k = 0 while k < count: path = search(d) if path not in p: p.append(path) k += 1 out.write("\n".join(p))