mardi 27 décembre 2016

why do I get same results directly within same run in second time without run random function in it in python?

English is not my mother language, I'm sorry if I make some mistakes.

Can anybody help me? I write a KargerMinCut function in which I have written a random function in python, but I get the same result within the same run. If I restart the function, different results printed.

Here is the output:

enter image description here

In this image, when I first use this KargerMinCut function, I get random integers highlighted with red, but I directly get the answer in the second usage. Why should this KargerMinCut function recalculate again to get different random integers? When I restart this KargerMinCut function, it does recalculate again.

here's the code

import random

with open('test.txt') as f:
    #kargerMinCut
    #a = [[int(x) for x in ln.split()] for ln in f]
    data_set = []
    for ln in f:
        line = ln.split()
        if line:
            a = [int(x) for x in line]
            data_set.append(a)

def choose_random_edge(data):
    a = random.randint(0,len(data)-1)
    b = random.randint(1,len(data[a])-1)
    return a,b

def compute_nodes(data):
    data_head = []
    for i in xrange(len(data)):
        data_head.append(data[i][0])
    return data_head

def find_index(data_head,data,u,v):
    index = data_head.index(data[u][v])
    return index

def replace(data_head,data,index,u):
    for i in data[index][1:]:
        index_index = data_head.index(i)
        for position,value in enumerate(data[index_index]):
            if value == data[index][0]:
                data[index_index][position] = data[u][0]
    return data

def merge(data):
    u,v = choose_random_edge(data)
    print u,v
    data_head = compute_nodes(data)
    index = find_index(data_head,data,u,v)
    data[u].extend(data[index][1:])
    #print data
    data = replace(data_head,data,index,u)
    #print data
    data[u][1:] = [x for x in data[u][1:] if x!=data[u][0]]
    #print data
    data.remove(data[index])
    #print data
    return data

def KargerMinCut(data):
        while len(data) >2:
            data = merge(data)
            #print data
        num = len(data[0][1:])
        print num

#KargerMinCut(data_set)

here's test.txt

1 2 3 4 7

2 1 3 4

3 1 2 4

4 1 2 3 5

5 4 6 7 8

6 5 7 8

7 1 5 6 8

8 5 6 7

Does it exist some cache? It costs me 1 hour, can anyone help me?




Aucun commentaire:

Enregistrer un commentaire