這篇文章主要講解了Python怎么找出出現(xiàn)次數(shù)超過數(shù)組長(zhǎng)度一半的元素,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
利用問題的普遍性和特殊性來(lái)求解,
代碼如下:
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): """ 普遍性解法 利用字典記錄每個(gè)元素出現(xiàn)的次數(shù)——然后找出元素出現(xiàn)次數(shù)超過數(shù)組長(zhǎng)度一半的元素 普遍性解法針對(duì)任何次數(shù)的統(tǒng)計(jì)均適用而不光只是針對(duì)出現(xiàn)次數(shù)超過數(shù)組長(zhǎng)度一半的情況 """ _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): """ 特殊性解法 假設(shè)有兩個(gè)元素出現(xiàn)的次數(shù)都超過數(shù)組長(zhǎng)度一半就會(huì)得出兩個(gè)元素出現(xiàn)的次數(shù)超出了數(shù)組長(zhǎng)度的矛盾結(jié)果——所以超過數(shù)組長(zhǎng)度一半的元素是唯一的 排序后在數(shù)組中間的一定是目標(biāo)解 特殊性解法只能針對(duì)元素出現(xiàn)次數(shù)超過數(shù)組長(zhǎng)度一半的情況 """ _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ù)組長(zhǎng)度一半的元素 suite = unittest.TestSuite() suite.addTest(GetFreqNumbersFromList('test_normal_solution')) suite.addTest(GetFreqNumbersFromList('test_specific_solution')) runner = unittest.TextTestRunner() runner.run(suite)
標(biāo)題名稱:Python怎么找出出現(xiàn)次數(shù)超過數(shù)組長(zhǎng)度一半的元素-創(chuàng)新互聯(lián)
URL地址:http://aaarwkj.com/article40/cdhdho.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、靜態(tài)網(wǎng)站、搜索引擎優(yōu)化、網(wǎng)站設(shè)計(jì)公司、App開發(fā)、網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容