美文网首页
2021-04-18python 二叉搜索

2021-04-18python 二叉搜索

作者: 喵呜e喵星人 | 来源:发表于2021-04-18 22:57 被阅读0次

    二叉搜索:
    第一步,先取中间位置值进行比较;
    第二步,在大于或者小于的一部分进行比较;
    重复第一、二步。

    
    def binarySearch(target,sortedLyst):
        left = 0
        right = len(sortedLyst) -1
        while  left<= right:
            print(left,right)
            midpoint = (left+right)//2
            print(midpoint,target)
            if target == sortedLyst[midpoint]:
                return midpoint
            elif target < sortedLyst[midpoint]:
                right = midpoint -1
            else:
                left = midpoint +1
        return -1
    
    lys = [20,44,48,55,62,66,74,88,93,99]
    binarySearch(90,lys)
    binarySearch(44,lys)
    

    结果:

    0 9
    4 90
    5 9
    7 90
    8 9
    8 90
    0 9
    4 44
    0 3
    1 44
    

    python 内建类对象比较。eq ==; it 小于; gt 大于。

    class SavingAccount(object):
    
        def __init__(self,name,pin,balance=0.0,num=0.0):
            self._name = name
            self._pin = pin
            self._balance = balance
            self._num = num
    
        def __eq__(self, other):
            return self._num==other._num
    
        def __lt__(self, other):
            print(other._name,other._balance,other._num)
            print(self._name,self._balance,self._num)
            return self._num < other._num
    
        def __gt__(self, other):
            print(other._name, other._balance, other._num)
            print(self._name, self._balance, self._num)
            return self._num > other._num
    
        def __str__(self):
            return str(self._name + self._pin+ str(self._balance)+str(self._num))
    
    
    

    相关文章

      网友评论

          本文标题:2021-04-18python 二叉搜索

          本文链接:https://www.haomeiwen.com/subject/curblltx.html