Example #1
0
def uppgift2():
    # Problem vid ordnad lista. Blanda före insättning.
    wordList = open('15wordu.txt', 'rt', encoding='utf8').read().split();
    tree = Bintree();
    for word in wordList:
        tree.put(word);
    print('Trädets höjd är', tree.height());
Example #2
0
def search(startWord, endWord):
    quene = Queue()
    tree = Bintree()
    father = WordNode(None, startWord)
    child = WordNode()

    quene.put(father)
    tree.put(father)

    while not quene.isempty():
        word = quene.get()
        if word.getWord() == endWord:
            child = word
            break
        else:
            children = generateChildren(word)
            for kid in children:
                if tree.put(kid):
                    quene.put(kid)

    if not child.getWord() == None:
        path = []
        while not child.getFather() == None:
            path += [child.getWord()]
            child = child.getFather()
        path += [father.getWord()]

        path.reverse()
        print('Väg mellan', startWord, 'och', endWord)
        for item in path:
            print(item + ' -> ')
    else:
        raise Exception('No path found')
Example #3
0
 def test_putta_nar_ej_tom_med_varde_storre_an_rotens(self):
     svenska = Bintree()
     svenska.put(1)
     svenska.put(3)
     svenska.put(4)
     svenska.put(5)
     self.assertEqual(5, svenska.root.right.right.right.value)
Example #4
0
def generateChildren(wordNodeFather):
    tree = Bintree()
    father = wordNodeFather.getWord()
    for i in range(0, len(father)):  #for every letter in father
        for j in range(0, len(letters)):
            possibleWord = father[:i] + letters[j] + father[i + 1:]
            if wordTree.exists(possibleWord) and not possibleWord == father:
                tree.put(WordNode(wordNodeFather, possibleWord))
    return tree.getTree()
Example #5
0
def uppgift4():
    wordList = open('word3u.txt', 'rt', encoding='utf8').read().split();
    wordListEngInput = open('englishu.txt', 'rt', encoding='utf8').read().split();
    tree = Bintree();
    treeEng = Bintree();
    for word in wordList:
        tree.put(word);
    for word in wordListEngInput:
        word = word.strip('".!?, ').lower();
        if (tree.exists(word) and treeEng.put(word)):
            print(word);


        
        
            
Example #6
0
File: uppg2.py Project: MaxKrog/KTH
from Bintree import Bintree

tree = Bintree()

f = open("word3.txt","r")
lines = f.readlines()

for line in lines:
	line = line.rstrip("\n")
	if tree.exists(line):
		print(line)
	else:
		tree.put(line)

#tree.write()
Example #7
0
from Bintree import Bintree

tree = Bintree()

f = open("word3.txt", "r")
lines = f.readlines()

for line in lines:
    line = line.rstrip("\n")
    if tree.exists(line):
        print(line)
    else:
        tree.put(line)

#tree.write()
Example #8
0
from Bintree import Bintree

svenska = Bintree()
engelska = Bintree()
with open("word3.txt", "r", encoding = "utf-8") as svenskfil:
    for rad in svenskfil:
        ordet = rad.strip()                # Ett trebokstavsord per rad
        if ordet in svenska:
            print(ordet, end = " ") 
        else:
            svenska.put(ordet)             # in i sökträdet
with open("engelska.txt", "r", encoding = "utf-8") as engfil:
    for row in engfil:
        for word in row.split():
            if word in engelska:
                pass
            elif word in svenska:
                engelska.put(word)
                print(word, end=" ")
print("\n")
Example #9
0
from Bintree import Bintree

sweTree = Bintree()
engTree = Bintree()

#Read the swedish words
sweFile = open("word3.txt", "r")
sweLines = sweFile.readlines()

#Insert them into a BST
for line in sweLines:
    line = line.rstrip("\n")
    if sweTree.exists(line):
        print(line)
    else:
        sweTree.put(line)

#Read english words
engFile = open("engelska.txt", "r")
engLines = engFile.readlines()

for line in engLines:
    line = line.rstrip("\n")
    line = line.split(" ")
    for word in line:
        if word == "":  #That's not much of a word is it?
            pass
        else:
            if engTree.exists(word):  #It's allready been inserted
                pass
            else:
Example #10
0
File: uppg3.py Project: MaxKrog/KTH
from Bintree import Bintree

sweTree = Bintree()
engTree = Bintree()

#Read the swedish words
sweFile = open("word3.txt","r")
sweLines = sweFile.readlines()

#Insert them into a BST
for line in sweLines:
	line = line.rstrip("\n")
	if sweTree.exists(line):
		print(line)
	else:
		sweTree.put(line)

#Read english words
engFile = open("engelska.txt","r")
engLines = engFile.readlines()

for line in engLines:
	line = line.rstrip("\n")
	line = line.split(" ")
	for word in line:
		if word == "": 					#That's not much of a word is it?
			pass
		else:
			if engTree.exists(word): 	#It's allready been inserted
				pass
			else:
Example #11
0
from Bintree import Bintree

wordTree = Bintree()
reversedTree = Bintree() #BST for printed reversed words.

f = open("word3.txt","r")
lines = f.readlines()


for line in lines:
	line = line.rstrip("\n")
	if not wordTree.exists(line):
		wordTree.put(line)
print("This app find words that are the same when reversed!")
input("Press enter to continue:")

for line in lines:
	line = line.rstrip("\n")
	reversedLine = line[::-1] 				#Reverses the string
	if not line == reversedLine: 			#Gets rid of symmetric words
		if not reversedTree.exists(line): 	#Storage of allready shown reversed words. Do this before other search since it's quicker.
			if wordTree.exists(reversedLine): 
				print(line)
				print(line[::-1])
				print()
				reversedTree.put(line)
Example #12
0
from Bintree import Bintree
import random
import time

tree = Bintree()

print("This program compares search-time between linear search and BST-search")
totalEntries = int(
    input("Please enter how many total entries there should be : "))

numberArray = [x for x in range(totalEntries)]
random.shuffle(numberArray)  #Randomizes the array.

for number in numberArray:  #Puts all the numbers into the binary-tree
    tree.put(number)

numberToFind = int(random.random() * totalEntries //
                   1)  #Make up a random number in the right interval.

print("\nLooking for number " + str(numberToFind) +
      " in shuffled intervall 0 - " + str(totalEntries) + "\n")

startTime = time.clock()
tree.exists(numberToFind)  #BST-SEARCH PROCESS
treeStop = time.clock()  #Time until BinarySearch was completed.

linStop = None  #Allocate memory

for number in numberArray:  #LINEAR-SEARCH PROCESS
    if number == numberToFind:
        linStop = time.clock(
Example #13
0
from Bintree import Bintree
import random
import time

tree = Bintree()

print("This program compares search-time between linear search and BST-search")
totalEntries = int(input("Please enter how many total entries there should be : "))

numberArray = [x for x in range(totalEntries)] 
random.shuffle(numberArray) 				#Randomizes the array.

for number in numberArray: 				#Puts all the numbers into the binary-tree
	tree.put(number)

numberToFind = int(random.random() * totalEntries // 1) #Make up a random number in the right interval.

print("\nLooking for number " + str(numberToFind)+" in shuffled intervall 0 - " + str(totalEntries) + "\n")

startTime = time.clock()
tree.exists(numberToFind) #BST-SEARCH PROCESS
treeStop = time.clock() #Time until BinarySearch was completed.

linStop = None #Allocate memory

for number in numberArray: #LINEAR-SEARCH PROCESS
	if number == numberToFind:
		linStop = time.clock() #If this goes through the number is found. Stop time.
		break

#Actual time consumed calculated below
Example #14
0
 def test_putta_nar_tom(self):
     svenska = Bintree()
     svenska.put(1)
     self.assertEqual(1, svenska.root.value)
Example #15
0
 def test_finns_med_givna_varden(self):
     svenska = Bintree()
     svenska.put(1)
     self.assertEqual(True, svenska.__contains__(1))
Example #16
0
        if not isinstance(other, WordNode): return False
        return self.getWord() < other.getWord()

    def __gt__(self, other):
        if not isinstance(other, WordNode): return False
        return self.getWord() > other.getWord()

    def __eq__(self, other):
        if not isinstance(other, WordNode): return False
        return self.getWord() == other.getWord()


wordList = open('word3u.txt', 'rt', encoding='utf8').read().split()
letters = 'abcdefghijklmnopqrstuvwxyzåäö'

wordTree = Bintree()
for word in wordList:
    wordTree.put(word)


def generateChildren(wordNodeFather):
    tree = Bintree()
    father = wordNodeFather.getWord()
    for i in range(0, len(father)):  #for every letter in father
        for j in range(0, len(letters)):
            possibleWord = father[:i] + letters[j] + father[i + 1:]
            if wordTree.exists(possibleWord) and not possibleWord == father:
                tree.put(WordNode(wordNodeFather, possibleWord))
    return tree.getTree()

Example #17
0
def uppgift3():
    wordList = open('word3u.txt', 'rt', encoding='utf8').read().split();
    tree = Bintree();
    for word in wordList:
        if not tree.put(word):
            print(word);
Example #18
0
 def test_putta_nar_ej_tom_med_varde_mindre_an_rotens(self):
     svenska = Bintree()
     svenska.put(3)
     svenska.put(2)
     self.assertEqual(2, svenska.root.left.value)