コード例 #1
0
ファイル: test_prufer.py プロジェクト: Abhityagi16/sympy
def test_prufer():
    # number of nodes is optional
    assert Prufer([[0, 1], [0, 2], [0, 3], [0, 4]], 5).nodes == 5
    assert Prufer([[0, 1], [0, 2], [0, 3], [0, 4]]).nodes == 5

    a = Prufer([[0, 1], [0, 2], [0, 3], [0, 4]])
    assert a.rank == 0
    assert a.nodes == 5
    assert a.prufer_repr == [0, 0, 0]

    a = Prufer([[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]])
    assert a.rank == 924
    assert a.nodes == 6
    assert a.tree_repr == [[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]]
    assert a.prufer_repr == [4, 1, 4, 0]

    assert Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) == \
        ([[0, 1], [1, 2], [4, 6], [4, 5], [1, 4], [2, 3]], 7)
    assert Prufer([0]*4).size == Prufer([6]*4).size == 1296

    # accept iterables but convert to list of lists
    tree = [(0, 1), (1, 5), (0, 3), (0, 2), (2, 6), (4, 7), (2, 4)]
    Prufer(tree).tree_repr == tree
    Prufer(set(tree)).tree_repr == tree

    raises(ValueError, lambda: Prufer([[1, 2], [3, 4]]))  # 0 is missing
    assert Prufer(*Prufer.edges([1, 2], [3, 4])).prufer_repr == [1, 3]
    raises(ValueError, lambda: Prufer.edges(
        [1, 3], [3, 4]))  # a broken tree but edges doesn't care
    raises(ValueError, lambda: Prufer.edges([1, 2], [5, 6]))
コード例 #2
0
 def doit(t, b):
     e, n = Prufer.edges(*t)
     t = Prufer(e, n)
     a = sorted(t.tree_repr)
     b = [i - 1 for i in b]
     assert t.prufer_repr == b
     assert sorted(Prufer(b).tree_repr) == a
     assert Prufer.unrank(t.rank, n).prufer_repr == b
コード例 #3
0
ファイル: test_prufer.py プロジェクト: asmeurer/sympy
 def doit(t, b):
     e, n = Prufer.edges(*t)
     t = Prufer(e, n)
     a = sorted(t.tree_repr)
     b = [i - 1 for i in b]
     assert t.prufer_repr == b
     assert sorted(Prufer(b).tree_repr) == a
     assert Prufer.unrank(t.rank, n).prufer_repr == b
コード例 #4
0
ファイル: test_prufer.py プロジェクト: tomtwohats/sympy
def test_prufer():
    a = Prufer([[0, 1], [0, 2], [0, 3], [0, 4]], 5)
    assert a.rank == 0
    assert a.nodes == 5
    assert a.prufer_repr == [0, 0, 0]

    a = Prufer([[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]], 6)
    assert a.rank == 1008
    assert a.nodes == 6
    assert a.tree_repr == [[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]]
    assert a.prufer_repr == [4, 4, 0, 0]
コード例 #5
0
ファイル: test_args.py プロジェクト: Visheshk/sympy
def test_sympy__combinatorics__prufer__Prufer():
    from sympy.combinatorics.prufer import Prufer
    assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4))
コード例 #6
0
def test_prufer():
    # number of nodes is optional
    assert Prufer([[0, 1], [0, 2], [0, 3], [0, 4]], 5).nodes == 5
    assert Prufer([[0, 1], [0, 2], [0, 3], [0, 4]]).nodes == 5

    a = Prufer([[0, 1], [0, 2], [0, 3], [0, 4]])
    assert a.rank == 0
    assert a.nodes == 5
    assert a.prufer_repr == [0, 0, 0]

    a = Prufer([[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]])
    assert a.rank == 924
    assert a.nodes == 6
    assert a.tree_repr == [[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]]
    assert a.prufer_repr == [4, 1, 4, 0]

    assert Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) == \
        ([[0, 1], [1, 2], [1, 4], [2, 3], [4, 5], [4, 6]], 7)
    assert Prufer([0] * 4).size == Prufer([6] * 4).size == 1296

    # accept iterables but convert to list of lists
    tree = [(0, 1), (1, 5), (0, 3), (0, 2), (2, 6), (4, 7), (2, 4)]
    tree_lists = [list(t) for t in tree]
    assert Prufer(tree).tree_repr == tree_lists
    assert sorted(Prufer(set(tree)).tree_repr) == sorted(tree_lists)

    raises(ValueError, lambda: Prufer([[1, 2], [3, 4]]))  # 0 is missing
    raises(ValueError, lambda: Prufer([[2, 3], [3, 4]]))  # 0, 1 are missing
    assert Prufer(*Prufer.edges([1, 2], [3, 4])).prufer_repr == [1, 3]
    raises(ValueError, lambda: Prufer.edges([1, 3], [3, 4])
           )  # a broken tree but edges doesn't care
    raises(ValueError, lambda: Prufer.edges([1, 2], [5, 6]))
    raises(ValueError, lambda: Prufer([[]]))

    a = Prufer([[0, 1], [0, 2], [0, 3]])
    b = a.next()
    assert b.tree_repr == [[0, 2], [0, 1], [1, 3]]
    assert b.rank == 1
コード例 #7
0
def program():
    j = 0
    option = input(
        "Wpisz opcję(1 - Drzewo Huffmana + Kodowanie Prufera lub 2 - Dekodowanie Prufera lub 3 - Wyjście): "
    )
    if option == "1":
        while True:
            fileWithInputData = input("Plik z tekstem wejściowym: ")
            if os.path.exists(fileWithInputData):
                file_object = open(fileWithInputData, "r")
                break
            else:
                print("Plik nie istnieje, podaj inną scieżkę!")
                continue
        word = file_object.read()
        dictionary = {}
        for c in word:
            if (c in dictionary):
                dictionary[c] += 1
            else:
                dictionary[c] = 1

        code, tree = Huffman_code(dictionary)

        nameOfGraphFile = input(
            "Ścieżka do grafu wyjściowego - bez rozszerzenia: ")
        set_globvar_to_zero()
        with open(nameOfGraphFile + ".dot", 'w') as f:
            f.write('digraph G {\n')
            f.write(draw_tree(tree, 0))
            f.write('}')
        subprocess.call('dot -Tpng ' + nameOfGraphFile + '.dot -o ' +
                        nameOfGraphFile + '.png',
                        shell=True)
        j = 0
        a = Prufer.to_prufer(graphStructure, len(graphStructure) + 1)

        nameOfFile = input("Ścieżka do pliku wyjsciowego: ")
        file = open(nameOfFile, "w")
        first = "0"
        second = ""
        third = ""
        for x in a:
            second = second + str(x) + " "
        for c in listValue:
            third = third + str(c) + " "
        lines = [first, "\n", second, "\n", third]
        file.writelines(lines)
        file.close()
        f = Image.open(nameOfGraphFile + ".png").show()
        program()
    elif option == "2":
        while True:
            fileWithInputDataMode2 = input(
                "Ścieżka do pliku z kodem Prufera: ")
            if os.path.exists(fileWithInputDataMode2):
                file_object = open(fileWithInputDataMode2, "r")
                break
            else:
                print("Plik nie istnieje, podaj inną scieżkę!")
                continue
        pruferVert = []
        pruferLet = []

        for i, line in enumerate(file_object):
            if i == 1:
                pruferNumbers = line.split(" ")
                for z in pruferNumbers:
                    pruferVert.append(z)
            elif i == 2:
                pruferLetters = line.split(" ")
                for z in pruferLetters:
                    pruferLet.append(z)
            elif i > 2:
                break

        for line in pruferVert:
            if line == " " or line == '\n':
                pruferVert.remove(line)
        for line in pruferLetters:
            if line == " " or line == '\n' or line == '':
                pruferLetters.remove(line)
        #print(pruferLetters)
        #print(pruferVert)
        Prufer_list = [int(i) for i in pruferVert]
        firstPrufferLetter = pruferLetters[0]
        a = Prufer.to_tree(Prufer_list)
        newStr = "digraph G {\n"
        numberLetterDictionary = []
        for x in a:
            numberLetterDictionary.append(str(x[0]))
        for x in a:
            newStr += str(x[0]) + " -> "
            newStr += str(x[1]) + "\n"
            if str(x[1]) not in numberLetterDictionary:
                newStr += '%s [label="%s %s", fontsize=16, fontcolor=blue, width=2, shape=box];\n' % (
                    str(x[1]), str(x[1]), firstPrufferLetter) + "\n"
                try:
                    pruferLetters.pop(0)
                    firstPrufferLetter = pruferLetters[0]
                except IndexError:
                    pass
        newStr += "}"
        nameOfGraphFilePrufer = input(
            "Podaj sciezke gdzie ma powstac graf - bez rozszerzenia: ")
        with open(nameOfGraphFilePrufer + ".dot", 'w') as f:
            f.write(newStr)
        subprocess.call('dot -Tpng ' + nameOfGraphFilePrufer + '.dot -o ' +
                        nameOfGraphFilePrufer + '.png',
                        shell=True)
        f = Image.open(nameOfGraphFilePrufer + ".png").show()
        program()
    elif option == "3":
        sys.exit()
    else:
        print("Coś poszło nie tak, proszę wybrać 1,2 lub 3")
        program()
コード例 #8
0
ファイル: ProjektGrafy.py プロジェクト: nowilus/pythonGrafy
def menu(modeOption):
    if modeOption == "1":
        while True:
            fileWithInputDataForMode1 = input("Podaj scieżkę do pliku z tekstem wejsciowym: ") 
            if os.path.exists(fileWithInputDataForMode1):   
                file_object  = open(fileWithInputDataForMode1, "r")
                print("\n# =====================================================")
                print("#            Wybrałeś plik: " +os.path.basename(fileWithInputDataForMode1))
                print("# =====================================================\n")
                break
            else:
                print ("Plik "+ os.path.basename(fileWithInputDataForMode1)+" nie istnieje, podaj inną scieżkę!")
                continue
        readFromFile = file_object.read()
        codes = {}
        for z in readFromFile:
            if z == "\n":
                z = " "
            if( z in codes):
                codes[z] += 1
            else:
                codes[z] = 1

        code, tree = Huffman_code(codes)

        nameOfGraphFileForMode1 = input("Podaj sciezke w której ma powstać graf(no extension): ")
        print("\n# =====================================================")
        print("#        Graf powstał w pliku: " +os.path.basename(nameOfGraphFileForMode1) + ".jpeg")
        print("# =====================================================\n")        
        with open(nameOfGraphFileForMode1 + ".dot",'w') as f:
            f.write('digraph G {\n')
            f.write(draw_tree(tree, 0))
            f.write('}')   
        subprocess.call('dot -Tjpeg '+nameOfGraphFileForMode1+'.dot -o '+nameOfGraphFileForMode1+'.jpeg', shell=True)

        a = Prufer.to_prufer(listOfEdges,len(listOfEdges)+1)

        fileWithOutputDataForMode1 = input("Podaj sciezke do pliku wyjściowego: ")
        print("\n# =====================================================")
        print("#        Powstały plik wyjściowy to: " +os.path.basename(fileWithOutputDataForMode1))
        print("# =====================================================\n") 
        outputFileForMode1 = open(fileWithOutputDataForMode1, "w")
        firstLine = "0"
        secondLine = ""
        thirdLine = ""
        for x in a:
            secondLine = secondLine + str(x) + " "
        for c in listValue:  
            thirdLine = thirdLine + str(c) + " "
        lines = [firstLine,"\n",secondLine,"\n",thirdLine]    
        outputFileForMode1.writelines(lines)
        outputFileForMode1.close()
        
        with open("tempFile.txt",'wb') as tF:
            pickle.dump(listOfLetters, tF)
        
        f = Image.open(nameOfGraphFileForMode1+".jpeg").show()
        os.system(fileWithOutputDataForMode1) 
        
    elif modeOption == "2":

        while True:
            fileWithInputDataMode2 = input("Podaj ścieżkę do pliku zawierającego kod Prufera: ") 
            if os.path.exists(fileWithInputDataMode2):   
                file_object  = open(fileWithInputDataMode2, "r")
                print("\n# =====================================================")
                print("#            Wybrałeś plik: " +os.path.basename(fileWithInputDataMode2))
                print("# =====================================================\n")
                break
            else:
                print ("Plik "+ os.path.basename(fileWithInputDataMode2)+" nie istnieje, podaj inną scieżkę!")
                continue
                
        pruferVert = []
        
        for a, b in enumerate(file_object):
            if a == 1:
                c = b.split(" ")
                for d in c:
                    pruferVert.append(d)
            elif a > 1:
                break
                
        for x in pruferVert:
            if x == " " or x == '\n':
                pruferVert.remove(x)
                
        while True:
            try:
                Prufer_list = [int(i) for i in pruferVert]
                break
            except ValueError:
                print ("Oops! Zły format pliku wejściowego "+ os.path.basename(fileWithInputDataMode2)+". Zamykanie programu...")
                sys.exit()
                
        pruferTree = Prufer.to_tree(Prufer_list)

        if os.path.exists('tempFile.txt'):   
            with open ('tempFile.txt', 'rb') as fp:
                itemlist = pickle.load(fp)
        else:
            itemlist={}
        
        newStr = "digraph G {\n"
        for x in pruferTree:
            if itemlist.get(x[0]):
                newStr +='%s [label="%s\n%s", fontcolor=black, fontsize=14];\n'%(str(x[0]), str(x[0]), itemlist.get(x[0]))
            elif itemlist.get(x[1]):
                newStr +='%s [label="%s\n%s", fontcolor=black, fontsize=14];\n'%(str(x[1]), str(x[1]), itemlist.get(x[1]))
            newStr += str(x[0]) + " -> "
            newStr += str(x[1]) + "\n"
        newStr+="}"
        
        nameOfGraphFileMode2= input("Podaj sciezke gdzie ma powstac graf(no extension): ") 
        print("\n# =====================================================")
        print("#        Graf powstał w pliku: " +os.path.basename(nameOfGraphFileMode2) + ".jpeg")
        print("# =====================================================\n")          
        with open(nameOfGraphFileMode2 + ".dot",'w') as f:
            f.write(newStr)   
            
        subprocess.call('dot -Tjpeg '+nameOfGraphFileMode2+'.dot -o '+nameOfGraphFileMode2+'.jpeg', shell=True)
        f = Image.open(nameOfGraphFileMode2+".jpeg").show()

    elif modeOption == '3':
        os.system('cls')
        sys.exit()
        
    else:
        print("\n# =====================================================")
        print("#                        BŁĄD")
        print("#            PODAJ POPRAWNĄ WARTOŚĆ Z MENU")
        print("# =====================================================\n")
        print("1. Kodowanie na podstawie gotowego pliku tekstowego ")
        print("2. Dekodowanie na podstawie pliku z kodem Prufera")
        print("3. Zamknij program\n")
        print("# =====================================================\n")
        newVal = input(">> ")
        menu(newVal)