Python 面試題:輸入一個數組,輸出該數組的第二大的數字

問題:
輸入一個數組,輸出該數組的第二大的數字,而且編寫相關的測試用例python

注意:數組

1.若是list含有非int, float元素須要remove
2.若是list有重複的最大元素,須要本身處理,內置的list.sort(reverse=True)heapq.nlargest排序,元素個數不變。app

附上代碼測試

removeInvalidItems 去掉不是int或float類型的值。
注意:不能像下邊這樣用一次循環,由於remove某個元素,下標發生了改變,有些值並不能移除code

for item in l:  # remove non_value items
    if not isinstance(item, (int, float)):
        l.remove(item)

下邊是可用代碼,文件名爲 findSecondUtil.pyblog

def removeInvalidItems(l):
    tmpl = list()
    for item in l:
        if not isinstance(item, (int, float)):
            tmpl.append(item)
    for item in tmpl:
        l.remove(item)
    return l

findSecondItem.py 實現找到第二大數字的第一種方法。這種方法不用去掉重複元素。排序

import sys
from hyang.python3.interview.boyan.findSecondUtil import removeInvalidItems
#from findSecondUtil import removeInvalidItems
 
def findSecond(l):
    l = removeInvalidItems(l)
    length = len(l)
    if length == 0:
        print("there is no number item in the list")
        return None
    elif length == 1:
        print("there is only one number item, it's ", l[0])
        return None
    elif length > sys.maxsize:
        print("out of scope")
        return None
    largest, second = max(l), min(l)
    if largest == second:
        return None
    for item in l:
        if item > second and item < largest:
            second = item
    return second

findSecondTest.py 測試代碼圖片

import unittest
from hyang.python3.interview.boyan.findSecondItem import findSecond
#from findSecondItem import findSecond
 
 
class Test_findSecondItem(unittest.TestCase):
 
    # 若是跑全部用例,只運行一次前提條件和結束條件。則用setupclass()和teardownclass()
    @classmethod
    def setUpClass(cls):
        print("在全部的測試用例執行以前,只執行一次============")
 
    @classmethod
    def tearDownClass(cls):
        print("在全部的測試用例執行以後,只執行一次============")
 
    # empty list
    def test_findSecondItem_01(self):
        l1 = list()
        assert (findSecond(l1) == None)
 
    # one item in list
    def test_findSecondItem_02(self):
        l1 = [2]
        assert (findSecond(l1) == None)
 
    # No item in list after remove non-number items
    def test_findSecondItem_03(self):
        l1 = [None, "abc", "xyz"]
        assert (findSecond(l1) == None)
 
    # one item in list after remove non-number items
    def test_findSecondItem_04(self):
        l1 = [None, 3, "abc"]
        assert (findSecond(l1) == None)
 
    # duplated largest number
    def test_findSecondItem_05(self):
        l1 = [32, None, 12, "abc", 8, 6, 36, 3, 32, 4, 36, 9, 25, '35', 36]
        assert (findSecond(l1) == 32)
 
 
# python3中寫不寫都會執行的
if __name__ == '__main__':
    unittest.main()

方法二:findSecondNum.py 從列表去掉全部的最大元素,再在列表中找一個最大就是第二大元素。rem

import sys
from hyang.python3.interview.boyan.findSecondUtil import removeInvalidItems
 
def findSecond(l):
    l = removeInvalidItems(l)
    length = len(l)
    if length == 0:
        print("there is no number item in the list")
        return None
    elif length == 1:
        print("there is only one number item, it's ", l[0])
        return None
    elif length > sys.maxsize:
        print("out of scope")
        return None
    largest=max(l)
    largest_count=l.count(largest)
    while largest_count>0:  #remove all the largest item
        l.remove(largest)
        largest_count-=1
    if len(l)==0:
        return None
    else:
        return max(l)

  

方法三:利用內置的list.sort,可是要去掉重複元素it

import sys
from hyang.python3.interview.boyan.findSecondUtil import removeInvalidItems
 
def findSecond(l):
    removeInvalidItems(l)
    l2 = list(set(l))   # remove duplicated items
    l2.sort(reverse=True)
    length=len(l2)
    if length>=2:
        return l2[1]
    else:
        return None

方法四:與方法三相似,利用內置的heapq.nlargest,也須要去掉重複元素

import sys, heapq
from hyang.python3.interview.boyan.findSecondUtil import removeInvalidItems
 
def findSecond(l):
    removeInvalidItems(l)
    l2 = list(set(l))   # remove duplicated items
    length = len(l)
    length = len(l2)
    if length >= 2:
        return heapq.nlargest(2, l2)[1]
    else:
        return None

最後須要注意執行程序所在路徑,見下圖,能夠結合本身的配置來調整。
在這裏插入圖片描述

相關文章
相關標籤/搜索