1.编写程序:新建一个 LeapYear 类,分析后实现判断闰年。
(1)代码:
class LeapYear():
def __init__(self, year):
self.year = year
def if_leapyear(self):
if self.year % 4 == 0 and self.year % 100 != 0 or self.year % 400 == 0:
return 1
else:
return 0
year=2024
leapyear = LeapYear(year)
if leapyear.if_leapyear():
print(f"{year}是闰年")
else:
print(f"{year}不是闰年")
(2)结果:
![](https://i-blog.csdnimg.cn/blog_migrate/19b391c640cfd9c0b719d7e3c580de24.png)
2.编写程序:新建一个 BinarySearch 类,实现整数列表的二分法查找。
(1)代码:
import random
class BinarySearch():
def __init__(self, list1):
self.list1 = list1
def sele_BinarySearch(self,n):
if not self.list1:
return "未找到!"
i = 0
j = 10 - 1
while i <= j:
mid = (i + j) // 2
if self.list1[mid] == n:
return mid
else:
if n < self.list1[mid]:
j = mid - 1
else:
i = mid + 1
if i > j:
return "未找到!"
if __name__ == '__main__':
list1 = random.sample(range(0, 20), 10)
list1.sort()
print(list1)
n = int(input("请输入查找元素值:"))
s1 = BinarySearch(list1)
print(s1.sele_BinarySearch(n))
(2)结果:
![](https://i-blog.csdnimg.cn/blog_migrate/4c1959dbba39016b9459526e4c35253a.png)