python英文题17-18

基于同一类:

03.Define a function called create_a_tree() which builds and returns the following binary tree:

def create_a_tree():
    tree = BinaryTree(9)
    tree.insert_left(3)
    tree.insert_right(6)
    tree.get_left().insert_right(7)
    tree.get_right().insert_right(2)
    return tree

04.Define a function named get_height(b_tree) which calculates the height in the binary tree recursively. For example, the following code fragment:

def get_height(b_tree):
    if b_tree == None:
        return -1
    else:
        return 1 + max(get_height(b_tree.get_left()), get_height(b_tree.get_right()))

05.Define a function called count_nodes(b_tree) which takes a binary tree as a parameter, and returns the number of nodes in the binary tree. How could we calculate the total number of nodes in the tree? Well, if we knew the number of nodes in the left sub-tree, and the number of nodes in the right sub-tree, then we would just need to add 1 to these values to find the number of nodes in the overall tree.  The following diagram illustrates this:

def count_nodes(b_tree):
    if b_tree==None:
        return 0
    else:
        return 1+count_nodes(b_tree.get_left())+count_nodes(b_tree.get_right())

06.Define a function named search(tree, item) which takes a binary tree as a parameter. The function searches all nodes of a binary tree for the parameter item and return True when found, and False otherwise. 

def search(tree, item):
    def ap(tree,l1=[]):
        l1.append(tree.get_data())
        if tree.get_left()!=None:
            ap(tree.get_left())
        if tree.get_right()!=None:
            ap(tree.get_right())
        return l1
    return item in ap(tree)

07.Define a function named get_max(b_tree, is_integer) which takes a binary tree and a boolean value as parameters. The function finds the maximum value of all elements in the binary tree recursively. If the boolean is True, the function returns the maximum integer in the binary tree. If the boolean value is False, the function returns "maximum" word in alphabetical order.

def get_max(b_tree, is_integer):
    def ap(tree,l1=[]):
        l1.append(tree.get_data())
        if tree.get_left()!=None:
            ap(tree.get_left())
        if tree.get_right()!=None:
            ap(tree.get_right())
        return l1
    return max(ap(b_tree))

08.Define a function named is_full(my_tree) which takes a binary tree as a parameter and returns True if the given tree is full, and False otherwise. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node.

def is_full(my_tree):
    result=[my_tree]
    while result:
        tmp=result.pop(0)
        if tmp.get_left():
            result.append(tmp.get_left())
        if tmp.get_right():
            result.append(tmp.get_right())
        if tmp.get_left()==None and tmp.get_right()!=None:
            return False
        if tmp.get_left()!=None and tmp.get_right()==None:
            return False
    return True  

09.Write a function called create_tree_from_nested_list(a_list) which takes a list of values in the nested list format and returns the corresponding BinaryTree object.

def create_tree_from_nested_list(a_list):
    if a_list[1] == None:
        left = None
    else:
        left = create_tree_from_nested_list(a_list[1])
    if a_list[2] == None:
        right = None
    else:
        right = create_tree_from_nested_list(a_list[2])
    return BinaryTree(a_list[0],left,right)

10.Write a function called convert_tree_to_list(b_tree) that takes a binary tree as a parameter, and returns the nested list format of the tree.

def convert_tree_to_list(b_tree):
    if b_tree == None:
        return None
    else:
        result = []
        result.append(b_tree.get_data())
        result.append(convert_tree_to_list(b_tree.get_left()))
        result.append(convert_tree_to_list(b_tree.get_right()))
    return result

01.Write a function evaluate_f(n) that takes an integer value n as a parameter, and evaluates the following mathematical function for that value of n.

def evaluate_f(n):
    if n==0:
        return 3
    elif n==1:
        return 2
    else:
        return 2*(evaluate_f(n-1)) + 3*(evaluate_f(n-2))

02.Write a function count_evens(my_list) that takes as a parameter a list. Elements within the list will be either numbers, or other lists (which can contain numbers or other lists, etc).Your function should return the total number of even numbers in the list and all of its sub-lists.

def count_evens(n):
    c=0
    for i in n:
        if type(i) == int :
            if i%2==0:
                c+=1
        else:
            c+=count_evens(i)
    return c

03.Write a function longest_valid_brackets(my_string) that takes a string as a parameter. This string will contain a mix of brackets and letters. The brackets will all be standard brackets: "(", ")"

def longest_valid_brackets(n):
    s=Stack()
    if n.find("(")>n.rfind(")"):
        return -1
    else:
        c=0
        k=n.find("(")
        for i in range(len(n)):
            if n[i]=="(":
                s.push("n[i]")
            if n[i]==")":
                if s.is_empty():
                    break
                else:
                    m=i
                    s.pop()
                if s.is_empty():
                    if m-k-1>c:
                        c=m-k-1
                    k=n[i+1:].find("(")+i+1
                    if k==-1:
                        break
                else:
                    x=n[:i].rfind("(")
                    if m-x-1>c:
                        c=m-x-1
    return c

04.Define a class called Car which stores information about a car's make, model, year of manufacture, and sale price. The class must have the following functionality:

class Car:
    def __init__(self,make, model, year,price=10000):
        self.__make=make
        self.__model=model
        self.__year=year
        self.__price=price
    def __str__(self):
        return f"{self.__year} {self.__make} {self.__model}, ${self.__price}"
    def get_make(self):
        return self.__make
    def get_model(self):
        return self.__model
    def get_year(self):
        return self.__year
    def get_price(self):
        return self.__price
    def set_price(self,n):
        if n>=0:
            self.__price=n

05.A Dealership class represents a company that sells cars, where the details of each car that it has in stock are stored using instances of the Car class.

class Dealership:
    def __init__(self,name):
        self.__name=name
        self.__stock=[]
    def get_name(self):
        return self.__name
    def add_car(self,c):
        if type(c)!=Car:
            raise ValueError("This dealership only sells cars!")
        else:
            self.__stock.append(c)
    def total_value_of_stock(self):
        t=sum([i.get_price() for i in self.__stock])
        return t

06.This question makes use of the Node and LinkedList ADTs.

Write a function get_list_of_ascending_elements(my_linked_list) that takes a LinkedList as a parameter. This LinkedList will contain numbers in its nodes.

Your function should return a normal python list containing all the elements of the list that are larger than all of the elements that are earlier in the list.

def get_list_of_ascending_elements(my_linked_list):
    list1=[]
    count=0
    node=my_linked_list.get_head()
    if node!=None:
        while True:
            if node.get_data()>count:
                list1.append(node.get_data())
                count=node.get_data()
                node=node.get_next()
            else:
                node=node.get_next()
            if node.get_next()==None:
                if node.get_data()>count:
                    list1.append(node.get_data())
                return list1
    else:
        return list1

07.This question makes use of the Node and LinkedList ADTs.

Write a function duplicate_list(my_linked_list) that takes a LinkedList as a parameter. Your function should modify this LinkedList such that every element within the list is duplicated. Duplicates should be placed immediately after the original.

def duplicate_list(my_linked_list):
    if my_linked_list.is_empty():
        return None
    n=my_linked_list.get_head()
    while n.get_next()!=None:
        s=n.get_data()
        m=n.get_next()
        n.set_next(Node(s,m))
        n=m
    s=n.get_data()
    n.set_next(Node(s))

08.

class SimpleHashTable:

Modify the class definition, so that the put() method returns a boolean value. This value should return True if using double hashing would result in fewer collisions to insert the key into the table than linear probing. The actual insertion should still use linear probing.

The formula to be used for double hashing is: 5 - (key % 5)

You should assume that all values inserted into the table will be unique.

class SimpleHashTable:
    def __init__(self, size=7):
        self.__size = size
        self.__slots = [None] * size
    def __str__(self):
        return str(self.__slots)
    def get_hash_code(self, key):
        return key % self.__size
    def put(self, key):
        s=self.__slots.copy()
        index = self.get_hash_code(key)
        if self.__slots[index] == None: #empty
            self.__slots[index] = key
            return False
        else:     
            new_index = self.get_new_hash_code_linear_probing(index)
            c1=1
            while self.__slots[new_index] != None: #look for an empty slot
                new_index = self.get_new_hash_code_linear_probing(new_index)
                c1+=1
            self.__slots[new_index]=key
        index = self.get_hash_code(key)
        c=5-(key%5)
        index=(index+c)%self.__size
        for i in range(c1-1):
            if s[index] != None:
                index=(index+c)%self.__size
            else:
                return True
        return False
    def get_new_hash_code_linear_probing(self, index):
        return ( index + 1 ) % self.__size

09.This question makes use of the BinaryTree ADT. The code for the BinaryTree class is provided and you do not need to include it in your answer.

Write a function shrinks(tree) that takes a BinaryTree as a parameter. All nodes in the tree will store an integer value. This function should return True if every node in the tree stores a value that is larger than the values stored by any of its child nodes.

def shrinks(tree):
    if tree.get_left()!=None and tree.get_right()!=None:
        if tree.get_data()<tree.get_left().get_data() or tree.get_data()<tree.get_right().get_data():
            return False
        return shrinks(tree.get_left()) and shrinks(tree.get_right())
    elif tree.get_right()==None and tree.get_left()==None:
        return True
    elif tree.get_right()==None:
        if tree.get_data()<tree.get_left().get_data():
            return False
        return shrinks(tree.get_left())
    else:
        if tree.get_data()<tree.get_right().get_data():
            return False
        return shrinks(tree.get_right())

10.

This question makes use of the BinaryTree ADT. The code for the BinaryTree class is provided and you do not need to include it in your answer.

Write a function is_subtree(tree1, tree2) that takes two binary trees as parameters.  This function should return True if tree2 is a subtree of tree1. That is, if there is a group of nodes within tree1 that have the same layout and store the same data as the entire tree2.

def same(t,s):
    if not t and not s:
        return True
    if (not t and s) or (not s and t):
        return False
    if t.get_data() != s.get_data():
        return False
    if not same(t.get_left(),s.get_left()):
        return False
    if not same(t.get_right(),s.get_right()):
        return False
    return True

def is_subtree(tree1, tree2):
    k=False
    h=False
    if same(tree1,tree2):
        return True
    elif tree1.get_left()!=None:
        h=is_subtree(tree1.get_left(), tree2)
    if not h and tree1.get_right()!=None:
        k=is_subtree(tree1.get_right(), tree2)
    return h or k

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值