python静态查找类的设计与实现

题目

建立一维数组数据结构类, 对数组元素进行静态查找
主要完成如下功能:

  1. 实现数组数据的输入与输出
  2. 对数组进行顺序查找
  3. 对有序数组进行折半查找(递归)
  4. 对有序数组进行折半查找(非递归)
  5. 在图形类上编写一个测试该类的程序

部分代码如下

from tkinter import *


class Array(object):
    """数组"""

    def __init__(self):
        self.items = []

    def del_array(self):
        """清空数组"""
        self.items = []

    def en_array(self, item):
        """数组输入"""
        self.items = [int(n) for n in item.split()]

    def out_array(self):
        """数组输出"""
        return self.items

    def search_array(self, item):
        """数组顺序查找"""
        for i in range(len(self.items)):
            if self.items[i] == item:
                return i
        return -1

    def search_half(self, item):
        """折半查找非递归"""
        self.items.sort()  # 排序,保证列表是有序的
        low = 0
        height = len(self.items) - 1
        while low <= height:
            k = (low + height) // 2
            if self.items[k] < item:
                low = k + 1
            elif self.items[k] > item:
                height = k - 1
            else:
                return k  # 找到后返回位置
        return -1

    def search_half_d(self, item, low, high):
        """折半查找递归"""

        mid = (low + high) // 2
        if item == self.items[mid]:
            return mid + 1
        elif low > high:
            return -1

        elif item > self.items[mid]:
            return Array.search_half_d(self, item, low + 1, high)
        else:
            return Array.search_half_d(self, item, low, high - 1)


def windows():
    def en_array():
        a = inp1.get()
        if a:
            array.en_array(a)
            txt.insert(END, " 成功保存数组 " + a)
        else:
            txt.insert(END, " 未输入内容 ")
        inp1.delete(0, END)  # 清空输入

    def out_array():
        b = array.out_array()
        if b != -1:
            txt.insert(END, " 内容如下 " + str(b))
        else:
            txt.insert(END, " 数组无内容 ")

    def search():
        a = inp1.get()
        b = array.search_array(int(a))
        if b != -1:
            txt.insert(END, " 成功查找 位置为: " + str(b + 1))
        else:
            txt.insert(END, " 未能在数组找到" + a)
        inp1.delete(0, END)  # 清空输入

    def search2():
        a = inp1.get()
        b = array.search_half(int(a))
        if b != -1:
            txt.insert(END, " 成功查找 位置为: " + str(b + 1))
        else:
            txt.insert(END, " 未能在数组找到" + a)
        inp1.delete(0, END)  # 清空输入

    def search3():
        a = inp1.get()
        b = array.search_half_d(int(a), 0, len(array.out_array())-1)
        if b != -1:
            txt.insert(END, " 成功查找 位置为: " + str(b))
        else:
            txt.insert(END, " 未能在数组找到" + a)
        inp1.delete(0, END)  # 清空输入

测试截图如下

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值