[Python] I can't understand differences between codes :( [closed]

Discussão em 'Python' iniciado por Stack, Novembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I have an exam and it includes a task, that requires writing an algorithm DBscan for finding clusters and their centroids by data in file (file with two columns X and Y). I cant understand why this two codes working different. The first code

    s = open('name_of_file.txt')
    s.readline()
    data = []
    for p in s:
    p = p.replace(',', '.')
    r = [float(i) for i in p.split()]
    data.append(r)

    print(len(data))
    def dist(p1, p2):
    x1, y1, x2, y2 = *p1, *p2
    return ((x2 - x1)**2 + (y2 - y1)**2)**0.5

    def getCluster(p0):
    cluster = [p for p in data if dist(p0, p) < 1]
    if len(cluster) > 0:
    for p in cluster: data.remove(p)
    next_cluster = [getCluster(p) for p in cluster]
    for c in next_cluster: cluster.extend(c)
    return cluster

    clusters = []
    while len(data) > 0:
    p0 = data.pop()
    cluster = [p0] + getCluster(p0)
    print(len(cluster), print(cluster[:15]))
    clusters.append(cluster)

    def center(kl):
    m = []
    for p in kl:
    s = sum(dist(p, p0) for p0 in kl)
    m.append([s, p])
    return min(m)[1]

    centers = [center(c) for c in clusters]


    The second code is almost the same, only part of the "getCluster" function is different

    def getCluster(p0):
    cluster = [p for p in data if dist(p0, p) < 1]
    if len(cluster) > 0:
    for p in cluster: data.remove(p)
    next_cluster = [getCluster(p) for p in cluster]
    cluster.extend(next_cluster) #this is it
    return cluster


    I try to google this problem, but i dont find smth for me.

    Continue reading...

Compartilhe esta Página