Python 找出出現(xiàn)次數(shù)超過數(shù)組長度一半的元素實例
利用問題的普遍性和特殊性來求解,
代碼如下:
import unittest from datetime import datetime class GetFreqNumbersFromList(unittest.TestCase): def setUp(self): print("\n") self.start_time = datetime.now() print(f"{self._testMethodName} start: {self.start_time}") def tearDown(self): self.end_time = datetime.now() print(f"{self._testMethodName} end: {self.end_time}") exec_time = (self.end_time - self.start_time).microseconds print(f"{self._testMethodName} exec_time: {exec_time}") def normal_solution(self, _list, _debug=False): """ 普遍性解法 利用字典記錄每個元素出現(xiàn)的次數(shù)——然后找出元素出現(xiàn)次數(shù)超過數(shù)組長度一半的元素 普遍性解法針對任何次數(shù)的統(tǒng)計均適用而不光只是針對出現(xiàn)次數(shù)超過數(shù)組長度一半的情況 """ _target = len(_list) // 2 _dict = {} for _member in _list: if _member not in _dict: _dict.setdefault(_member, 1) else: _dict[_member] += 1 _ret = [_member for _member in _dict if _dict[_member] > _target] if _debug: print(_ret) return _ret def specific_solution(self, _list, _debug=False): """ 特殊性解法 假設有兩個元素出現(xiàn)的次數(shù)都超過數(shù)組長度一半就會得出兩個元素出現(xiàn)的次數(shù)超出了數(shù)組長度的矛盾結果——所以超過數(shù)組長度一半的元素是唯一的 排序后在數(shù)組中間的一定是目標解 特殊性解法只能針對元素出現(xiàn)次數(shù)超過數(shù)組長度一半的情況 """ _list.sort() if _debug: print(_list[len(_list) // 2]) return _list[len(_list) // 2] def test_normal_solution(self): actual_result = self.normal_solution([2,2,2,2,2,2,1,1,1,1,1], False) self.assertEqual(actual_result[0], 2) def test_specific_solution(self): actual_result = self.specific_solution([2,2,2,2,2,2,1,1,1,1,1], False) self.assertEqual(actual_result, 2) if __name__ == "__main__": # 找出出現(xiàn)次數(shù)超過數(shù)組長度一半的元素 suite = unittest.TestSuite() suite.addTest(GetFreqNumbersFromList('test_normal_solution')) suite.addTest(GetFreqNumbersFromList('test_specific_solution')) runner = unittest.TextTestRunner() runner.run(suite)
測試結果:
補充知識:Python 用積分思想計算圓周率
早上起來突然想求圓周率,1單位時圓的面積。
代碼如下:
from math import pow, sqrt def calc_circle_s_with(r, dy, x_slices): x_from_start_to_cc = sqrt(1 - pow(dy, 2)) dx = x_from_start_to_cc / x_slices x_to_edge = 1 - x_from_start_to_cc quarter_circle_s = 0 while x_to_edge < 1: rect_s = dy * dx quarter_circle_s += rect_s x_to_edge = x_to_edge + dx dy = sqrt(1 - pow((1 - x_to_edge), 2)) circle_s = 4 * quarter_circle_s print(circle_s) calc_circle_s_with(1, 0.0001, 10000000)
運行結果接近3.1415926,dy傳的越小,x_slices傳的越大,就越接近。
半徑為:1
初始小矩形到圓周的距離:1 - x_from_start_to_cc
其中dy代表四分之一圓中初始小矩形的高度,x_slices代表小矩形的寬度:(1 - x_from_start_to_cc) / x_slices
四分之一圓的面積積分為:quarter_circle_s
以上這篇Python 找出出現(xiàn)次數(shù)超過數(shù)組長度一半的元素實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python 生成一個從0到n個數(shù)字的列表4種方法小結
今天小編就為大家分享一篇Python 生成一個從0到n個數(shù)字的列表4種方法小結,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11Python的代理類實現(xiàn),控制訪問和修改屬性的權限你都了解嗎
這篇文章主要為大家詳細介紹了Python的代理類實現(xiàn),控制訪問和修改屬性的權限,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03使用Streamlit和Pandas實現(xiàn)帶有可點擊鏈接的數(shù)據(jù)表格
這篇文章主要為大家詳細介紹了如何利用?Streamlit?和?Pandas?在?Python?中創(chuàng)建一個帶有可點擊鏈接的數(shù)據(jù)表格,感興趣的小伙伴可以跟隨小編一起學習一下2023-11-11