def reorder_list(orig_list): dummy = ListNode(0) dummy.next = orig_list.head p = q = dummy # find the break point while p and p.next: p = p.next.next q = q.next # break the list r = q.next q.next = None second_half = LinkList() second_half.head = r # reverse the second half second_half.reverse_list() # merge p = orig_list.head r = second_half.head while r: p_next = p.next r_next = r.next r.next = p.next p.next = r r = r_next p = p_next del second_half return orig_list
def add_lists_reverse(list1, list2): ''' add two lists in reverse order ''' p = list1.head q = list2.head carry = 0 sum_list = LinkList() while p and q: curr_sum_digit = (p.data + q.data + carry) % 10 carry = (p.data + q.data + carry) / 10 sum_list.append_node(ListNode(curr_sum_digit)) p = p.next q = q.next while q: curr_sum_digit = (q.data + carry) % 10 carry = (q.data + carry) / 10 sum_list.append_node(ListNode(curr_sum_digit)) q = q.next while p: curr_sum_digit = (p.data + carry) % 10 carry = (p.data + carry) / 10 sum_list.append_node(ListNode(curr_sum_digit)) p = p.next if carry == 1: sum_list.append_node(ListNode(1)) return sum_list
def add_two_lists(list1, list2): sum_list = LinkList() p = list1.head q = list2.head carry = 0 while p or q: first = p.data if p else 0 second = q.data if q else 0 sum = first + second + carry carry = sum / 10 sum = sum % 10 sum_list.append_node(ListNode(sum)) if p: p = p.next if q: q = q.next if carry: sum_list.append_node(ListNode(carry)) return sum_list
def create(): #创建41人节点 dic = {} for i in range(1,42): linknode_val = {"num":i, "note":False} dic["P{}".format(i)] = LinkList.LinkList.LinkNode(linknode_val, None) if i == 16: dic["P{}".format(i)].val["note"] = True if i == 31: dic["P{}".format(i)].val["note"] = True #将链表连接,变成循环链表 link = LinkList.LinkList() link.link_list() link.head = dic["P1"] cur = link.head for i in range(2,42): cur.next = dic["P{}".format(i)] print(cur.next, i) cur = cur.next dic["P41"].next = link.head print(dic["P41"].next) #进行问题模拟 n = 41 count = 1 cur = link.head while n > 2: count += 1 if count % 3 == 0: cur.next = cur.next.next count = 1 n -=1 cur = cur.next if n == 2: print(cur.val["note"], cur.next.val["note"])
def merge_lists(lists): ''' merge len(lists) sorted linked lists, and return the result linked list ''' for each_list in lists: each_list.append_node(ListNode(sys.maxint)) min_heap = Heap() result_list = LinkList() curr_nodes = [each_list.head for each_list in lists] curr_datas = [node.data for node in curr_nodes] # build the heap according to curr_datas min_heap.build_heap('min', curr_datas) # min_heap.heap[0] == maxint means all the lists go to end, only then, stop the while loop while min_heap.heap[0] != sys.maxint: # extract min node curr_min = min_heap.extract_node() # append to result result_list.append_node(ListNode(curr_min)) min_index = curr_datas.index(curr_min) curr_nodes[min_index] = curr_nodes[min_index].next curr_datas[min_index] = curr_nodes[min_index].data # insert the extracted node's next's data, and re-heapify min_heap.add_node(curr_datas[min_index]) return result_list
def merge_two_lists_1(listA, listB): p = listA.head q = listB.head if not p: return listB if not q: return listA result_list = LinkList() #tail = ListNode(0) #tail.next = result_list.head while p and q: if p.data < q.data: result_list.append_node(ListNode(p.data)) p = p.next else: result_list.append_node(ListNode(q.data)) q = q.next if p: result_list.append_node(p) if q: result_list.append_node(q) return result_list
class UnorderList: list1 = LinkList() f = open('demo.txt', 'rw+') split_Word = f.read().split(" ") index = 0 length = len(split_Word) while index < length: list1.insertdata(str(split_Word[index])) index += 1 list1.printList() word = raw_input("enter the word which you want to search\n") result = list1.search(word) if result: list1.deleteword(word) list1.printList() else: list1.insertdata(word) list1.printList() list1.updateList() # print f.read() f.close()
def __init__(self): self.linklist = LinkList.LinkList()
Input: 1->2->3 Output: 2->1->3 Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. ''' from LinkList import * def swap_nodes(my_list): dummy = ListNode(0) dummy.next = my_list.head p = dummy while p.next and p.next.next: q = p.next r = q.next if not r: return my_list p.next = r q.next = r.next r.next = q p = q my_list.head = dummy.next return my_list if __name__ == '__main__': test_cases = [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1], []] for each_test_case in test_cases: curr_linkedlist = LinkList(each_test_case) swap_nodes(curr_linkedlist).print_list()
dummy = ListNode(0) dummy.next = my_list.head h = my_list.head new_head = dummy while h: i+=1 if i % k == 0: new_head = reverse(new_head, k) h = new_head.next else: h = h.next my_list.head = dummy.next return my_list def reverse(new_head, k): p = new_head.next while k-1 > 0: q=p.next p.next=q.next q.next=new_head.next new_head.next=q k-=1 return p if __name__=='__main__': test_cases=[([1,2,3,4,5],2), ([1,2,3,4,5],3)] for each_test_case in test_cases: linkedlist = LinkList(each_test_case[0]) k = each_test_case[1] reverse_nodes_in_k_group(linkedlist, k).print_list()
''' 3->1->2->5->2->1->3 compare 3f to 3b(return value) if equal, return (True, None) first_node=3f, length=7 1->2->5->2->1->3 compare 1f(3f.next) to 1b(return value) if equal, return (True, 3b(1f.next)) first_node=1f(3f.next), length=5 2->5->2->1->3 compare 2f(1f.next) to 2b(return value) if equal, return (True, 1b(2b.next)) first_node=2f(1f.next), length=3 5->2->1->3 first_node=5 length==1 return (True, 2b) ''' def isPalindrome_2_helper(first_node, length): if length == 0: return (True, first_node) if length == 1: return (True, first_node.next) front_node = first_node return_tuple = isPalindrome_2_helper(first_node.next, length - 2) return_result = return_tuple[0] back_node = return_tuple[1] if return_result == False: return (False, back_node.next) if front_node.data != back_node.data: return (False, back_node.next) else: return (True, back_node.next) if __name__ == '__main__': a = LinkList([3, 1, 2, 5, 2, 1, 3]) print isPalindrome_1(a) print isPalindrome_2(a)
fast = fast.next.next l1 = head l2 = slow.next slow.next = None nh_1 = merge_sort_list_helper(l1) nh_2 = merge_sort_list_helper(l2) return merge(nh_1, nh_2) def merge(l1, l2): if not l1: return l2 if not l2: return l1 if l1.data <= l2.data: l1.next = merge(l1.next, l2) return l1 else: l2.next = merge(l1, l2.next) return l2 if __name__ == '__main__': test_cases = [[3, 7, 4, 8, 6, 5], [10, 7, 4, 11, 5, 2, 6, 19, 1], [1], [5, 4], [6, 5, 4, 3, 2, 2], [10, 4, 7, 11, 5, 11, 2, 4]] for each_test_case in test_cases: orig_list = LinkList(each_test_case) insertion_sort_list(orig_list).print_list() orig_list = LinkList(each_test_case) merge_sort_list(orig_list).print_list()
class StockAccountImplementation: list_obj = LinkedListStack() linklist_obj = LinkList() customer_info = json.load(open("customer.json", "r")) company_info = json.load(open("company.json", "r")) transaction_obj = json.load(open("transaction.json", "r")) name_keys = list(customer_info["customers"].keys()) # /* # * Function to save # * @param year # * @return # */ def save(self, customer, name, choice): print "defination" print choice if choice == 1: self.customer_info["customers"][name] = ({ "cname": customer["cname"], "noOfShare": customer["noOfShare"], "amount_per_share": customer["amount_per_share"] }) # print customer_info with open('customer.json', 'w') as data: json.dump(self.customer_info, data) print("Person Detail Added Successfully!") else: print self.company_info self.company_info[name] = ({ "company_name": customer["company_name"], "company_symbol": customer["company_symbol"], "share_Price": customer["share_Price"], "total_share": customer["total_share"] }) # print self.company_info with open('company.json', 'w') as data1: json.dump(self.company_info, data1) print("Person Detail Added Successfully!") # def save_transaction(self,name,company,transaction,new_customer_amount,new_no_of_share,new_company_share): # self.transaction_obj = ({ # "customer_name": transaction["customer_name"], # "company_symbol":transaction["company_symbol"], # "buy_sell": transaction["buy_sell"], # "total_share": transaction["total_share"], # "total_Price": transaction["total_Price"], # "time": transaction["time"], # # }) # with open('customer.json', 'r') as file: # json_data = json.load(file) # name_key = list(self.customer_info["customers"]) # for item in name_key: # if item == name: # self.customer_info["customers"][item]["amount_per_share"] = str(new_customer_amount) # self.customer_info["customers"][item]["noOfShare"] = str(new_no_of_share) # # print ("Person Detail Added Successfully!") # # with open('customer.json', 'w') as data: # json.dump(self.customer_info, data) # name_keys = list(self.company_info.keys()) # print self.company_info # for item in name_keys: # if item == company["company_name"]: # # print company_info[item]["total_share"] # self.company_info[item]["total_share"] = str(new_company_share) # print ("Person Detail Added Successfully!") # # with open('company.json', 'w') as data: # json.dump(self.company_info, data) # # with open('transaction.json', 'w') as data: # json.dump(self.transaction_obj, data) def add_customer(self): print "Customer Information" name = raw_input("enter customer name : ") amount = raw_input("enter a amount : ") no_Of_Share = raw_input("Enter the Number Of Share : ") customer_obj = Customer(name, amount, no_Of_Share) customer_obj.set_customer_name(name) customer_obj.set_amount(amount) customer_obj.set_noOfShare(no_Of_Share) name = customer_obj.get_customer_name() customer = ({ "cname": customer_obj.get_customer_name(), "noOfShare": customer_obj.get_noOfShare(), "amount_per_share": customer_obj.get_amount() }) self.list_obj.push(customer) self.save(customer, name, 1) def display_customer(self): print "\t\tName\tNoOfShare\tAmount\t" self.list_obj.display() for data in self.name_keys: print "\t\t",self.customer_info["customers"][data]["cname"],"\t\t",\ self.customer_info["customers"][data]["noOfShare"],"\t\t",\ self.customer_info["customers"][data]["amount_per_share"] print "\n" def add_company(self): print "Customer Information" company_name = raw_input("enter company name : ") company_symbol = raw_input("enter a company Symbol : ") share_price = raw_input("Enter the Price Of Share : ") total_share = raw_input("Enter the total Number Of Share : ") company_obj = Company(company_name, company_symbol, share_price, total_share) company_obj.set_company_name(company_name) company_obj.set_company_symbol(company_symbol) company_obj.set_share_price(share_price) company_obj.set_total_share(total_share) name = company_obj.get_company_name() company = ({ "company_name": company_obj.get_company_name(), "company_symbol": company_obj.get_company_symbol(), "share_Price": company_obj.get_share_price(), "total_share": company_obj.get_total_share() }) self.list_obj.push(company) self.save(company, name, 2) def display_company(self): print "\t\tName\tSymbol\tShare Price\t" for data in self.company_info: print "\t\t", self.company_info[data]["company_name"], "\t\t", self.company_info[data]['company_symbol'], "\t\t", \ self.company_info[data]['share_Price'] print "\n" def tansaction(self): print "enter 1.)Buy Share" print "enter 2.)Sell Share" choice = input("Enter your choice : ") if choice == 1: self.buy_shares() elif choice == 2: self.sell_share() def buy_shares(self): symbol = raw_input("Enter Company Symbol to Buy Shares : ") company = self.searchCompany(symbol) # print company if company != None: name = raw_input( "Enter Customer Name from whom Company wants to buy shares : ") customer = self.searchCustomer(name) print customer if customer != None: amount = raw_input("Enter amount to buy shares : ") noofShares = raw_input("Enter number of shares to buy : ") self.buy(amount, noofShares, customer, company, name) else: print "Customer Not Found" else: print "Company outer Not Found" def searchCompany(self, search): try: companylist = json.load(open('company.json', 'r')) name_keys = list(companylist.keys()) count = 0 # print name_keys for data in name_keys: if companylist[data]["company_symbol"] == search or companylist[ data]["company_name"] == search: count += 1 print "company found" companyName = companylist[data]["company_name"] # print companyName company_symbol = companylist[data]["company_symbol"] total_share = companylist[data]["total_share"] share_Price = companylist[data]["share_Price"] new_obj = { "company_name": companyName, "company_symbol": company_symbol, "total_share": total_share, "share_Price": share_Price } if count == 0: return None else: return new_obj except SyntaxError: print "error in name" def searchCustomer(self, name): try: customerlist = json.load(open('customer.json', 'r')) name_keys = list(customerlist["customers"].keys()) count = 0 for data in name_keys: # print data if data == name: count += 1 customername = customerlist["customers"][data]["cname"] no_of_share = customerlist["customers"][data]["noOfShare"] amount_per_share = customerlist["customers"][data][ "amount_per_share"] new_obj = { "cname": customername, "noOfShare": no_of_share, "amount_per_share": amount_per_share, } if count == 0: return None else: return new_obj except SyntaxError: print "error in name" def buy(self, amount, noofShares, customer, company, name): # print customer["noOfShare"] if amount >= company["share_Price"]: print "outer if" if noofShares <= customer["noOfShare"]: sharePrice = company["share_Price"] # 345 # print sharePrice shares = int(amount) / int(sharePrice) # print ("Shares : " ,shares) # print company["share_Price"] transaction = Transaction() new_customer_amount = int( customer["amount_per_share"]) - int(amount) new_no_of_share = int(customer["noOfShare"]) + int(noofShares) print "Customer.shares : ", customer["noOfShare"] new_company_share = int( company["total_share"]) - int(noofShares) # company["share_Price"] = int(company["share_Price"]) - int(amount) transaction.set_customer_name(customer["cname"]) transaction.set_company_symbol(company["company_symbol"]) transaction.set_buy_sell("Buy") transaction.set_total_share(shares) transaction.set_total_price(amount) now = datetime.datetime.now() today = now.strftime("%Y-%m-%d %H:%M") transaction.set_time(today) transact = ({ "customer_name": transaction.get_customer_name(), "company_symbol": transaction.get_company_symbol(), "buy_sell": transaction.get_buy_sell(), "total_share": transaction.get_total_share(), "total_Price": transaction.get_total_price(), "time": transaction.get_time() }) # self.linklist_obj.insertdata(transact) # self.save_transaction(transact,company,name,new_customer_amount,new_no_of_share,new_company_share) self.transaction_obj.append({ "customer_name": transaction.get_customer_name(), "company_symbol": transaction.get_company_symbol(), "buy_sell": transaction.get_buy_sell(), "total_share": transaction.get_total_share(), "total_Price": transaction.get_total_price(), "time": transaction.get_time() }) print self.transaction_obj with open('customer.json', 'r') as file: json_data = json.load(file) name_key = list(self.customer_info["customers"]) for item in name_key: if item == name: self.customer_info["customers"][item][ "amount_per_share"] = str(new_customer_amount) self.customer_info["customers"][item][ "noOfShare"] = str(new_no_of_share) print("Person Detail Added Successfully!") with open('customer.json', 'w') as data: json.dump(self.customer_info, data) name_keys = list(self.company_info.keys()) print self.company_info for item in name_keys: if item == company["company_name"]: # print company_info[item]["total_share"] self.company_info[item]["total_share"] = str( new_company_share) print("Person Detail Added Successfully!") with open('company.json', 'w') as data: json.dump(self.company_info, data) with open('transaction.json', 'w') as data: json.dump(self.transaction_obj, data) def sell(self, amount, noofShares, customer, company, name): print customer["noOfShare"] print noofShares if noofShares <= customer["noOfShare"]: print "if" if amount >= company["share_Price"]: sharePrice = customer["amount_per_share"] print "if1" shares = int(amount) / int(sharePrice) print "Shares : ", shares print company["share_Price"] transaction = Transaction() new_customer_amount = int( customer["amount_per_share"]) + int(amount) new_no_of_share = int(customer["noOfShare"]) - int(noofShares) print "Customer.shares : ", customer["noOfShare"] new_company_share = int( company["total_share"]) + int(noofShares) # company["share_Price"] = int(company["share_Price"]) - int(amount) transaction.set_customer_name(customer["cname"]) transaction.set_company_symbol(company["company_symbol"]) transaction.set_buy_sell("Sell") transaction.set_total_share(str(shares)) transaction.set_total_price(amount) now = datetime.datetime.now() today = now.strftime("%Y-%m-%d %H:%M") transaction.set_time(today) self.transaction_obj.append({ "customer_name": transaction.get_customer_name(), "company_symbol": transaction.get_company_symbol(), "buy_sell": transaction.get_buy_sell(), "total_share": transaction.get_total_share(), "total_Price": transaction.get_total_price(), "time": transaction.get_time() }) # print transaction_obj # with open('customer.json', 'r') as file: # json_data = json.load(file) name_key = list(self.customer_info["customers"]) for item in name_key: if item == name: self.customer_info["customers"][item][ "amount_per_share"] = str(new_customer_amount) self.customer_info["customers"][item][ "noOfShare"] = str(new_no_of_share) print("Person Detail Added Successfully!") with open('customer.json', 'w') as data: json.dump(self.customer_info, data) name_keys = list(self.company_info.keys()) for item in name_keys: if item == company["company_name"]: # print company_info[item]["total_share"] self.company_info[item]["total_share"] = str( new_company_share) print("Person Detail Added Successfully!") with open('company.json', 'w') as data: json.dump(self.company_info, data) with open('transaction.json', 'w') as data: json.dump(self.transaction_obj, data) def sell_share(self): customer_name = raw_input("Enter Customer Name : ") customer = self.searchCustomer(customer_name) if customer != None: company_name = raw_input("Enter Company name to buy share : ") company = self.searchCompany(company_name) if company != None: amount = raw_input("Enter amount to buy shares : ") noofShares = raw_input("Enter number of shares to buy : ") self.sell(amount, noofShares, customer, company, customer_name) else: print "Customer Not Found" else: print "Company Not Found" def display_transaction(self): for data in self.transaction_obj: print "customer_name : ", data["customer_name"] print "buy or sell : ", data["buy_sell"] print "total_share : ", data["total_share"] print "total_Price : ", data["total_Price"] print "time : ", data["time"], "\n"
def __init__(self): self.brackets = [] #储存结果的列表 self.LinkList = LinkList.LinkList() #匹配括号时所用到的链表 self.allLeft = ['[', '{', '(', '<'] self.allRight = [']', '}', ')', '>'] self.next = 0 #迭代器使用
lenA += 1 while tailB.next: tailB = tailB.next lenB += 1 if tailA is not tailB: return None if lenA < lenB: diff = lenB - lenA while diff > 0: headB = headB.next diff -= 1 elif lenB < lenA: diff = lenA - lenB while diff > 0: headA = headA.next diff -= 1 while headA: if headA == headB: return headA headA = headA.next headB = headB.next if __name__ == '__main__': la = LinkList([1, 3, 5, 6, 7, 8, 9, 10]) lb = LinkList([2, 4]) tb = lb.get_tail_node() tb.next = la.head.next.next.next lb.print_list() print get_intersection_node(la, lb)
def merge_two_lists_2(list_1, list_2): result = LinkList() result.head = merge_two_lists_helper(list_1.head, list_2.head) return result
# recursive def merge_two_lists_2(list_1, list_2): result = LinkList() result.head = merge_two_lists_helper(list_1.head, list_2.head) return result def merge_two_lists_helper(head_1, head_2): if not head_1: return head_2 if not head_2: return head_1 if head_1.data < head_2.data: head_1.next = merge_two_lists_helper(head_1.next, head_2) return head_1 else: head_2.next = merge_two_lists_helper(head_1, head_2.next) return head_2 if __name__ == '__main__': test_cases = [([1, 3, 5, 6], [2, 4]), ([1, 3, 5], []), ([1, 2, 3, 4], [5, 6, 7, 8]), ([2], [1])] for each_test_case in test_cases: listA_list, listB_list = each_test_case listA = LinkList(listA_list) listB = LinkList(listB_list) merge_two_lists_1(listA, listB).print_list() merge_two_lists_2(listA, listB).print_list()
n1.next = n2.next n2.next = temp.next def mergeTwoLists(l1,l2): if l1 == 0: return l2 if l2 == 0: return l1 if (l1!=0 and l2!=0) and l1.data > l2.data: swap(l1,l2) if l1!=0: l1.next = mergeTwoLists(l1.next,l2) return l1 L1 = LL.LinkList() H1 = L1.initlist([]) L2 = LL.LinkList( H2 = L2.initlist([]) L3 = LL.LinkList() H3 = L3.initlist([]) ls = [H1,H2,H3] Hnew = mergeKLists([]) while Hnew: print Hnew.data Hnew = Hnew.next
def __init__(self, echo): self.LinkList = LinkList.LinkList() #匹配对应符号时所用到的链表 self.echo = echo #所需匹配的一对符号 self.left_point = None #左侧在原文中的位置 self.right_point = None #右侧在原文中的位置 self.text = '' #一对符号之间的内容
from LinkList import * l1 = LinkList() l2 = LinkList() l1.init_list([1, 5, 7, 8, 10, 19]) l2.init_list([0, 3, 4, 9]) l1.show() l2.show() def merge(list_target01, list_target02): # 将list_target02合并到list_target01中 p = list_target01.head q = list_target02.head.next while p.next is not None: if p.next.value < q.value: p = p.next else: temp = p.next p.next = q p = p.next q = temp p.next = q merge(l1, l2) print("===============================") l1.show()
curr_node = None def list2bst(my_list): global curr_node curr_node = my_list.head.next root = list2bst_helper(0, len(my_list) - 1) return BinaryTree(root) def list2bst_helper(start, end): global curr_node if start > end: return None mid = start + (end - start) / 2 left_child = list2bst_helper(start, mid - 1) parent = TreeNode(curr_node.data) curr_node = curr_node.next parent.left = left_child parent.right = list2bst_helper(mid + 1, end) return parent if __name__ == '__main__': test_cases = [[1, 2, 3, 4, 5, 6]] for each_test_case in test_cases: my_list = LinkList(each_test_case) bst = list2bst(my_list) bst.pre_order_print(bst.root) print bst.in_order_print(bst.root)
from LinkList import * def reverse_linked_list(orig_list, m, n): assert (1 <= m <= n <= len(orig_list)) dummy = ListNode(0) dummy.next = orig_list.head p = dummy count = n - m while m - 1 > 0: p = p.next m -= 1 q = p.next while count > 0: r = q.next q.next = r.next r.next = p.next p.next = r count -= 1 orig_list.head = dummy.next return orig_list if __name__ == '__main__': test_cases = [([1, 2, 3, 4, 5, 6], 6, 6), ([1, 2, 3], 1, 3)] for each_test_case in test_cases: orig_list_data, m, n = each_test_case orig_linkedlist = LinkList(orig_list_data) print each_test_case reverse_linked_list(orig_linkedlist, m, n).print_list()
class StockAccountImplementation: list_obj = LinkedListStack() customerFile = "customer.json" companyFile = "company.json" transactionFile = "transaction.json" linklist_obj = LinkList() transaction_obj = Transaction() # /* # * Function to read json data from file # * @param filename # */ def read_json(self, filename): jsonDataObj = json.load(open(filename, "r")) return jsonDataObj # /* # * Function to save data into json formate in file # * @param data # * @param filename # */ def save(self, data, filename): with open(filename, 'w') as temp: json.dump(data, temp) print("Person Detail Added Successfully!") # /* # * Function to add customers # */ def add_customer(self): print "Customer Information" name = raw_input("enter customer name : ") amount = raw_input("enter a amount : ") no_Of_Share = raw_input("Enter the Number Of Share : ") customer_obj = Customer(name, amount, no_Of_Share) customer_obj.set_customer_name(name) customer_obj.set_amount(amount) customer_obj.set_noOfShare(no_Of_Share) customer = self.read_json(self.customerFile) customer["customers"].append({ "cname": customer_obj.get_customer_name(), "noOfShare": customer_obj.get_noOfShare(), "amount_per_share": customer_obj.get_amount() }) self.list_obj.push(customer) self.save(customer, self.customerFile) # /* # * Function to display customers # */ def display_customer(self): customer_data = self.read_json(self.customerFile) print "\t\tName\tNoOfShare\tAmount\t" for data in customer_data["customers"]: print "\n\t\t",data["cname"],"\t\t", data["noOfShare"],"\t\t",\ data["amount_per_share"] print "\n" # /* # * Function to display customers # */ def add_company(self): print "Customer Information" company_name = raw_input("enter company name : ") company_symbol = raw_input("enter a company Symbol : ") share_price = raw_input("Enter the Price Of Share : ") total_share = raw_input("Enter the total Number Of Share : ") company_obj = Company(company_name, company_symbol, share_price, total_share) company_obj.set_company_name(company_name) company_obj.set_company_symbol(company_symbol) company_obj.set_share_price(share_price) company_obj.set_total_share(total_share) company = self.read_json("company.json") company["company"].append({ "company_name": company_obj.get_company_name(), "company_symbol": company_obj.get_company_symbol(), "share_Price": company_obj.get_share_price(), "total_share": company_obj.get_total_share() }) self.list_obj.push(company) self.save(company, self.companyFile) # /* # * Function to display customers # */ def display_company(self): company_data = self.read_json(self.companyFile) print "\t\tName\tSymbol\tShare Price\t" for data in company_data["company"]: print "\n\t\t", data["company_name"],"\t\t", data['company_symbol'], "\t\t", \ data["share_Price"] print "\n" # /* # * Function to search a companies/customers data # * @param search_data # * @param file # * @param temp # * @return # */ def search(self, search_data, file, temp): try: file_data = self.read_json(file) count = 0 if temp == 'company': for data in file_data[temp]: if (data["company_symbol"] == search_data or data["company_name"] == search_data): count += 1 print "company data found" companyName = data["company_name"] company_symbol = data["company_symbol"] total_share = data["total_share"] share_Price = data["share_Price"] new_obj = { "company_name": companyName, "company_symbol": company_symbol, "total_share": total_share, "share_Price": share_Price } else: for data in file_data[temp]: if (data["cname"] == search_data): count += 1 print "customers data found" customername = data["cname"] no_of_share = data["noOfShare"] amount_per_share = data["amount_per_share"] new_obj = { "cname": customername, "noOfShare": no_of_share, "amount_per_share": amount_per_share } if count == 0: return None else: return new_obj except SyntaxError: print "error in name" # /* # * Function to do transaction # */ def tansaction(self): print "enter 1.)Buy Share" print "enter 2.)Sell Share" choice = input("Enter your choice : ") if choice == 1: self.buy_shares() elif choice == 2: self.sell_share() # /* # * Function to buy shares # */ def buy_shares(self): symbol = raw_input("Enter Company Symbol to Buy Shares : ") company = self.search(symbol, self.companyFile, "company") if company != None: name = raw_input( "Enter Customer Name from whom Company wants to buy shares : ") customer = self.search(name, self.customerFile, "customers") print customer if customer != None: amount = raw_input("Enter amount to buy shares : ") if customer["amount_per_share"] > 0: print customer["amount_per_share"] noofShares = raw_input("Enter number of shares to buy : ") if company["total_share"] < 0: self.buy(amount, noofShares, customer, company, name) else: print "company shares no left" exit(0) else: print "customer has no money" exit(0) else: print "Customer Not Found" else: print "Company outer Not Found" # /* # * Function to buy stocks # * @param amount # * @param noofShares # * @param customer # * @param company # * @param name # */ def buy(self, amount, noofShares, customer, company, name): print company if amount >= company["share_Price"]: if noofShares <= customer["noOfShare"]: sharePrice = company["share_Price"] shares = int(amount) / int(sharePrice) new_customer_amount = int( customer["amount_per_share"]) - int(amount) new_no_of_share = int(customer["noOfShare"]) + int(noofShares) print "Customer.shares : ", customer["noOfShare"] new_company_share = int( company["total_share"]) - int(noofShares) self.transaction_obj.set_customer_name(customer["cname"]) self.transaction_obj.set_company_symbol( company["company_symbol"]) self.transaction_obj.set_buy_sell("Buy") self.transaction_obj.set_total_share(str(shares)) self.transaction_obj.set_total_price(amount) now = datetime.datetime.now() today = now.strftime("%Y-%m-%d %H:%M") self.transaction_obj.set_time(today) transaction = self.read_json(self.transactionFile) transaction["transaction"].append({ "customer_name": self.transaction_obj.get_customer_name(), "company_symbol": self.transaction_obj.get_company_symbol(), "buy_sell": self.transaction_obj.get_buy_sell(), "total_share": self.transaction_obj.get_total_share(), "total_Price": self.transaction_obj.get_total_price(), "time": self.transaction_obj.get_time() }) self.save(transaction, self.transactionFile) self.linklist_obj.insertdata(transaction) customer_data = self.read_json(self.customerFile) for item in customer_data["customers"]: if item["cname"] == name: print "if" print item["amount_per_share"] item["amount_per_share"] = str(new_customer_amount) item["noOfShare"] = str(new_no_of_share) self.save(customer_data, self.customerFile) company_data = self.read_json(self.companyFile) for item in company_data["company"]: if item["company_name"] == company["company_name"]: item["total_share"] = str(new_company_share) self.save(company_data, self.companyFile) # /* # * Function to sell stocks # * @param amount # * @param noofShares # * @param customer # * @param company # * @param name # */ def sell(self, amount, noofShares, customer, company, name): print customer["noOfShare"] print noofShares if noofShares <= customer["noOfShare"]: print "if" if amount <= company["share_Price"]: sharePrice = customer["amount_per_share"] print "if1" shares = int(amount) / int(sharePrice) print "Shares : ", shares print company["share_Price"] new_customer_amount = int( customer["amount_per_share"]) + int(amount) new_no_of_share = int(customer["noOfShare"]) - int(noofShares) print "Customer.shares : ", customer["noOfShare"] new_company_share = int( company["total_share"]) + int(noofShares) self.transaction_obj.set_customer_name(customer["cname"]) self.transaction_obj.set_company_symbol( company["company_symbol"]) self.transaction_obj.set_buy_sell("Sell") self.transaction_obj.set_total_share(str(shares)) self.transaction_obj.set_total_price(amount) now = datetime.datetime.now() today = now.strftime("%Y-%m-%d %H:%M") self.transaction_obj.set_time(today) transaction = self.read_json(self.transactionFile) transaction["transaction"].append({ "customer_name": self.transaction_obj.get_customer_name(), "company_symbol": self.transaction_obj.get_company_symbol(), "buy_sell": self.transaction_obj.get_buy_sell(), "total_share": self.transaction_obj.get_total_share(), "total_Price": self.transaction_obj.get_total_price(), "time": self.transaction_obj.get_time() }) self.save(transaction, self.transactionFile) customer_data = self.read_json(self.customerFile) for item in customer_data["customers"]: if item["cname"] == name: item["amount_per_share"] = str(new_customer_amount) item["noOfShare"] = str(new_no_of_share) self.save(customer_data, self.customerFile) print("Person Detail Added Successfully!") company_data = self.read_json(self.companyFile) for item in company_data["company"]: if item["company_name"] == company["company_name"]: item["total_share"] = str(new_company_share) self.save(company_data, self.companyFile) print("Person Detail Added Successfully!") # /* # * Function to sell stock # */ def sell_share(self): customer_name = raw_input("Enter Customer Name : ") customer = self.search(customer_name, self.customerFile, "customers") if customer != None: company_name = raw_input("Enter Company name to buy share : ") company = self.search(company_name, self.companyFile, "company") if company != None: amount = raw_input("Enter amount to buy shares : ") noofShares = raw_input("Enter number of shares to buy : ") self.sell(amount, noofShares, customer, company, customer_name) else: print "Customer Not Found" else: print "Company Not Found" # /* # * Function to display all transaction # */ def display_transaction(self): transaction_display = self.read_json(self.transactionFile) for data in transaction_display["transaction"]: print "customer_name : ", data["customer_name"] print "buy or sell : ", data["buy_sell"] print "total_share : ", data["total_share"] print "total_Price : ", data["total_Price"] print "time : ", data["time"], "\n"
''' merge len(lists) sorted linked lists, and return the result linked list ''' for each_list in lists: each_list.append_node(ListNode(sys.maxint)) min_heap = Heap() result_list = LinkList() curr_nodes = [each_list.head for each_list in lists] curr_datas = [node.data for node in curr_nodes] # build the heap according to curr_datas min_heap.build_heap('min', curr_datas) # min_heap.heap[0] == maxint means all the lists go to end, only then, stop the while loop while min_heap.heap[0] != sys.maxint: # extract min node curr_min = min_heap.extract_node() # append to result result_list.append_node(ListNode(curr_min)) min_index = curr_datas.index(curr_min) curr_nodes[min_index] = curr_nodes[min_index].next curr_datas[min_index] = curr_nodes[min_index].data # insert the extracted node's next's data, and re-heapify min_heap.add_node(curr_datas[min_index]) return result_list if __name__=='__main__': lists=[[2,5,8], [1,4,10], [3,6,7]] linklists=[] for each_list in lists: linklists.append(LinkList(each_list)) for each_list in linklists: each_list.print_list() merge_lists(linklists).print_list()
def merge_sort_list(orig_list): nh = merge_sort_list_helper(orig_list.head) result_list = LinkList() result_list.head = nh return result_list
#Solution:变量tmp用于储存当前data的node,如果下一个节点的 #data和cur.data相同,那么tmp内容不变,继续遍历链表; #若cur.data != cur.next.data,说明内容发生了变换, #则要用tmp.next连接cur.next,并用cur.next更新tmp; #最后一个tmp注意和后面的节点断开,即加上tmp.next = 0 def deleteDuplicates(head): #newhead = head if head == 0 or head.next == 0: return head cur = head tmp = head while cur.next: if cur.data != cur.next.data: tmp.next = cur.next tmp = cur.next cur = cur.next tmp.next = 0 return head l = LL.LinkList() h = l.initlist([1, 1]) h_remove = deleteDuplicates(h) while h_remove: print h_remove.data h_remove = h_remove.next
p = p.next # case 1: insert between previous and current if prev.data <= val <= p.data: break # case 2: insert at end or beginning if prev.data > p.data and (val > prev.data or val < p.data): break # case 3: when duplicates in list, traverse back to start point if p == node: break new_node = ListNode(val) prev.next = new_node new_node.next = p #return orig_list if __name__ == '__main__': orig_list = LinkList([1, 3, 3, 4]) p = q = orig_list.head orig_list.make_loop(0) node = q.next.next # node = second 3 print orig_list.loop_length() for val in [2, 3, 5]: insert_node_cyclic(orig_list, node, val) p = q = orig_list.head print p.data, p = p.next while p != q: print p.data, p = p.next print
def add_two_lists(list1, list2): sum_list = LinkList() p = list1.head q = list2.head carry = 0 while p or q: first = p.data if p else 0 second = q.data if q else 0 sum = first + second + carry carry = sum / 10 sum = sum % 10 sum_list.append_node(ListNode(sum)) if p: p = p.next if q: q = q.next if carry: sum_list.append_node(ListNode(carry)) return sum_list if __name__ == '__main__': test_cases = [([7, 1, 6], [1, 5, 9, 2]), ([1], [9, 9, 9]), ([1, 2, 3], [4, 5, 6]), ([8, 5, 6], [3, 7, 5])] for each_test_case in test_cases: list1 = LinkList(each_test_case[0]) list2 = LinkList(each_test_case[1]) print each_test_case add_lists_reverse(list1, list2).print_list() add_two_lists(list1, list2).print_list()
for j in range(len(A)): if A[j] != elem: A[i] = A[j] i += 1 return A[:i] if __name__ == '__main__': test_cases = [[1, 1, 2], [1, 1, 2, 3, 3, 3, 4, 4], [1, 2, 3], [1]] for each_test_case in test_cases: print 'remove dup in array, Q1', each_test_case, remove_dup_in_array_q1( each_test_case) test_cases = [[1, 1, 2], [1, 1, 2, 3, 3, 3, 4, 4], [1, 2, 3], [1], [1, 2, 2, 2, 3, 3, 4, 4, 4], [1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6]] for each_test_case in test_cases: print 'remove dup in array Q2', each_test_case, remove_dup_in_array_q2( each_test_case) test_cases = [[1, 2, 2, 2, 3, 3], [1], [1, 1, 1, 1], [1, 2, 2, 2, 3, 3, 4]] for each_test_case in test_cases: print 'remove dup in list Q1', each_test_case remove_dup_in_list_q1(LinkList(each_test_case)).print_list() test_cases = [[1, 1], [1, 1, 1, 2, 3], [1], [1, 2, 2, 2, 3, 3, 3]] for each_test_case in test_cases: print 'remove dup in list Q2', each_test_case remove_dup_in_list_q2(LinkList(each_test_case)).print_list() for each_test_case in test_cases: print 'remove element in array', each_test_case, remove_elem( each_test_case, 1)
from LinkList import * import time l = [i for i in range(999999)] link = LinkList() link.init_list(l) tm = time.time() # for i in L: # print(i) # 列表 # link.show() # 链表 # l.append(8866) # link.append(8866) # 尾插入 # l.insert(0,8866) # link.head_insert(8866) # 头插入 # link.insert(100,9999) # link.delete(1) # 删除 l.remove(1) # link.show() # print(link.get_index(7)) print("time:", time.time() - tm)