diff --git a/README.md b/README.md index 54d5563..2a69f37 100644 --- a/README.md +++ b/README.md @@ -4,43 +4,44 @@ * test1 - finds the kth minimum number in a list * test2 - implements preorder, inorder, and postorder traversal of a binary tree with and without using recursion -* test3 - manipulates a number string by adding a "*" between two consecutive even numbers and "-" between two consecutive odd numbers -* test4 - itermixes two strings after crerating chunks in size n e.g. ABCDEFG and 1234567890 with 2 char chunks -> AB12CD34EF56G7890 -* test5 - finds the common words in two lists -* test6 - demonstrates trying and catching exceptions while getting an a positive integer as an input and printing its square -* test7 - counts the occurrence of each word in a list +* test3 - finds the best time to buy and sell a stock once or unlimited times or fix number of times to make the maximum profit +* test4 - recovers a binary search tree with 2 replaced nodes +* test5 - implements a search typehead +* test6 - implements bubble sort, insertion sort, quick sort, merge sort, and bucket sort algorithms +* test7 - finds the largest rectangle in a histogram * test8 - finds duplicate characters in a string * test9 - determines if two strings are anagram or not * test10 - prints the first non-repeated character from a string * test11 - reverses a string by using recursion -* test12 - checks if a string has all digits -* test13 - reverses words in a paragraph +* test12 - finds the median of an array which is created by merging two sorted arrays +* test13 - implements a simple vending machine * test14 - removes duplicate entries in a list * test15 - checks if 2 strings are rotation of each other -* test16 - reverse words in a given sentence without using any library method +* test16 - reverses words in a given sentence without using any library method * test17 - finds the nth node from the end in a singly linked list * test18 - creates a list with only unique items * test19 - finds all combinations of a string * test20 - checks if a string is a palindrome * test21 - reverses a singly linked list -* test22 - implements a binary tree +* test22 - creates a binary tree iterator * test23 - searches an integer in a presorted integer array which was rotated from an unknown pivot point (array has no duplicates) * test24 - finds the middle node in a linked list in one pass * test25 - prints all leaves of a binary tree -* test26 - implements bubble sort, insertion sort, quick sort, merge sort, and bucket sort algorithms -* test27 - implements a simple vending machine +* test26 - counts the occurrence of each word in a list +* test27 - implements a binary tree * test28 - finds the least common ancestor in a binary search tree * test29 - finds the maximum depth of a binary tree -* test30 - creates a binary tree iterator -* test31 - recovers a binary search tree with 2 replaced nodes +* test30 - returns level order of a binary tree +* test31 - finds the common words in two lists * test32 - finds list of all unique triplets in a list of integers satisfying a+b+c=0 in non-descending order * test33 - reads a text file and creates another text file with the reversed file content * test34 - finds starting position of substrings in a string S where each substring is a combination of all substrings provided in a list L -* test35 - finds the best time to buy and sell a stock once or unlimited times or fix number of times to make the maximum profit -* test36 - finds the largest rectangle in a histogram +* test35 - intermixes two strings after crerating chunks in size n e.g. ABCDEFG and 1234567890 with 2 char chunks -> AB12CD34EF56G7890 +* test36 - reverses words in a paragraph * test37 - finds a, b, c, d values such that A[a]+A[b] = A[c] + A[d] where a < b and c < d and a < c and b != d and b != c * test38 - finds largest distance between nodes of a tree * test39 - finds stepping numbers between two integers e.g. A=10, B=40 output = [10, 12, 21, 23, 32, 34] -* test40 - returns level order of a binary tree -* test41 - implements a search typehead -* test42 - finds the kth minimum number in a list (another version) \ No newline at end of file +* test40 - checks if a string has all digits +* test41 - demonstrates trying and catching exceptions while getting a positive integer as an input and printing its square +* test42 - finds the kth minimum number in a list (another version) +* test43 - manipulates a number string by adding a "*" between two consecutive even numbers and "-" between two consecutive odd numbers \ No newline at end of file diff --git a/test12/.idea/misc.xml b/test12/.idea/misc.xml index c1f6583..65531ca 100644 --- a/test12/.idea/misc.xml +++ b/test12/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test12/.idea/test12.iml b/test12/.idea/test12.iml index 74d515a..d0876a7 100644 --- a/test12/.idea/test12.iml +++ b/test12/.idea/test12.iml @@ -1,9 +1,7 @@ - - - + diff --git a/test12/main.py b/test12/main.py index 09f9e04..7d9f684 100644 --- a/test12/main.py +++ b/test12/main.py @@ -1,4 +1,4 @@ -# check if a string has all digits +# This script finds the median of an array which is created by merging two sorted arrays # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -18,25 +18,171 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # +class median_array(): + def __init__(self, l1, l2): + if(len(l1)>=len(l2)): + self.l1 = l1 + self.l2 = l2 + else: + self.l1 = l2 + self.l2 = l1 -class digitstr(str): - - def __init__(self, astr): - self = astr - - def alldigits(self): - if self == "": return False - else: return(self.checkdig(self)) + self.median = None - def checkdig(self, astr): - if(astr == ""): + def iseven(self, anum): + if anum == (anum >> 1) * 2: + # totlen is even return True - elif(astr[0].isdigit()): - return self.checkdig(astr[1:]) else: return False + def find_median(self): + + med2 = len(self.l2) >> 1 + totlen = len(self.l1)+len(self.l2) + even = self.iseven(totlen) + med = ((totlen+1) >> 1) - 1 + med1 = med - med2 - 1 + soln = sol1 = sol2 = None + + # handle special cases that l1 and l2 has no intersections + if (self.l2[0] >= self.l1[-1]): + soln = sol1 = self.l1[med] + if even: + if med+1 == len(self.l1): + sol2 = self.l2[0] + else: + sol2 = self.l1[med + 1] + soln = (sol1 + sol2) / 2 + + return soln + elif (self.l2[-1]<=self.l1[0]): + if(med < len(self.l2)): + soln = sol1 = self.l2[med] + if even: + sol2 = self.l1[0] + soln = (sol1 + sol2) / 2 + else: + soln = sol1 = self.l1[med - len(self.l2)] + if even: + sol2 = self.l1[med - len(self.l2) + 1] + soln = (sol1 + sol2) / 2 + + return soln + + # print("med1={} med2={} total length={} median={}".format(med1, med2, totlen, med)) + + # set the search area in the shorter array + if self.l1[med1] > self.l2[med2]: + min2 = med2 + max2 = len(self.l2) - 1 + else: + min2 = 0 + max2 = med2 + + while True: + if self.l1[med1] > self.l2[med2]: + # print("med1={} at {} med2={} at {} min2 {} max2 {}". + # format(self.l1[med1], med1, self.l2[med2], med2, min2, max2)) + if(self.l1[med1] < self.l2[med2+1]): + # we found the median or exhausted one of the arrays + break + min2 = med2+1 + if (min2 > max2): + # we hit the max or min of l2 + break + move = (max2 - min2) + 1 >> 1 + # print("move={}".format(move)) + med1 -= move + med2 += move + elif self.l1[med1] < self.l2[med2]: + # print("med1={} at {} med2={} at {} min2 {} max2 {}". + # format(self.l1[med1], med1, self.l2[med2], med2, min2, max2)) + if(self.l1[med1+1] > self.l2[med2]): + # we found the median or exhausted one of the arrays + break + max2 = med2-1 + if (min2 > max2): + # we hit the max or min of l2 + break + move = (max2 - min2) + 1 >> 1 + # print("move={}".format(move)) + med1 += move + med2 -= move + else: + # we found the median + break + + # we exhausted all items in array 2 + # search for solution in array 1 + if self.l2[med2] >= self.l1[med1]: + sol1 = self.l2[med2] + else: + sol1 = self.l1[med1] + soln = sol1 + # print ("solution1 is {} ".format(sol1)) + + if even: + if med2+1 < len(self.l2) and self.l2[med2 + 1] < self.l1[med1 + 1]: + sol2 = self.l2[med2 + 1] + else: + sol2 = self.l1[med1 + 1] + soln = (sol1+sol2)/2 + + # print ("solution2 is {} ".format(sol2)) + # print ("final solution is {} ".format(soln)) + + return soln + if __name__ == '__main__': + l1 = [2, 5, 25, 37, 50, 66, 71, 72, 80, 91, 92, 100] + l2 = [75, 77, 79, 84, 86, 105, 107, 110] + + ma = median_array(l1, l2) + + med = ma.find_median() + + print("TEST#1 - median of A1 {} and A2 {} is {}".format(l1, l2, med)) + + l1 = [2, 5, 25, 37, 50, 66, 71, 72, 80, 91, 92, 100] + l2 = [75, 77, 79, 84, 86, 105, 107, 110, 120] + + ma = median_array(l1, l2) + + med = ma.find_median() + + print("TEST#2 - median of A1 {} and A2 {} is {}".format(l1, l2, med)) + l1 = [2] + l2 = [75] + + ma = median_array(l1, l2) + + med = ma.find_median() + + print("TEST#3 - median of A1 {} and A2 {} is {}".format(l1, l2, med)) + l1 = [20] + l2 = [20] + + ma = median_array(l1, l2) + + med = ma.find_median() + + print("TEST#4 - median of A1 {} and A2 {} is {}".format(l1, l2, med)) + + l1 = [20] + l2 = [20, 21] + + ma = median_array(l1, l2) + + med = ma.find_median() + + print("TEST#5 - median of A1 {} and A2 {} is {}".format(l1, l2, med)) + + l1 = [10, 18] + l2 = [20, 30, 40, 45] + + ma = median_array(l1, l2) + + med = ma.find_median() - astr = digitstr("23423423y5") - print("alldigit? = ", astr.alldigits()) + print("TEST#6 - median of A1 {} and A2 {} is {}".format(l1, l2, med)) diff --git a/test13/.idea/misc.xml b/test13/.idea/misc.xml index 50f1aef..8161a60 100644 --- a/test13/.idea/misc.xml +++ b/test13/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test13/.idea/modules.xml b/test13/.idea/modules.xml index eb5d17d..12f1cc0 100644 --- a/test13/.idea/modules.xml +++ b/test13/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test27/.idea/test27.iml b/test13/.idea/test27.iml similarity index 100% rename from test27/.idea/test27.iml rename to test13/.idea/test27.iml diff --git a/test13/main.py b/test13/main.py index 531fb3a..6722a41 100644 --- a/test13/main.py +++ b/test13/main.py @@ -1,4 +1,4 @@ -# This script reverses words in a paragraph +# This script implements a simple vending machine # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -19,22 +19,84 @@ # along with this program. If not, see . # -def reverse(alist): - blist = [] - for item in alist: - blist.insert(0,item) - return blist +class order(): + def __init__(self, money, item): + self.money = money + self.item = item -def reverse2(alist): - blist = [] - for item in alist[::-1]: - blist.append(item) - return blist +class item(): + def __init__(self, name, price): + self.name = name + self.price = price + + def to_str(self): + astr = "item = (name = " + self.name + " price = " + str(self.price) + ")" + return astr + +class invitem(): + def __init__(self, item, count): + self.item = item + self.count = count + + def remove(self, num=1): + self.count = self.count - num + + def add(self, num=1): + self.count = self.count + num + + def print(self): + print("{}, count = {}".format(self.item.to_str(), self.count)) + +class vmachine(): + def __init__(self, list): + self.dict = dict() + for each in list: + self.add(invitem(item(each[0], each[1]), each[2])) + + def add(self, invitem): + if(self.dict.get(invitem.item.name)): + self.dict[invitem.item.name].count = self.dict[invitem.item.name].count + invitem.count + else: + self.dict[invitem.item.name] = invitem + + def sell(self, order, num=1): + trans = False + invitem = self.dict.get(order.item) + remain = order.money + + if(invitem): + cost = invitem.item.price*num + if(cost < order.money): + trans = True + remain = order.money - cost + invitem.count = invitem.count - num + return trans, remain + return trans, remain + + def print(self): + for each in self.dict.values(): + each.print() if __name__ == "__main__": - astr = "In this study we used domain engineering as a method for gaining deeper formal understanding of a class of algorithms. Specifically, we analyzed 6 stemming algorithms from 4 different sub-domains of the conflation algorithms domain and developed formal domain models and generators based on these models. The application generator produces source code for not only affix removal but also successor variety, table lookup, and n-gram stemmers. The performance of the generated stemmers was compared with the stemmers developed manually in terms of stem similarity, source, and executable sizes, and development and execution times. Five of the stemmers generated by the application generator produced more than 99.9% identical stems with the manually developed stemmers. Some of the generated stemmers were as efficient as their manual equivalents and some were not." - alist = list(astr.split()) + inv = [["choclate", 10, 25], ["gum", 1, 100], ["coke", 5, 50]] + vm = vmachine(inv) + + vm.print() + + money = 50 + + ord = order(money, "gum") + trans, money = vm.sell(ord, 5) + print("transaction = {}, remain = {}".format(trans, money)) + vm.print() + + ord = order(money, "choclate") + trans, money = vm.sell(ord, 6) + print("transaction = {}, remain = {}".format(trans, money)) + vm.print() - print("reverse of {} is {}".format(alist, reverse(alist))) - print("reverse2 of {} is {}".format(alist, reverse2(alist))) + ord = order(money, "coke") + trans, money = vm.sell(ord, 2) + print("transaction = {}, remain = {}".format(trans, money)) + vm.print() \ No newline at end of file diff --git a/test30/.DS_Store b/test22/.DS_Store similarity index 100% rename from test30/.DS_Store rename to test22/.DS_Store diff --git a/test22/.idea/misc.xml b/test22/.idea/misc.xml index 8161a60..d7e9cdb 100644 --- a/test22/.idea/misc.xml +++ b/test22/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test22/.idea/modules.xml b/test22/.idea/modules.xml index ba082d1..ceb0057 100644 --- a/test22/.idea/modules.xml +++ b/test22/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test30/.idea/test30.iml b/test22/.idea/test30.iml similarity index 100% rename from test30/.idea/test30.iml rename to test22/.idea/test30.iml diff --git a/test30/.idea/workspace.xml b/test22/.idea/workspace.xml similarity index 100% rename from test30/.idea/workspace.xml rename to test22/.idea/workspace.xml diff --git a/test22/main.py b/test22/main.py index 83686cc..7ecb5d5 100644 --- a/test22/main.py +++ b/test22/main.py @@ -1,4 +1,4 @@ -# This script implements a binary tree +# This script creates a binary tree iterator # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -19,85 +19,105 @@ # along with this program. If not, see . # -def create_binary_tree(alist): - try: - if alist is None: return None - else: - bt = btree(alist[0]) - for item in alist[1:]: - bt.insert(item) - except: - raise - +def create_btree(alist): + bt = None + if (alist != None and alist != []): + bt = btree(alist[0]) + for each in alist [1:]: + bt.add(each) return bt class btree(): def __init__(self, data): - self.left = None - self.right = None self.data = data + self.left = self.right = None + self.parent = None - def find(self, data): - if self.data == data: - return self - elif self.data > data: - if(self.left != None): - return self.left.find(data) - else: - return None + def add(self, data): + ret = False + if data == self.data: + # error - skip it + pass else: - if(self.right != None): - return self.right.find(data) - else: - return None - - def insert(self, num): - if self.data == num: - raise ValueError - elif self.data > num: - if self.left == None: - self.left = btree(num) + next = None + if(self.data > data): + next = self.left else: - self.left.insert(num) - else: - if self.right == None: - self.right = btree(num) + next = self.right + + if(next == None): + node = btree(data) + node.parent = self + if(self.data > data): + self.left = node + else: + self.right = node + ret = True else: - self.right.insert(num) + ret = next.add(data) + return ret def to_list(self): - alist = llist = rlist = [] - if(self.left != None): - llist = self.left.to_list() - alist.extend(llist) + alist = [] + + if(self.left): + alist.append(self.left.to_list()) alist.append(self.data) - if(self.right != None): - rlist = self.right.to_list() - alist.extend(rlist) + if(self.right): + alist.append(self.right.to_list()) return alist -if __name__ == "__main__": +class iter(): + def __init__(self, bt): + self.bt = bt + self.cur = None + + def begin(self): + if(self.bt.left): + it = iter(self.bt.left) + return(it.begin()) + else: + return self.bt + + def end(self): + if(self.bt.right): + it = iter(self.bt.right) + return(it.end()) + else: + return self.bt + + def next(self): + bt = self.cur + self.cur = None + if(bt.right): + it = iter(bt.right) + self.cur = it.begin() + else: + while (bt.parent and self.cur == None): + if(bt.parent.right != bt): + self.cur = bt.parent + else: + bt = bt.parent - try: - al = [1, 2, 30, 4, 60, 34, 12, -1 , 5, 23, 67, 35, 4, 99, -20, -45, 89, 78] - bt = create_binary_tree(al) - num = 55 + return self.cur - print("{} node in binary tree {} is {}".format(num, bt.to_list(), bt.find(num))) + def setcurrent(self, node): + self.cur = node - except: - print ("list is not unique") + def current(self): + return self.cur - try: - al = [1, 2, 30, 4, 60, 34, 12, -1 , 5, 23, 67, 35, 99, -20, -45, 89, 78] - bt = create_binary_tree(al) +if __name__=="__main__": - num = 55 - print("{} node in binary tree {} is {}".format(num, bt.to_list(), bt.find(num))) + alist = [1, 2, 30, 4, 60, 34, 12, -1, 5, 23, 67, 35, 4, 99, -20, -45, 89, 78] + bt = create_btree(alist) + print("list is {}".format(alist)) + print("btree is {}".format(bt.to_list())) - num = 99 - print("{} node in binary tree {} is {}".format(num, bt.to_list(), bt.find(num))) + it = iter(bt) + it.setcurrent(it.begin()) + print ("it begin = {} and it end {}".format(it.current().data, it.end().data)) - except: - print ("list is not unique") + while(it.current() != it.end()): + print ("in next= {}".format(it.next().data)) diff --git a/test7/.DS_Store b/test26/.DS_Store similarity index 100% rename from test7/.DS_Store rename to test26/.DS_Store diff --git a/test26/.idea/misc.xml b/test26/.idea/misc.xml index 8161a60..8617bf6 100644 --- a/test26/.idea/misc.xml +++ b/test26/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test26/.idea/modules.xml b/test26/.idea/modules.xml index 0423e98..3617fc4 100644 --- a/test26/.idea/modules.xml +++ b/test26/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test7/.idea/test7.iml b/test26/.idea/test7.iml similarity index 100% rename from test7/.idea/test7.iml rename to test26/.idea/test7.iml diff --git a/test26/main.py b/test26/main.py index 75cb854..cf01efd 100644 --- a/test26/main.py +++ b/test26/main.py @@ -1,4 +1,4 @@ -# This script implements bubble sort, insertion sort, quick sort, merge sort, and bucket sort algorithms +# count the occurrence of each word in a list # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -19,149 +19,31 @@ # along with this program. If not, see . # -class slist(list): +class listcount(list): + def __init__(self, alist): + super().__init__(alist) + self.adict = dict() + self.createdict() - def __init__(self, slist): - super().__init__(slist) - self.blist = slist - self.ilist = slist - self.bclist = [] - - def bubblesort(self): - last = len(self) - 1 - while last > 0: - for i in range(last): - if self.blist[i] > self.blist[i+1]: - temp = self.blist[i] - self.blist[i] = self.blist[i+1] - self.blist[i+1] = temp - last = last - 1 - return self.blist - - def insertionsort(self): - last = len(self) - first = 0 - while first < last: - min = self.ilist[first] - mindex = first - for i in range(first+1, last): - if self.ilist[i] < min: - min = self.ilist[i] - mindex = i - if(mindex != first): - self.ilist.pop(mindex) - self.ilist.insert(0,min) - first = first + 1 - - return self.ilist - - def findminmax(self): - min = max = self[0] - for each in self: - if each < min: - min = each - elif each > max: - max = each - return min, max - - def bucketsort(self, k): - if(len(self)<=1): return self - min, max = self.findminmax() - bucket = [] - bsize = int((max - min)/k)+1 - for i in range(k): - bucket.append([]) - for each in self: - bucket[int((each-min)/bsize)].append(each) - - for i in range(k): - alist = slist(bucket[i]) - self.bclist.extend(alist.insertionsort()) - - return self.bclist - - -def partition(list, pi): - low = [] - high = [] - for i in range(len(list)): - if i == pi: pass - elif list[i] > list[pi]: - high.append(list[i]) - else: - low.append(list[i]) - return low, high - -def quicksort(list): - if(list == None): return None - elif(len(list) <= 1): - return list - else: - low, high = partition(list, 0) - # print("low = {}, pivot = {}, high = {}".format(low, list[0], high)) - qlist = quicksort(low) - qlist.append(list[0]) - qlist.extend(quicksort(high)) - - return qlist - -def mergesort(list): - if list == None: return None - elif(len(list) <=1): return list - else: - mid = int(len(list)/2) - alist = list[:mid] - blist = list[mid:] - amlist = mergesort(alist) - bmlist = mergesort(blist) - i = j = 0 - mlist = [] - while(i - + \ No newline at end of file diff --git a/test22/.idea/test22.iml b/test27/.idea/test22.iml similarity index 100% rename from test22/.idea/test22.iml rename to test27/.idea/test22.iml diff --git a/test27/main.py b/test27/main.py index 6722a41..83686cc 100644 --- a/test27/main.py +++ b/test27/main.py @@ -1,4 +1,4 @@ -# This script implements a simple vending machine +# This script implements a binary tree # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -19,84 +19,85 @@ # along with this program. If not, see . # -class order(): - def __init__(self, money, item): - self.money = money - self.item = item - -class item(): - def __init__(self, name, price): - self.name = name - self.price = price - - def to_str(self): - astr = "item = (name = " + self.name + " price = " + str(self.price) + ")" - return astr - -class invitem(): - def __init__(self, item, count): - self.item = item - self.count = count - - def remove(self, num=1): - self.count = self.count - num - - def add(self, num=1): - self.count = self.count + num - - def print(self): - print("{}, count = {}".format(self.item.to_str(), self.count)) - -class vmachine(): - def __init__(self, list): - self.dict = dict() - for each in list: - self.add(invitem(item(each[0], each[1]), each[2])) - - def add(self, invitem): - if(self.dict.get(invitem.item.name)): - self.dict[invitem.item.name].count = self.dict[invitem.item.name].count + invitem.count +def create_binary_tree(alist): + try: + if alist is None: return None else: - self.dict[invitem.item.name] = invitem - - def sell(self, order, num=1): - trans = False - invitem = self.dict.get(order.item) - remain = order.money - - if(invitem): - cost = invitem.item.price*num - if(cost < order.money): - trans = True - remain = order.money - cost - invitem.count = invitem.count - num - return trans, remain - return trans, remain - - def print(self): - for each in self.dict.values(): - each.print() + bt = btree(alist[0]) + for item in alist[1:]: + bt.insert(item) + except: + raise + + return bt + +class btree(): + def __init__(self, data): + self.left = None + self.right = None + self.data = data + + def find(self, data): + if self.data == data: + return self + elif self.data > data: + if(self.left != None): + return self.left.find(data) + else: + return None + else: + if(self.right != None): + return self.right.find(data) + else: + return None + + def insert(self, num): + if self.data == num: + raise ValueError + elif self.data > num: + if self.left == None: + self.left = btree(num) + else: + self.left.insert(num) + else: + if self.right == None: + self.right = btree(num) + else: + self.right.insert(num) + + def to_list(self): + alist = llist = rlist = [] + if(self.left != None): + llist = self.left.to_list() + alist.extend(llist) + alist.append(self.data) + if(self.right != None): + rlist = self.right.to_list() + alist.extend(rlist) + + return alist if __name__ == "__main__": - inv = [["choclate", 10, 25], ["gum", 1, 100], ["coke", 5, 50]] - vm = vmachine(inv) + try: + al = [1, 2, 30, 4, 60, 34, 12, -1 , 5, 23, 67, 35, 4, 99, -20, -45, 89, 78] + bt = create_binary_tree(al) + num = 55 + + print("{} node in binary tree {} is {}".format(num, bt.to_list(), bt.find(num))) - vm.print() + except: + print ("list is not unique") - money = 50 + try: + al = [1, 2, 30, 4, 60, 34, 12, -1 , 5, 23, 67, 35, 99, -20, -45, 89, 78] + bt = create_binary_tree(al) - ord = order(money, "gum") - trans, money = vm.sell(ord, 5) - print("transaction = {}, remain = {}".format(trans, money)) - vm.print() + num = 55 + print("{} node in binary tree {} is {}".format(num, bt.to_list(), bt.find(num))) - ord = order(money, "choclate") - trans, money = vm.sell(ord, 6) - print("transaction = {}, remain = {}".format(trans, money)) - vm.print() + num = 99 + print("{} node in binary tree {} is {}".format(num, bt.to_list(), bt.find(num))) - ord = order(money, "coke") - trans, money = vm.sell(ord, 2) - print("transaction = {}, remain = {}".format(trans, money)) - vm.print() \ No newline at end of file + except: + print ("list is not unique") diff --git a/test3/.idea/misc.xml b/test3/.idea/misc.xml index fc30dfa..65531ca 100644 --- a/test3/.idea/misc.xml +++ b/test3/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test3/.idea/modules.xml b/test3/.idea/modules.xml index 82cf164..48bdd3e 100644 --- a/test3/.idea/modules.xml +++ b/test3/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test35/.idea/test35.iml b/test3/.idea/test35.iml similarity index 100% rename from test35/.idea/test35.iml rename to test3/.idea/test35.iml diff --git a/test3/main.py b/test3/main.py index f74f65f..62cce35 100644 --- a/test3/main.py +++ b/test3/main.py @@ -1,5 +1,5 @@ -# This script manipulates a number string by adding a "*" between two -# consecutive even numbers and "-" between two consecutive odd numbers +# This script finds the best time to buy and sell a stock once or unlimited times +# or fix number of time to make the maximum profit # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -20,36 +20,250 @@ # along with this program. If not, see . # -class strmanup(str): - def __init__(self, astr): - super().__init__() - self.offset = 0 - self = astr +class best_profit(): + def __init__(self, sp): + self.sp = sp + self.sellindex = self.buyindex = 0 - def isEven(self, i): - return((int(self[i]) % 2) == 0) + def profit(self): + # if seelindex does not have the default value + if self.sellindex == 0: + return 0 + else: + return self.sp[self.sellindex] - self.sp[self.buyindex] + def setbuyindex(self, buyindex): + self.buyindex = buyindex - def isOdd(self, i): - return((int(self[i]) % 2) != 0) + def setsellindex(self, sellindex): + self.sellindex = sellindex - def manupstr(self, offset): - newstr = "" - if(len(self) 0: + + # print("selling ... index = {}".format(index-1)) + # update merge cost list + # self.update_merge_cost(sellno) + total_profit += self.bplist[sellno].profit() + sellno += 1 + self.bplist.append(best_profit(self)) + self.bplist[sellno].setbuyindex(index) + + # keep track off the min price + if self[index] < self[self.bplist[sellno].buyindex]: + self.bplist[sellno].setbuyindex(index) + + # check the profit if we sell now + profit = self[index] - self.bplist[sellno].buyprice() + + # replace the maxprofit if profit is more than maxprofit + if(profit > self.bplist[sellno].profit()): + self.bplist[sellno].sellindex = index + + if(self.bplist[sellno].profit() > 0): + print("selling ... index = {}".format(index)) + # update merge cost list + # self.update_merge_cost(sellno) + total_profit += self.bplist[sellno].profit() + else: + self.bplist.pop(sellno) + + return total_profit, self.bplist + + # this is an alternative implementation of unlimited trades + # this function creates the all buy sell points that will be used + # to determine the maximum profit when at most X number of trades is allowed + def max_profit_all(self): + + self.actlist = list() + total_profit = actindex = 0 + downtrend = True + self.actlist.append(0) + + # iterate over price list to determine the best profit + for index in range(1, len(self)): + + if downtrend: + if self[index] < self[index-1]: + self.actlist[actindex] = index + elif self[index] > self[index-1]: + # local min found - buy point + self.actlist.append(index) + # self.tradesort(actindex-1) + actindex += 1 + downtrend = False + else: + if self[index] > self[index -1]: + self.actlist[actindex] = index + elif self[index] < self[index-1]: + # local max found - sell point + self.actlist.append(index) + # cash it - add profit to the total + total_profit += self[self.actlist[actindex]] - self[self.actlist[actindex-1]] + actindex += 1 + downtrend = True + + if downtrend: + # remove the last activity node - nothing to sell + self.actlist.pop(actindex) + actindex -= 1 + + total_profit = self.set_bplist_from_actlist() + + return total_profit, self.actlist + + def trade_cost(self, index): + # cost of removing a trade = absolute value of price of this trade - price of next trade + return(abs(self[self.actlist[index]] - self[self.actlist[index+1]])) + + def set_bplist_from_actlist(self): + total_profit = 0 + self.bplist = list() + for i in range(len(self.actlist)-1): + if self[self.actlist[i+1]] > self[self.actlist[i]]: + bp = best_profit(self) + bp.setbuyindex(self.actlist[i]) + bp.setsellindex(self.actlist[i+1]) + total_profit += bp.profit() + self.bplist.append(bp) + + return total_profit + + def keep_best_trades(self, n): + self.legs = 2 * n + + while len(self.actlist) > self.legs: + minindex = 0 + for i in range(len(self.actlist)-1): + if(self.trade_cost(i) < self.trade_cost(minindex)): + minindex = i + + # remove two activities to eliminate the least beneficial trade + self.actlist.pop(minindex) + self.actlist.pop(minindex) + + total_profit = self.set_bplist_from_actlist() + + print("ACTIVITY LIST= {}".format(self.actlist)) + return total_profit, self.actlist + + def max_profit_limited(self, numoftrades): + total_profit = 0 + bplist = list() + actlist = list() + + total_profit, actlist = self.max_profit_all() + + total_profit, actlist = self.keep_best_trades(numoftrades) + + return (total_profit, actlist) + def print_bplist(self): + for i in range(len(self.bplist)): + print("SELL #{}".format(i)) + self.bplist[i].print() + + +if __name__=="__main__": + + sprices = (5, 3, 2, 10, 12, 15, 17, 11, 6, 8 , 10, 20, 23, 17, 15, 16, 18, 20, 26, 50, + 13, 24, 45, 49, 25, 23, 27, 31, 25) + sp = stock_prices(list(sprices)) + + mpo = sp.max_profit_once() + print ("MAX PROFIT ONCE") + mpo.print() + + maxprofit, mpu = sp.max_profit_unlimited() + + print("\n\nMAX PROFIT UNLIMITED TRADES") + print("Total Profit = {}".format(maxprofit)) + + maxprofit, al = sp.max_profit_all() + + print("\n\nMAX PROFIT ALL (UNLIMITED TRADES)") + print("Total Profit = {}".format(maxprofit)) + for index in al: + print("LOCAL MAX/MIN POINT INDEX = {} PRICE = {}".format(index, sp[index])) + sp.print_bplist() + + n = 1 + maxprofit, al = sp.max_profit_limited(n) + + print("\n\nMAX PROFIT {} TRADE".format(n)) + print("Total Profit = {}".format(maxprofit)) + for index in al: + print("LOCAL MAX/MIN POINT INDEX = {} PRICE = {}".format(index, sp[index])) + sp.print_bplist() + + n = 3 + maxprofit, al = sp.max_profit_limited(n) + + print("\n\nMAX PROFIT {} TRADES".format(n)) + print("Total Profit = {}".format(maxprofit)) + for index in al: + print("LOCAL MAX/MIN POINT INDEX = {} PRICE = {}".format(index, sp[index])) + sp.print_bplist() + + n = 2 + maxprofit, al = sp.max_profit_limited(n) + + print("\n\nMAX PROFIT {} TRADES".format(n)) + print("Total Profit = {}".format(maxprofit)) + for index in al: + print("LOCAL MAX/MIN POINT INDEX = {} PRICE = {}".format(index, sp[index])) + sp.print_bplist() diff --git a/test22/.idea/.gitignore b/test30/.idea/.gitignore similarity index 100% rename from test22/.idea/.gitignore rename to test30/.idea/.gitignore diff --git a/test30/.idea/misc.xml b/test30/.idea/misc.xml index d7e9cdb..65531ca 100644 --- a/test30/.idea/misc.xml +++ b/test30/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test30/.idea/modules.xml b/test30/.idea/modules.xml index ceb0057..4b03934 100644 --- a/test30/.idea/modules.xml +++ b/test30/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test40/.idea/test40.iml b/test30/.idea/test40.iml similarity index 100% rename from test40/.idea/test40.iml rename to test30/.idea/test40.iml diff --git a/test30/main.py b/test30/main.py index 7ecb5d5..8484602 100644 --- a/test30/main.py +++ b/test30/main.py @@ -1,4 +1,4 @@ -# This script creates a binary tree iterator +# This script returns level order of a binary tree # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -18,106 +18,79 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # - def create_btree(alist): - bt = None - if (alist != None and alist != []): - bt = btree(alist[0]) - for each in alist [1:]: - bt.add(each) - return bt - -class btree(): + head = None + if not alist or alist == []: + pass + else: + tn = treenode(alist[0]) + head = tn + for item in alist[1:]: + tn.add_node(item) + + return head + +def create_levelorder(tn): + lvl = 0 + lolist = list() + tn.levelorder(lolist, 0) + + return lolist + +class treenode(): def __init__(self, data): self.data = data - self.left = self.right = None - self.parent = None - - def add(self, data): - ret = False - if data == self.data: - # error - skip it - pass - else: - next = None - if(self.data > data): - next = self.left + self.left = None + self.right = None + + def add_node(self, data): + if(data data): - self.left = node - else: - self.right = node - ret = True + self.left = treenode(data) + elif(data>self.data): + if(self.right): + self.right.add_node(data) else: - ret = next.add(data) - return ret + self.right = treenode(data) + else: + pass # duplicate node, just ignore - def to_list(self): - alist = [] + def levelorder(self, lolist, lvl): + if(len(lolist) <= lvl): + lolist.append(list()) + lolist[lvl].append(self.data) if(self.left): - alist.append(self.left.to_list()) - alist.append(self.data) + self.left.levelorder(lolist, lvl+1) + if(self.right): - alist.append(self.right.to_list()) + self.right.levelorder(lolist, lvl+1) - return alist +if __name__ == "__main__": -class iter(): - def __init__(self, bt): - self.bt = bt - self.cur = None + tlist = [20, 34, 10, 11, 45, 42, 13, 17, 25, 28, 5, 7] - def begin(self): - if(self.bt.left): - it = iter(self.bt.left) - return(it.begin()) - else: - return self.bt + tr = create_btree(tlist) - def end(self): - if(self.bt.right): - it = iter(self.bt.right) - return(it.end()) - else: - return self.bt - - def next(self): - bt = self.cur - self.cur = None - if(bt.right): - it = iter(bt.right) - self.cur = it.begin() - else: - while (bt.parent and self.cur == None): - if(bt.parent.right != bt): - self.cur = bt.parent - else: - bt = bt.parent + lolist = create_levelorder(tr) + + print("test#1 - levelorder of {} is {}".format(tlist, lolist)) + + tlist = [15, 2, 60, 72, 48, 12, 11, 20, 34, 10, 11, 45, 42, 13, 17, 25, 28, 5, 7] + + tr = create_btree(tlist) - return self.cur + lolist = create_levelorder(tr) - def setcurrent(self, node): - self.cur = node + print("test#2 - levelorder of {} is {}".format(tlist, lolist)) - def current(self): - return self.cur + tlist = [1] -if __name__=="__main__": + tr = create_btree(tlist) - alist = [1, 2, 30, 4, 60, 34, 12, -1, 5, 23, 67, 35, 4, 99, -20, -45, 89, 78] - bt = create_btree(alist) - print("list is {}".format(alist)) - print("btree is {}".format(bt.to_list())) + lolist = create_levelorder(tr) - it = iter(bt) - it.setcurrent(it.begin()) - print ("it begin = {} and it end {}".format(it.current().data, it.end().data)) + print("test#3 - levelorder of {} is {}".format(tlist, lolist)) - while(it.current() != it.end()): - print ("in next= {}".format(it.next().data)) diff --git a/test5/.DS_Store b/test31/.DS_Store similarity index 100% rename from test5/.DS_Store rename to test31/.DS_Store diff --git a/test4/.idea/.gitignore b/test31/.idea/.gitignore similarity index 100% rename from test4/.idea/.gitignore rename to test31/.idea/.gitignore diff --git a/test12/.idea/aws.xml b/test31/.idea/aws.xml similarity index 100% rename from test12/.idea/aws.xml rename to test31/.idea/aws.xml diff --git a/test31/.idea/misc.xml b/test31/.idea/misc.xml index e524f65..ad6d11e 100644 --- a/test31/.idea/misc.xml +++ b/test31/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test31/.idea/modules.xml b/test31/.idea/modules.xml index 557cc95..f5ac542 100644 --- a/test31/.idea/modules.xml +++ b/test31/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test5/.idea/test5.iml b/test31/.idea/test5.iml similarity index 100% rename from test5/.idea/test5.iml rename to test31/.idea/test5.iml diff --git a/test31/main.py b/test31/main.py index a84595b..0230544 100644 --- a/test31/main.py +++ b/test31/main.py @@ -1,4 +1,4 @@ -# This script recovers a binary search tree with 2 replaced nodes +# This script finds the common words in two lists # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -19,155 +19,34 @@ # along with this program. If not, see . # -def create_btree(alist): - bt = None - if alist != None and alist != []: - bt = btree(alist[0]) - for each in alist[1:]: - add_btree(bt, each) - return bt - -def add_btree(bt, data): - if data == None: - pass - elif bt == None: - bt = btree(data) - else: - if data == bt.data: - pass #duplicate, do don't do anything (or raise an except - elif data < bt.data: - if bt.left: - add_btree(bt.left, data) - else: - bt.left = btree(data) - else: - if bt.right: - add_btree(bt.right, data) +class listops(): + def __init__(self, lista, listb): + self.listA = lista + self.listB = listb + self.mdict = dict() + def intersect(self): + for item in self.listA: + if(self.mdict.get(item) != None): + self.mdict[item] = self.mdict[item] + 1 else: - bt.right = btree(data) - -def recover_btree(bt): - reclist = bt.recover() - print("MIN misplaced {} and MAX misplaced {}".format(bt.recmin.data, bt.recmax.data)) - swap_data(bt.recmin, bt.recmax) - return reclist - -def swap_data(a, b): - temp = a.data - a.data = b.data - b.data = temp - -class btree(): - def __init__(self, data): - self.data = data - self.left = self.right = self.parent = None - self.resetrecovery() - - def resetrecovery(self): - self.recmin = self.recmax = None - - # set minimum misplaced node - def setrecmin(self, node): - if(node): - if(self.recmin == None or self.recmin.data > node.data): - self.recmin = node - - # set maximum misplaced node - def setrecmax(self, node): - if(node): - if(self.recmax == None or self.recmax.data < node.data): - self.recmax = node - - def to_list(self): - alist = [] - - if self.left: - alist.extend(self.left.to_list()) - alist.append(self) - if self.right: - alist.extend(self.right.to_list()) - - return alist - - def to_data_list(self): - alist = [] - - if self.left: - alist.extend(self.left.to_data_list()) - - alist.append(self.data) - - if self.right: - alist.extend(self.right.to_data_list()) - - return alist - - def to_data_tlist(self): - alist = [] - - if self.left: - alist.append(self.left.to_data_tlist()) - - alist.append(self.data) - - if self.right: - alist.append(self.right.to_data_tlist()) - - return alist - - def recover(self): - ll = [] - rl = [] - self.resetrecovery() - - if self.left: - ll = self.left.recover() - self.setrecmin(self.left.recmin) - self.setrecmax(self.left.recmax) - if ll[-1] and (ll[-1].data > self.data): - self.setrecmin(self) - self.setrecmax(ll[-1]) - - if self.right: - rl = self.right.recover() - self.setrecmin(self.right.recmin) - self.setrecmax(self.right.recmax) - if rl[0] and (rl[0].data < self.data): - self.setrecmin(rl[0]) - self.setrecmax(self) - - ll.append(self) - ll.extend(rl) - dl = [] - #for each in ll: - # dl.append(each.data) - #print ("recover = {}".format(dl)) - return ll - -if __name__=="__main__": - - bt = create_btree([1, 2, 30, 4, 60, 34, 12, -1, 5, 23, 67, 35, 4, 99, -20, -45, 89, 78]) - tlist = bt.to_list() - print("Original tlist = ", bt.to_data_tlist()) - - #test 6th and 11th replacement - swap_data(tlist[5], tlist[10]) - print("broken list = ", bt.to_data_tlist()) - reclist = recover_btree(bt) - print("recovered list = ", bt.to_data_list()) - - tlist = bt.to_list() - print("\n\nOriginal tlist = ", bt.to_data_tlist()) - # test min and max replacement - swap_data(tlist[0], tlist[16]) - print("broken list = ", bt.to_data_tlist()) - reclist = recover_btree(bt) - print("recovered list = ", bt.to_data_list()) - - tlist = bt.to_list() - print("\n\nOriginal tlist = ", bt.to_data_tlist()) - # test 7th and 15th replacement - swap_data(tlist[6], tlist[14]) - print("broken list = ", bt.to_data_tlist()) - reclist = recover_btree(bt) - print("recovered list = ", bt.to_data_list()) + self.mdict[item] = 1 + for item in self.listB: + if(self.mdict.get(item) != None): + print("Intersected=", item) + def printdict(self): + print("DICT= {}".format(self.mdict)) + +if __name__ == '__main__': + lista = ["apple", "orange", "apple", "pinapple", "melon", "melon", "blueberry"] + listb = ["raspbery", "apple", "pinapple", "watermelon", "banana"] + + lo1 = listops(lista, listb) + lo1.intersect() + lo1.printdict() + + str1 = "In this study we used domain engineering as a method for gaining deeper formal understanding of a class of algorithms. Specifically, we analyzed 6 stemming algorithms from 4 different sub-domains of the conflation algorithms domain and developed formal domain models and generators based on these models. The application generator produces source code for not only affix removal but also successor variety, table lookup, and n-gram stemmers. The performance of the generated stemmers was compared with the stemmers developed manually in terms of stem similarity, source, and executable sizes, and development and execution times. Five of the stemmers generated by the application generator produced more than 99.9% identical stems with the manually developed stemmers. Some of the generated stemmers were as efficient as their manual equivalents and some were not." + str2 = "In the early 1980s software companies started the systematic reuse process through domain engineering to improve software productivity and quality. There has been insufficient empirical study of the domain engineering process and domain products such as reusable components and generators. This paper addresses this problem by documenting and empirically evaluating a domain engineering project for the conflation algorithms domain. This domain is important for many types of systems such as information retrieval systems, search engines, and word processors. The application generator developed for this study extends the domain scope compared to previous ones." + + lo2 = listops(str1.split(), str2.split()) + lo2.intersect() + lo2.printdict() diff --git a/test4/.DS_Store b/test35/.DS_Store similarity index 100% rename from test4/.DS_Store rename to test35/.DS_Store diff --git a/test22/.idea/aws.xml b/test35/.idea/aws.xml similarity index 100% rename from test22/.idea/aws.xml rename to test35/.idea/aws.xml diff --git a/test35/.idea/misc.xml b/test35/.idea/misc.xml index 65531ca..2856404 100644 --- a/test35/.idea/misc.xml +++ b/test35/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test35/.idea/modules.xml b/test35/.idea/modules.xml index 48bdd3e..cbb2cf7 100644 --- a/test35/.idea/modules.xml +++ b/test35/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test4/.idea/test4.iml b/test35/.idea/test4.iml similarity index 100% rename from test4/.idea/test4.iml rename to test35/.idea/test4.iml diff --git a/test35/main.py b/test35/main.py index 62cce35..078b493 100644 --- a/test35/main.py +++ b/test35/main.py @@ -1,5 +1,5 @@ -# This script finds the best time to buy and sell a stock once or unlimited times -# or fix number of time to make the maximum profit +# mingle two strings after crerating chunks in size n +# e.g. ABCDEFG and 1234567890 with 2 char chunks -> AB12CD34EF56G7890 # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -20,250 +20,54 @@ # along with this program. If not, see . # -class best_profit(): - def __init__(self, sp): - self.sp = sp - self.sellindex = self.buyindex = 0 +class merger(): + def __init__(self, list1, list2): + self.list1 = list1 + self.list2 = list2 + lista = listb = [] - def profit(self): - # if seelindex does not have the default value - if self.sellindex == 0: - return 0 - else: - return self.sp[self.sellindex] - self.sp[self.buyindex] - def setbuyindex(self, buyindex): - self.buyindex = buyindex - - def setsellindex(self, sellindex): - self.sellindex = sellindex - - def sellprice(self): - return self.sp[self.sellindex] - - def buyprice(self): - return self.sp[self.buyindex] - - def print(self): - print("MAXPROFIT = {}".format(sp[self.sellindex] - sp[self.buyindex])) - print("Buy for {} on index {}".format(sp[self.buyindex], self.buyindex)) - print("Sell for {} on index {}".format(sp[self.sellindex], self.sellindex)) - -class stock_prices(list): - - def __init__(self, alist): - super().__init__(alist) - self.bplist = list() - self.actlist = list() - self.costlist = list() - - def max_profit_once(self): - - bp = best_profit(self) - bp.buyindex = 0 - profit = 0 - - # iterate over price list to determine th best profit - for index in range(len(self)): - # keep track off the min price - if self[index] < self[bp.buyindex]: - bp.setbuyindex(index) - - # check the profit if we sell now - profit = self[index] - self[bp.buyindex] - - # replace the maxprofit if profit is more than maxprofit - if(profit > self[bp.sellindex] - self[bp.buyindex]): - bp.sellindex = index + def merge(self, offset): + flist = list() - return bp - - # this function determines the bet buy and sell times when unlimited number - # of trades are allowed - def max_profit_unlimited(self): - - self.bplist = list() - self.bplist.append(best_profit(self)) - total_profit = sellno = 0 - - # iterate over price list to determine the best profit - for index in range(1, len(self)): - - # print("sellno = {} index= {} {} {} {}". - # format(sellno, index, self.bplist[sellno].buyindex, - # self[index], self[index-1])) - # print(self.bplist[sellno].profit()) - # price decrease indicates a sell point - if self[index] < self[index-1] and self.bplist[sellno].profit() > 0: - - # print("selling ... index = {}".format(index-1)) - # update merge cost list - # self.update_merge_cost(sellno) - total_profit += self.bplist[sellno].profit() - sellno += 1 - self.bplist.append(best_profit(self)) - self.bplist[sellno].setbuyindex(index) - - # keep track off the min price - if self[index] < self[self.bplist[sellno].buyindex]: - self.bplist[sellno].setbuyindex(index) - - # check the profit if we sell now - profit = self[index] - self.bplist[sellno].buyprice() - - # replace the maxprofit if profit is more than maxprofit - if(profit > self.bplist[sellno].profit()): - self.bplist[sellno].sellindex = index - - if(self.bplist[sellno].profit() > 0): - print("selling ... index = {}".format(index)) - # update merge cost list - # self.update_merge_cost(sellno) - total_profit += self.bplist[sellno].profit() + if len(self.list1) < len(self.list2): + lista = self.list1 + listb = self.list2 else: - self.bplist.pop(sellno) - - return total_profit, self.bplist - - # this is an alternative implementation of unlimited trades - # this function creates the all buy sell points that will be used - # to determine the maximum profit when at most X number of trades is allowed - def max_profit_all(self): - - self.actlist = list() - total_profit = actindex = 0 - downtrend = True - self.actlist.append(0) - - # iterate over price list to determine the best profit - for index in range(1, len(self)): - - if downtrend: - if self[index] < self[index-1]: - self.actlist[actindex] = index - elif self[index] > self[index-1]: - # local min found - buy point - self.actlist.append(index) - # self.tradesort(actindex-1) - actindex += 1 - downtrend = False - else: - if self[index] > self[index -1]: - self.actlist[actindex] = index - elif self[index] < self[index-1]: - # local max found - sell point - self.actlist.append(index) - # cash it - add profit to the total - total_profit += self[self.actlist[actindex]] - self[self.actlist[actindex-1]] - actindex += 1 - downtrend = True - - if downtrend: - # remove the last activity node - nothing to sell - self.actlist.pop(actindex) - actindex -= 1 - - total_profit = self.set_bplist_from_actlist() - - return total_profit, self.actlist - - def trade_cost(self, index): - # cost of removing a trade = absolute value of price of this trade - price of next trade - return(abs(self[self.actlist[index]] - self[self.actlist[index+1]])) - - def set_bplist_from_actlist(self): - total_profit = 0 - self.bplist = list() - for i in range(len(self.actlist)-1): - if self[self.actlist[i+1]] > self[self.actlist[i]]: - bp = best_profit(self) - bp.setbuyindex(self.actlist[i]) - bp.setsellindex(self.actlist[i+1]) - total_profit += bp.profit() - self.bplist.append(bp) - - return total_profit - - def keep_best_trades(self, n): - self.legs = 2 * n - - while len(self.actlist) > self.legs: - minindex = 0 - for i in range(len(self.actlist)-1): - if(self.trade_cost(i) < self.trade_cost(minindex)): - minindex = i - - # remove two activities to eliminate the least beneficial trade - self.actlist.pop(minindex) - self.actlist.pop(minindex) - - total_profit = self.set_bplist_from_actlist() - - print("ACTIVITY LIST= {}".format(self.actlist)) - return total_profit, self.actlist - - def max_profit_limited(self, numoftrades): - total_profit = 0 - bplist = list() - actlist = list() - - total_profit, actlist = self.max_profit_all() - - total_profit, actlist = self.keep_best_trades(numoftrades) - - return (total_profit, actlist) - def print_bplist(self): - for i in range(len(self.bplist)): - print("SELL #{}".format(i)) - self.bplist[i].print() - - -if __name__=="__main__": - - sprices = (5, 3, 2, 10, 12, 15, 17, 11, 6, 8 , 10, 20, 23, 17, 15, 16, 18, 20, 26, 50, - 13, 24, 45, 49, 25, 23, 27, 31, 25) - sp = stock_prices(list(sprices)) - - mpo = sp.max_profit_once() - print ("MAX PROFIT ONCE") - mpo.print() - - maxprofit, mpu = sp.max_profit_unlimited() + listb = self.list1 + lista = self.list2 - print("\n\nMAX PROFIT UNLIMITED TRADES") - print("Total Profit = {}".format(maxprofit)) + times = int(len(lista)/offset) + for i in range(times): + flist = flist + lista[i*offset:i*offset+offset] + flist = flist + listb[i*offset:i*offset+offset] + flist = flist + lista[times*offset:len(lista)] + flist = flist + listb[times*offset:len(listb)] - maxprofit, al = sp.max_profit_all() + return(flist) - print("\n\nMAX PROFIT ALL (UNLIMITED TRADES)") - print("Total Profit = {}".format(maxprofit)) - for index in al: - print("LOCAL MAX/MIN POINT INDEX = {} PRICE = {}".format(index, sp[index])) - sp.print_bplist() +if __name__ == '__main__': - n = 1 - maxprofit, al = sp.max_profit_limited(n) + # TEST#1 + tlist1a = ["2","3","4","2","3","5","2","4","3","5","6","4","5"] + tlist1b = ["a","s","d","a","s","d","a","s","f","d","s","g","g","d","f","g","d","f","f","g","h","j","f","g","h","j","g","h","j"] - print("\n\nMAX PROFIT {} TRADE".format(n)) - print("Total Profit = {}".format(maxprofit)) - for index in al: - print("LOCAL MAX/MIN POINT INDEX = {} PRICE = {}".format(index, sp[index])) - sp.print_bplist() + m1 = merger(tlist1a, tlist1b) + num1 = 2 + print("TEST1 - {} char merged list = {}".format(num1, m1.merge(num1))) - n = 3 - maxprofit, al = sp.max_profit_limited(n) + # TEST#2 + tlist2a = ["1","2","3","2","3","4","2","4","5","3","6","4","5","7","5","6","7","5","8","6","7","9","7","8","0","8","9","0"] + tlist2b = ["x","c","v","x","c","v","c","v","b","n","f","g","h","y","r","t","y","r","t","y"] - print("\n\nMAX PROFIT {} TRADES".format(n)) - print("Total Profit = {}".format(maxprofit)) - for index in al: - print("LOCAL MAX/MIN POINT INDEX = {} PRICE = {}".format(index, sp[index])) - sp.print_bplist() + m2 = merger(tlist2a, tlist2b) + num2 = 3 + print("TEST2 - {} char merged list = {}".format(num2, m2.merge(num2))) - n = 2 - maxprofit, al = sp.max_profit_limited(n) + # TEST#3 + tlist3a = ["5","6","7","8","9"] + tlist3b = ["q","w","e","s","k"] - print("\n\nMAX PROFIT {} TRADES".format(n)) - print("Total Profit = {}".format(maxprofit)) - for index in al: - print("LOCAL MAX/MIN POINT INDEX = {} PRICE = {}".format(index, sp[index])) - sp.print_bplist() + m3 = merger(tlist3a, tlist3b) + num3 = 4 + print("TEST3 - {} char merged list = {}".format(num3, m3.merge(num3))) diff --git a/test13/.DS_Store b/test36/.DS_Store similarity index 100% rename from test13/.DS_Store rename to test36/.DS_Store diff --git a/test3/.idea/aws.xml b/test36/.idea/aws.xml similarity index 100% rename from test3/.idea/aws.xml rename to test36/.idea/aws.xml diff --git a/test36/.idea/misc.xml b/test36/.idea/misc.xml index 65531ca..50f1aef 100644 --- a/test36/.idea/misc.xml +++ b/test36/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test36/.idea/modules.xml b/test36/.idea/modules.xml index 6d9c0ed..eb5d17d 100644 --- a/test36/.idea/modules.xml +++ b/test36/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test13/.idea/test13.iml b/test36/.idea/test13.iml similarity index 100% rename from test13/.idea/test13.iml rename to test36/.idea/test13.iml diff --git a/test36/main.py b/test36/main.py index 5fde7d2..531fb3a 100644 --- a/test36/main.py +++ b/test36/main.py @@ -1,4 +1,4 @@ -# This script finds the largest rectangle in a histogram +# This script reverses words in a paragraph # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -18,107 +18,23 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # -class histogram(list): - def __init__(self, alist): - # pad the list with 0s to set boundaries for the calculation - # the 0s act like histogram data with 0 value on each side of the histogram - # this simplifies the program while does not affect the result - alist.insert(0,0) - alist.append(0) - super().__init__(alist) - self.sorted = [] - self.used = [] - self.max_rect_area = 0 - print("alist= {}".format(alist)) - def insert_sorted(self, i): - index = 0 - while index < len(self.sorted): - # print("insert_sorted index={} self.sorted={} len(self.sorted)={} i={}".format(index, self.sorted, len(self.sorted), i)) - if self[self.sorted[index]] > self[i]: - break - index += 1 +def reverse(alist): + blist = [] + for item in alist: + blist.insert(0,item) + return blist - self.sorted.insert(index, i) +def reverse2(alist): + blist = [] + for item in alist[::-1]: + blist.append(item) + return blist - def create_sorted(self): - self.sorted.append(0) +if __name__ == "__main__": + astr = "In this study we used domain engineering as a method for gaining deeper formal understanding of a class of algorithms. Specifically, we analyzed 6 stemming algorithms from 4 different sub-domains of the conflation algorithms domain and developed formal domain models and generators based on these models. The application generator produces source code for not only affix removal but also successor variety, table lookup, and n-gram stemmers. The performance of the generated stemmers was compared with the stemmers developed manually in terms of stem similarity, source, and executable sizes, and development and execution times. Five of the stemmers generated by the application generator produced more than 99.9% identical stems with the manually developed stemmers. Some of the generated stemmers were as efficient as their manual equivalents and some were not." - for i in range(1, len(self)): - self.insert_sorted(i) - print("self.sorted = {}".format(self.sorted)) + alist = list(astr.split()) - def insert_used(self, i): - index = 0 - while index < len(self.used): - if self.used[index] > i: - break - index += 1 - self.used.insert(index, i) - - return index - - def initialize_used(self): - # initialize the used list with imaginary histogram blocks - self.used = [] - - def get_used_value(self, index): - return(self[self.used[index]]) - - def calculate_rectangle_area(self, used_index): - print("self.used = {} used_index = {} self[used_index] = {}".format(self.used, used_index, self[used_index])) - - # return 0 for the boundary values - if(used_index == 0 or used_index == len(self.used) -1 ): return 0 - - prev = used_index - 1 - while prev > 0 and self.get_used_value(prev) == self.get_used_value(used_index): - prev -= 1 - - print("prev = {}".format(prev)) - - next = used_index + 1 - while next < len(self.used)-1 and self.get_used_value(next) == self.get_used_value(used_index): - next += 1 - - print("next = {}".format(next)) - - rect_area = self[self.used[used_index]] * (self.used[next] - self.used[prev] - 1 ) - - return rect_area - - def largest_rect(self): - # sort all histogram values in increasing order - # first rectangle will be bounded by the shortest historam value - self.create_sorted() - # initialize used with two imaginary histogram values 0 and histogram+1 values - self.initialize_used() - - while self.sorted != []: - # calculate the area of the first rectangle - hist_val = self.sorted.pop(0) - # insert the popped histogram value into the used histogram list - used_index = self.insert_used(hist_val) - rect_area = self.calculate_rectangle_area(used_index) - print("rect_area = {}".format(rect_area)) - - if(rect_area > self.max_rect_area): - # update the max rectangle area if the area is greater - self.max_rect_area = rect_area - - return self.max_rect_area - -# Press the green button in the gutter to run the script. -if __name__ == '__main__': - - alist = [12, 15, 17, 25, 40, 55, 30, 24, 60, 80, 90] - - hist = histogram(alist) - - print("LARGEST RECTANGLE FOR {} is {}".format(alist, hist.largest_rect())) - - alist = [12, 15, 17, 25, 25, 14, 12, 40, 55, 30, 24, 18, 18, 20, 60, 80, 90] - - hist = histogram(alist) - - print("LARGEST RECTANGLE FOR {} is {}".format(alist, hist.largest_rect())) \ No newline at end of file + print("reverse of {} is {}".format(alist, reverse(alist))) + print("reverse2 of {} is {}".format(alist, reverse2(alist))) diff --git a/test4/.idea/misc.xml b/test4/.idea/misc.xml index 2856404..e524f65 100644 --- a/test4/.idea/misc.xml +++ b/test4/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test4/.idea/modules.xml b/test4/.idea/modules.xml index cbb2cf7..557cc95 100644 --- a/test4/.idea/modules.xml +++ b/test4/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test31/.idea/test31.iml b/test4/.idea/test31.iml similarity index 100% rename from test31/.idea/test31.iml rename to test4/.idea/test31.iml diff --git a/test31/.idea/workspace.xml b/test4/.idea/workspace.xml similarity index 100% rename from test31/.idea/workspace.xml rename to test4/.idea/workspace.xml diff --git a/test4/main.py b/test4/main.py index 078b493..a84595b 100644 --- a/test4/main.py +++ b/test4/main.py @@ -1,5 +1,4 @@ -# mingle two strings after crerating chunks in size n -# e.g. ABCDEFG and 1234567890 with 2 char chunks -> AB12CD34EF56G7890 +# This script recovers a binary search tree with 2 replaced nodes # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -20,54 +19,155 @@ # along with this program. If not, see . # -class merger(): - def __init__(self, list1, list2): - self.list1 = list1 - self.list2 = list2 - lista = listb = [] +def create_btree(alist): + bt = None + if alist != None and alist != []: + bt = btree(alist[0]) + for each in alist[1:]: + add_btree(bt, each) + return bt - def merge(self, offset): - flist = list() - - if len(self.list1) < len(self.list2): - lista = self.list1 - listb = self.list2 +def add_btree(bt, data): + if data == None: + pass + elif bt == None: + bt = btree(data) + else: + if data == bt.data: + pass #duplicate, do don't do anything (or raise an except + elif data < bt.data: + if bt.left: + add_btree(bt.left, data) + else: + bt.left = btree(data) else: - listb = self.list1 - lista = self.list2 + if bt.right: + add_btree(bt.right, data) + else: + bt.right = btree(data) + +def recover_btree(bt): + reclist = bt.recover() + print("MIN misplaced {} and MAX misplaced {}".format(bt.recmin.data, bt.recmax.data)) + swap_data(bt.recmin, bt.recmax) + return reclist + +def swap_data(a, b): + temp = a.data + a.data = b.data + b.data = temp + +class btree(): + def __init__(self, data): + self.data = data + self.left = self.right = self.parent = None + self.resetrecovery() + + def resetrecovery(self): + self.recmin = self.recmax = None + + # set minimum misplaced node + def setrecmin(self, node): + if(node): + if(self.recmin == None or self.recmin.data > node.data): + self.recmin = node + + # set maximum misplaced node + def setrecmax(self, node): + if(node): + if(self.recmax == None or self.recmax.data < node.data): + self.recmax = node + + def to_list(self): + alist = [] + + if self.left: + alist.extend(self.left.to_list()) + alist.append(self) + if self.right: + alist.extend(self.right.to_list()) + + return alist + + def to_data_list(self): + alist = [] + + if self.left: + alist.extend(self.left.to_data_list()) + + alist.append(self.data) + + if self.right: + alist.extend(self.right.to_data_list()) + + return alist + + def to_data_tlist(self): + alist = [] + + if self.left: + alist.append(self.left.to_data_tlist()) + + alist.append(self.data) + + if self.right: + alist.append(self.right.to_data_tlist()) - times = int(len(lista)/offset) - for i in range(times): - flist = flist + lista[i*offset:i*offset+offset] - flist = flist + listb[i*offset:i*offset+offset] - flist = flist + lista[times*offset:len(lista)] - flist = flist + listb[times*offset:len(listb)] + return alist - return(flist) + def recover(self): + ll = [] + rl = [] + self.resetrecovery() -if __name__ == '__main__': + if self.left: + ll = self.left.recover() + self.setrecmin(self.left.recmin) + self.setrecmax(self.left.recmax) + if ll[-1] and (ll[-1].data > self.data): + self.setrecmin(self) + self.setrecmax(ll[-1]) - # TEST#1 - tlist1a = ["2","3","4","2","3","5","2","4","3","5","6","4","5"] - tlist1b = ["a","s","d","a","s","d","a","s","f","d","s","g","g","d","f","g","d","f","f","g","h","j","f","g","h","j","g","h","j"] + if self.right: + rl = self.right.recover() + self.setrecmin(self.right.recmin) + self.setrecmax(self.right.recmax) + if rl[0] and (rl[0].data < self.data): + self.setrecmin(rl[0]) + self.setrecmax(self) - m1 = merger(tlist1a, tlist1b) - num1 = 2 - print("TEST1 - {} char merged list = {}".format(num1, m1.merge(num1))) + ll.append(self) + ll.extend(rl) + dl = [] + #for each in ll: + # dl.append(each.data) + #print ("recover = {}".format(dl)) + return ll - # TEST#2 - tlist2a = ["1","2","3","2","3","4","2","4","5","3","6","4","5","7","5","6","7","5","8","6","7","9","7","8","0","8","9","0"] - tlist2b = ["x","c","v","x","c","v","c","v","b","n","f","g","h","y","r","t","y","r","t","y"] +if __name__=="__main__": - m2 = merger(tlist2a, tlist2b) - num2 = 3 - print("TEST2 - {} char merged list = {}".format(num2, m2.merge(num2))) + bt = create_btree([1, 2, 30, 4, 60, 34, 12, -1, 5, 23, 67, 35, 4, 99, -20, -45, 89, 78]) + tlist = bt.to_list() + print("Original tlist = ", bt.to_data_tlist()) - # TEST#3 - tlist3a = ["5","6","7","8","9"] - tlist3b = ["q","w","e","s","k"] + #test 6th and 11th replacement + swap_data(tlist[5], tlist[10]) + print("broken list = ", bt.to_data_tlist()) + reclist = recover_btree(bt) + print("recovered list = ", bt.to_data_list()) - m3 = merger(tlist3a, tlist3b) - num3 = 4 - print("TEST3 - {} char merged list = {}".format(num3, m3.merge(num3))) + tlist = bt.to_list() + print("\n\nOriginal tlist = ", bt.to_data_tlist()) + # test min and max replacement + swap_data(tlist[0], tlist[16]) + print("broken list = ", bt.to_data_tlist()) + reclist = recover_btree(bt) + print("recovered list = ", bt.to_data_list()) + tlist = bt.to_list() + print("\n\nOriginal tlist = ", bt.to_data_tlist()) + # test 7th and 15th replacement + swap_data(tlist[6], tlist[14]) + print("broken list = ", bt.to_data_tlist()) + reclist = recover_btree(bt) + print("recovered list = ", bt.to_data_list()) diff --git a/test12/.DS_Store b/test40/.DS_Store similarity index 100% rename from test12/.DS_Store rename to test40/.DS_Store diff --git a/test4/.idea/aws.xml b/test40/.idea/aws.xml similarity index 100% rename from test4/.idea/aws.xml rename to test40/.idea/aws.xml diff --git a/test40/.idea/misc.xml b/test40/.idea/misc.xml index 65531ca..c1f6583 100644 --- a/test40/.idea/misc.xml +++ b/test40/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test40/.idea/modules.xml b/test40/.idea/modules.xml index 4b03934..76c0ada 100644 --- a/test40/.idea/modules.xml +++ b/test40/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test3/.idea/test3.iml b/test40/.idea/test12.iml similarity index 100% rename from test3/.idea/test3.iml rename to test40/.idea/test12.iml diff --git a/test40/main.py b/test40/main.py index 8484602..09f9e04 100644 --- a/test40/main.py +++ b/test40/main.py @@ -1,4 +1,4 @@ -# This script returns level order of a binary tree +# check if a string has all digits # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -18,79 +18,25 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # -def create_btree(alist): - head = None - if not alist or alist == []: - pass - else: - tn = treenode(alist[0]) - head = tn - for item in alist[1:]: - tn.add_node(item) - return head +class digitstr(str): -def create_levelorder(tn): - lvl = 0 - lolist = list() - tn.levelorder(lolist, 0) + def __init__(self, astr): + self = astr - return lolist + def alldigits(self): + if self == "": return False + else: return(self.checkdig(self)) -class treenode(): - def __init__(self, data): - self.data = data - self.left = None - self.right = None - - def add_node(self, data): - if(dataself.data): - if(self.right): - self.right.add_node(data) - else: - self.right = treenode(data) + def checkdig(self, astr): + if(astr == ""): + return True + elif(astr[0].isdigit()): + return self.checkdig(astr[1:]) else: - pass # duplicate node, just ignore - - def levelorder(self, lolist, lvl): - if(len(lolist) <= lvl): - lolist.append(list()) - - lolist[lvl].append(self.data) - if(self.left): - self.left.levelorder(lolist, lvl+1) - - if(self.right): - self.right.levelorder(lolist, lvl+1) - -if __name__ == "__main__": - - tlist = [20, 34, 10, 11, 45, 42, 13, 17, 25, 28, 5, 7] - - tr = create_btree(tlist) - - lolist = create_levelorder(tr) - - print("test#1 - levelorder of {} is {}".format(tlist, lolist)) - - tlist = [15, 2, 60, 72, 48, 12, 11, 20, 34, 10, 11, 45, 42, 13, 17, 25, 28, 5, 7] - - tr = create_btree(tlist) - - lolist = create_levelorder(tr) - - print("test#2 - levelorder of {} is {}".format(tlist, lolist)) - - tlist = [1] - - tr = create_btree(tlist) - - lolist = create_levelorder(tr) + return False - print("test#3 - levelorder of {} is {}".format(tlist, lolist)) +if __name__ == '__main__': + astr = digitstr("23423423y5") + print("alldigit? = ", astr.alldigits()) diff --git a/test6/.DS_Store b/test41/.DS_Store similarity index 100% rename from test6/.DS_Store rename to test41/.DS_Store diff --git a/test5/.idea/aws.xml b/test41/.idea/aws.xml similarity index 100% rename from test5/.idea/aws.xml rename to test41/.idea/aws.xml diff --git a/test41/.idea/misc.xml b/test41/.idea/misc.xml index 65531ca..10b2d30 100644 --- a/test41/.idea/misc.xml +++ b/test41/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test41/.idea/modules.xml b/test41/.idea/modules.xml index a191b2b..1c1ae1d 100644 --- a/test41/.idea/modules.xml +++ b/test41/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test6/.idea/test6.iml b/test41/.idea/test6.iml similarity index 100% rename from test6/.idea/test6.iml rename to test41/.idea/test6.iml diff --git a/test41/main.py b/test41/main.py index de4181b..7ae338a 100644 --- a/test41/main.py +++ b/test41/main.py @@ -1,4 +1,5 @@ -# This script implements a search typehead +# This script demonstrates trying and catching exceptions while getting an a positive integer as an input +# and printing its square # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -18,91 +19,32 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # -class search_typehead(): - def __init__(self, alist): - self.adict = dict() - thn = None - for word in alist: - print("word = {}".format(word)) - thn = self.adict.get(word[0]) - if not thn: - thn = thnode(word[0]) - self.adict[word[0]] = thn - thn.add_word(word, 1) - - def find_typehead(self, wpart): - - thn = self.adict.get(wpart[0]) - if not thn: - return [] - else: - return thn.find_typehead(wpart, 1) - - def print(self): - for each in self.adict.values(): - print("search_typehead = {}".format(each)) - each.print() - -class thnode(): - def __init__(self, achar): - self.char = achar - self.next = dict() - self.word = None - - def add_word(self, word, index): - if index == len(word) - 1: - self.word = word - else: - thn = self.next.get(word[index]) - if not thn: - thn = thnode(word[index]) - self.next[word[index]] = thn - - thn.add_word(word, index+1) - - def find_typehead(self, wpart, index): - thlist = [] - - if index == len(wpart): - if(self.word): - thlist.append(self.word) - - for item in self.next.values(): - alist = item.find_typehead(wpart, index) - thlist.extend(alist) - else: - alist = [] - thn = self.next.get(wpart[index]) - if thn: - alist = thn.find_typehead(wpart, index + 1) - - thlist.extend(alist) - - return thlist - - def print(self): - print("char = {} word = {}".format(self.char, self.word)) - print("dictionary:") - for each in self.next.values(): - each.print() - -if __name__=="__main__": - alist = ["michael", "michael phelp", "mich", "john", "john wayne", - "johny", "mark", "markus", "michael phone", "mindy", "joan", "joan ark"] - - sth = search_typehead(alist) - - sth.print() - - wpart = "mic" - print("typehead list for {} is {} ".format(wpart, sth.find_typehead(wpart))) - - wpart = "jo" - print("typehead list for {} is {} ".format(wpart, sth.find_typehead(wpart))) - - wpart = "min" - print("typehead list for {} is {} ".format(wpart, sth.find_typehead(wpart))) - - wpart = "po" - print("typehead list for {} is {} ".format(wpart, sth.find_typehead(wpart))) +class square(int): + def __init__(self, num): + self = num + + def getnum(self): + return self + + def getsqr(self): + return (self * self) + +# Press the green button in the gutter to run the script. +if __name__ == '__main__': + + try: + numstr = input("Enter a number: ") + num = int(numstr) + if num < 0: raise ValueError + except NameError: + print("Name Error") + except ValueError: + print("Value Error") + except IOError: + print("I/O Error") + except: + print("not a valid entry") + else: + numobj = square(num) + print("Square of {0} is {1}".format(numobj.getnum(), numobj.getsqr())) diff --git a/test3/.DS_Store b/test43/.DS_Store similarity index 100% rename from test3/.DS_Store rename to test43/.DS_Store diff --git a/test43/.idea/.gitignore b/test43/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/test43/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/test7/.idea/aws.xml b/test43/.idea/aws.xml similarity index 100% rename from test7/.idea/aws.xml rename to test43/.idea/aws.xml diff --git a/test43/.idea/inspectionProfiles/profiles_settings.xml b/test43/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/test43/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/test43/.idea/misc.xml b/test43/.idea/misc.xml new file mode 100644 index 0000000..fc30dfa --- /dev/null +++ b/test43/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/test43/.idea/modules.xml b/test43/.idea/modules.xml new file mode 100644 index 0000000..82cf164 --- /dev/null +++ b/test43/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/test43/.idea/test3.iml b/test43/.idea/test3.iml new file mode 100644 index 0000000..74d515a --- /dev/null +++ b/test43/.idea/test3.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/test43/.idea/vcs.xml b/test43/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/test43/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/test43/main.py b/test43/main.py new file mode 100644 index 0000000..f74f65f --- /dev/null +++ b/test43/main.py @@ -0,0 +1,55 @@ +# This script manipulates a number string by adding a "*" between two +# consecutive even numbers and "-" between two consecutive odd numbers +# +# This script is a part of the Easy Python project which creates a number +# sample python scripts to answer simple programming questions. The +# entire project is accessible at https://github.com/okany/easypython. +# Copyright (c) 2021 Okan Yilmaz +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +class strmanup(str): + def __init__(self, astr): + super().__init__() + self.offset = 0 + self = astr + + def isEven(self, i): + return((int(self[i]) % 2) == 0) + + def isOdd(self, i): + return((int(self[i]) % 2) != 0) + + def manupstr(self, offset): + newstr = "" + if(len(self) - + \ No newline at end of file diff --git a/test5/.idea/modules.xml b/test5/.idea/modules.xml index f5ac542..a191b2b 100644 --- a/test5/.idea/modules.xml +++ b/test5/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test41/.idea/test41.iml b/test5/.idea/test41.iml similarity index 100% rename from test41/.idea/test41.iml rename to test5/.idea/test41.iml diff --git a/test5/main.py b/test5/main.py index 0230544..de4181b 100644 --- a/test5/main.py +++ b/test5/main.py @@ -1,4 +1,4 @@ -# This script finds the common words in two lists +# This script implements a search typehead # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -18,35 +18,91 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # +class search_typehead(): + def __init__(self, alist): + self.adict = dict() + thn = None + for word in alist: + print("word = {}".format(word)) + thn = self.adict.get(word[0]) + if not thn: + thn = thnode(word[0]) + self.adict[word[0]] = thn -class listops(): - def __init__(self, lista, listb): - self.listA = lista - self.listB = listb - self.mdict = dict() - def intersect(self): - for item in self.listA: - if(self.mdict.get(item) != None): - self.mdict[item] = self.mdict[item] + 1 - else: - self.mdict[item] = 1 - for item in self.listB: - if(self.mdict.get(item) != None): - print("Intersected=", item) - def printdict(self): - print("DICT= {}".format(self.mdict)) - -if __name__ == '__main__': - lista = ["apple", "orange", "apple", "pinapple", "melon", "melon", "blueberry"] - listb = ["raspbery", "apple", "pinapple", "watermelon", "banana"] - - lo1 = listops(lista, listb) - lo1.intersect() - lo1.printdict() - - str1 = "In this study we used domain engineering as a method for gaining deeper formal understanding of a class of algorithms. Specifically, we analyzed 6 stemming algorithms from 4 different sub-domains of the conflation algorithms domain and developed formal domain models and generators based on these models. The application generator produces source code for not only affix removal but also successor variety, table lookup, and n-gram stemmers. The performance of the generated stemmers was compared with the stemmers developed manually in terms of stem similarity, source, and executable sizes, and development and execution times. Five of the stemmers generated by the application generator produced more than 99.9% identical stems with the manually developed stemmers. Some of the generated stemmers were as efficient as their manual equivalents and some were not." - str2 = "In the early 1980s software companies started the systematic reuse process through domain engineering to improve software productivity and quality. There has been insufficient empirical study of the domain engineering process and domain products such as reusable components and generators. This paper addresses this problem by documenting and empirically evaluating a domain engineering project for the conflation algorithms domain. This domain is important for many types of systems such as information retrieval systems, search engines, and word processors. The application generator developed for this study extends the domain scope compared to previous ones." - - lo2 = listops(str1.split(), str2.split()) - lo2.intersect() - lo2.printdict() + thn.add_word(word, 1) + + def find_typehead(self, wpart): + + thn = self.adict.get(wpart[0]) + if not thn: + return [] + else: + return thn.find_typehead(wpart, 1) + + def print(self): + for each in self.adict.values(): + print("search_typehead = {}".format(each)) + each.print() + +class thnode(): + def __init__(self, achar): + self.char = achar + self.next = dict() + self.word = None + + def add_word(self, word, index): + if index == len(word) - 1: + self.word = word + else: + thn = self.next.get(word[index]) + if not thn: + thn = thnode(word[index]) + self.next[word[index]] = thn + + thn.add_word(word, index+1) + + def find_typehead(self, wpart, index): + thlist = [] + + if index == len(wpart): + if(self.word): + thlist.append(self.word) + + for item in self.next.values(): + alist = item.find_typehead(wpart, index) + thlist.extend(alist) + else: + alist = [] + thn = self.next.get(wpart[index]) + if thn: + alist = thn.find_typehead(wpart, index + 1) + + thlist.extend(alist) + + return thlist + + def print(self): + print("char = {} word = {}".format(self.char, self.word)) + print("dictionary:") + for each in self.next.values(): + each.print() + +if __name__=="__main__": + alist = ["michael", "michael phelp", "mich", "john", "john wayne", + "johny", "mark", "markus", "michael phone", "mindy", "joan", "joan ark"] + + sth = search_typehead(alist) + + sth.print() + + wpart = "mic" + print("typehead list for {} is {} ".format(wpart, sth.find_typehead(wpart))) + + wpart = "jo" + print("typehead list for {} is {} ".format(wpart, sth.find_typehead(wpart))) + + wpart = "min" + print("typehead list for {} is {} ".format(wpart, sth.find_typehead(wpart))) + + wpart = "po" + print("typehead list for {} is {} ".format(wpart, sth.find_typehead(wpart))) diff --git a/test6/.idea/misc.xml b/test6/.idea/misc.xml index 10b2d30..8161a60 100644 --- a/test6/.idea/misc.xml +++ b/test6/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/test6/.idea/modules.xml b/test6/.idea/modules.xml index 1c1ae1d..0423e98 100644 --- a/test6/.idea/modules.xml +++ b/test6/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test26/.idea/test26.iml b/test6/.idea/test26.iml similarity index 100% rename from test26/.idea/test26.iml rename to test6/.idea/test26.iml diff --git a/test6/main.py b/test6/main.py index 7ae338a..75cb854 100644 --- a/test6/main.py +++ b/test6/main.py @@ -1,5 +1,4 @@ -# This script demonstrates trying and catching exceptions while getting an a positive integer as an input -# and printing its square +# This script implements bubble sort, insertion sort, quick sort, merge sort, and bucket sort algorithms # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -20,31 +19,149 @@ # along with this program. If not, see . # -class square(int): - def __init__(self, num): - self = num +class slist(list): - def getnum(self): - return self + def __init__(self, slist): + super().__init__(slist) + self.blist = slist + self.ilist = slist + self.bclist = [] - def getsqr(self): - return (self * self) + def bubblesort(self): + last = len(self) - 1 + while last > 0: + for i in range(last): + if self.blist[i] > self.blist[i+1]: + temp = self.blist[i] + self.blist[i] = self.blist[i+1] + self.blist[i+1] = temp + last = last - 1 + return self.blist -# Press the green button in the gutter to run the script. -if __name__ == '__main__': + def insertionsort(self): + last = len(self) + first = 0 + while first < last: + min = self.ilist[first] + mindex = first + for i in range(first+1, last): + if self.ilist[i] < min: + min = self.ilist[i] + mindex = i + if(mindex != first): + self.ilist.pop(mindex) + self.ilist.insert(0,min) + first = first + 1 + + return self.ilist + + def findminmax(self): + min = max = self[0] + for each in self: + if each < min: + min = each + elif each > max: + max = each + return min, max + + def bucketsort(self, k): + if(len(self)<=1): return self + min, max = self.findminmax() + bucket = [] + bsize = int((max - min)/k)+1 + for i in range(k): + bucket.append([]) + for each in self: + bucket[int((each-min)/bsize)].append(each) + + for i in range(k): + alist = slist(bucket[i]) + self.bclist.extend(alist.insertionsort()) + + return self.bclist + + +def partition(list, pi): + low = [] + high = [] + for i in range(len(list)): + if i == pi: pass + elif list[i] > list[pi]: + high.append(list[i]) + else: + low.append(list[i]) + return low, high + +def quicksort(list): + if(list == None): return None + elif(len(list) <= 1): + return list + else: + low, high = partition(list, 0) + # print("low = {}, pivot = {}, high = {}".format(low, list[0], high)) + qlist = quicksort(low) + qlist.append(list[0]) + qlist.extend(quicksort(high)) + + return qlist - try: - numstr = input("Enter a number: ") - num = int(numstr) - if num < 0: raise ValueError - except NameError: - print("Name Error") - except ValueError: - print("Value Error") - except IOError: - print("I/O Error") - except: - print("not a valid entry") +def mergesort(list): + if list == None: return None + elif(len(list) <=1): return list else: - numobj = square(num) - print("Square of {0} is {1}".format(numobj.getnum(), numobj.getsqr())) + mid = int(len(list)/2) + alist = list[:mid] + blist = list[mid:] + amlist = mergesort(alist) + bmlist = mergesort(blist) + i = j = 0 + mlist = [] + while(i - + \ No newline at end of file diff --git a/test7/.idea/modules.xml b/test7/.idea/modules.xml index 3617fc4..6d9c0ed 100644 --- a/test7/.idea/modules.xml +++ b/test7/.idea/modules.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/test36/.idea/test36.iml b/test7/.idea/test36.iml similarity index 100% rename from test36/.idea/test36.iml rename to test7/.idea/test36.iml diff --git a/test7/main.py b/test7/main.py index cf01efd..5fde7d2 100644 --- a/test7/main.py +++ b/test7/main.py @@ -1,4 +1,4 @@ -# count the occurrence of each word in a list +# This script finds the largest rectangle in a histogram # # This script is a part of the Easy Python project which creates a number # sample python scripts to answer simple programming questions. The @@ -18,32 +18,107 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # - -class listcount(list): +class histogram(list): def __init__(self, alist): + # pad the list with 0s to set boundaries for the calculation + # the 0s act like histogram data with 0 value on each side of the histogram + # this simplifies the program while does not affect the result + alist.insert(0,0) + alist.append(0) super().__init__(alist) - self.adict = dict() - self.createdict() + self.sorted = [] + self.used = [] + self.max_rect_area = 0 + print("alist= {}".format(alist)) + + def insert_sorted(self, i): + index = 0 + while index < len(self.sorted): + # print("insert_sorted index={} self.sorted={} len(self.sorted)={} i={}".format(index, self.sorted, len(self.sorted), i)) + if self[self.sorted[index]] > self[i]: + break + index += 1 + + self.sorted.insert(index, i) + + def create_sorted(self): + self.sorted.append(0) + + for i in range(1, len(self)): + self.insert_sorted(i) + print("self.sorted = {}".format(self.sorted)) + + def insert_used(self, i): + index = 0 + while index < len(self.used): + if self.used[index] > i: + break + index += 1 + self.used.insert(index, i) + + return index + + def initialize_used(self): + # initialize the used list with imaginary histogram blocks + self.used = [] + + def get_used_value(self, index): + return(self[self.used[index]]) + + def calculate_rectangle_area(self, used_index): + print("self.used = {} used_index = {} self[used_index] = {}".format(self.used, used_index, self[used_index])) + + # return 0 for the boundary values + if(used_index == 0 or used_index == len(self.used) -1 ): return 0 - def createdict(self): - for item in self: - if (self.adict.get(item) == None): - self.adict[item] = 1 - else: - self.adict[item] = self.adict[item]+1 + prev = used_index - 1 + while prev > 0 and self.get_used_value(prev) == self.get_used_value(used_index): + prev -= 1 - def printcounts(self): - print("WORD COUNT = {}".format(self.adict)) + print("prev = {}".format(prev)) + next = used_index + 1 + while next < len(self.used)-1 and self.get_used_value(next) == self.get_used_value(used_index): + next += 1 + + print("next = {}".format(next)) + + rect_area = self[self.used[used_index]] * (self.used[next] - self.used[prev] - 1 ) + + return rect_area + + def largest_rect(self): + # sort all histogram values in increasing order + # first rectangle will be bounded by the shortest historam value + self.create_sorted() + # initialize used with two imaginary histogram values 0 and histogram+1 values + self.initialize_used() + + while self.sorted != []: + # calculate the area of the first rectangle + hist_val = self.sorted.pop(0) + # insert the popped histogram value into the used histogram list + used_index = self.insert_used(hist_val) + rect_area = self.calculate_rectangle_area(used_index) + print("rect_area = {}".format(rect_area)) + + if(rect_area > self.max_rect_area): + # update the max rectangle area if the area is greater + self.max_rect_area = rect_area + + return self.max_rect_area + +# Press the green button in the gutter to run the script. if __name__ == '__main__': - test1 = "Conflation algorithms areused in Information Retrieval (IR) systems for matching the morphological variants of terms for efficient indexing and faster retrieval operations. The conflation process can be done either manually or automatically. The automatic conflation operation is also called stemming. Frakes [1] categorizes stemming methods into four groups: Manuscript received July 9, 2007. Okan Yilmaz, Student Member, IEEE, William Frakes, Member, IEEE A Case Study of Using Domain Analysis for the Conflation Algorithms Domain IN the early 1980s software companies started the systematic reuse process through domain engineering to improve software productivity and quality. There has been insufficient empirical study of the domain engineering process and domain products such as reusable components and generators. This paper addresses this problem by documenting and empirically evaluating a domain engineering project for the conflation algorithms domain. This domain is important for many types of systems such as information retrieval systems, search engines, and word processors. The application generator developed for this study extends the domain scope compared to previous ones. affix removal, successor variety, n-gram and table lookup. Affix removal is the most intuitive and commonly used of these algorithm types. In order to determine the stem, affix removal algorithms remove suffixes and sometimes also prefixes of terms. Successor variety and n-gram methods analyze a word corpus to determine the stems of terms. Successor variety bases its analysis on the frequency of letter sequences in terms, while n-gram conflates terms into groups based on the ratio of common letter sequences, called n-grams. Table lookup based methods use tables which map terms to their stems." - test2 = "We did a domain analysis for the semantic automatic conflation algorithms domain. We analyzed 3 affix removal stemmers, a successor variety stemmer, an n-gram stemmer, and a table lookup stemmer. Based on this analysis, we created a generic architecture, determined reusable components, and designed and developed a little language and an application generator for this domain. We compared the performance of the automatically generated algorithms with their original versions and found that automatically generated versions of the algorithms are nearly as precise as the original versions." - list1 = list(test1.split()) - list2 = list(test2.split()) + alist = [12, 15, 17, 25, 40, 55, 30, 24, 60, 80, 90] + + hist = histogram(alist) + + print("LARGEST RECTANGLE FOR {} is {}".format(alist, hist.largest_rect())) + + alist = [12, 15, 17, 25, 25, 14, 12, 40, 55, 30, 24, 18, 18, 20, 60, 80, 90] - wc1 = listcount(list1) - wc1.printcounts() + hist = histogram(alist) - wc2 = listcount(list2) - wc2.printcounts() + print("LARGEST RECTANGLE FOR {} is {}".format(alist, hist.largest_rect())) \ No newline at end of file