人菜还要学算法
2021/7/8 1:35:46
本文主要是介绍人菜还要学算法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
二分法
#!/usr/bin/python # -*- coding: utf-8 -*- from functools import wraps from random import randrange class Dichotomy: def __init__(self, arr, target, not_then_return): self.arr = arr self.target = target self.not_then_return = not_then_return def __dichotomy(self): left, right = 0, len(self.arr) - 1 ret = None while left <= right: m = (left + right) // 2 if self.comp(self.arr[m], self.target): ret = m right = m - 1 else: left = m + 1 return ret def wrap_solve(self, func): @wraps(func) def wrapper(*args, **kwargs): _id = self.__dichotomy() return func(_id, self.arr, self.not_then_return, *args, **kwargs) if _id \ else self.not_then_return return wrapper def __call__(self, func_comp, func_solve, *args, **kwargs): self.comp = func_comp return self.wrap_solve(func_solve)(*args, **kwargs) if __name__ == '__main__': arr = sorted([randrange(50) for i in range(20)]) target = 233 not_then_return = float('-inf') print(Dichotomy(arr=arr, target=target, not_then_return=not_then_return)( func_comp=lambda i, _target: i**2 > _target, func_solve=lambda i, _arr, n_t_r: (i, _arr[i]) if i != n_t_r else n_t_r))
つづく
这篇关于人菜还要学算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-26JavaScript入门教程:从零开始学习JavaScript编程
- 2024-12-26JavaScript入门教程:从零开始学习JavaScript
- 2024-12-26JS编程入门指南:从零开始学习JavaScript
- 2024-12-25Java编程面试题详解与解答
- 2024-12-25TS基础知识详解:初学者必看教程
- 2024-12-252024面试题解析与攻略:从零开始的面试准备指南
- 2024-12-25数据结构与算法学习:新手入门教程
- 2024-12-25初学者必备:订单系统资料详解与实操教程
- 2024-12-24内网穿透资料入门教程
- 2024-12-24微服务资料入门指南