python面試的100題(14)

32.請寫出一個函數知足如下條件

該函數的輸入是一個僅包含數字的list,輸出一個新的list,其中每個元素要知足如下條件:數組

一、該元素是偶數閉包

二、該元素在原list中是在偶數的位置(index是偶數)app

def num_list(num):
    return [i for i in num if i %2 ==0 and num.index(i)%2==0]

num = [0,1,2,3,4,5,6,7,8,9,10]
result = num_list(num)
print(result)

33.使用單一的列表生成式來產生一個新的列表

該列表只包含知足如下條件的值,元素爲原始列表中偶數切片函數

list_data = [1,2,5,8,10,3,18,6,20]
res = [x for x in list_data[::2] if x %2 ==0]
print(res)

34.用一行代碼生成[1,4,9,16,25,36,49,64,81,100]

[x * x for x in range(1,11)]

35.輸入某年某月某日,判斷這一天是這一年的第幾天?

import datetime

y = int(input("請輸入4位數字的年份:"))
m = int(input("請輸入月份:"))
d = int(input("請輸入是哪一天"))

targetDay = datetime.date(y,m,d)
dayCount = targetDay - datetime.date(targetDay.year -1,12,31)
print("%s是 %s年的第%s天。"%(targetDay,y,dayCount.days))

36.兩個有序列表,l1,l2,對這兩個列表進行合併不可以使用extend

def loop_merge_sort(l1,l2):
    tmp = []
    while len(l1)>0 and len(l2)>0:
        if l1[0] <l2[0]:
            tmp.append(l1[0])
            del l1[0]
        else:
            tmp.append(l2[0])
            del l2[0]
        

37.給定一個任意長度數組,實現一個函數

讓全部奇數都在偶數前面,並且奇數升序排列,偶數降序排序,如字符串'1982376455',變成'1355798642'oop

# 方法一
def func1(l):
    if isinstance(l, str):
        l = [int(i) for i in l]
    l.sort(reverse=True)
    for i in range(len(l)):
        if l[i] % 2 > 0:
            l.insert(0, l.pop(i))
    print(''.join(str(e) for e in l))

# 方法二
def func2(l):
    print("".join(sorted(l, key=lambda x: int(x) % 2 == 0 and 20 - int(x) or int(x))))

38.寫一個函數找出一個整數數組中,第二大的數

def find_second_large_num(num_list):
    """
    找出數組第2大的數字
    """
    # 方法一
    # 直接排序,輸出倒數第二個數便可
    tmp_list = sorted(num_list)
    print("方法一\nSecond_large_num is :", tmp_list[-2])
    
    # 方法二
    # 設置兩個標誌位一個存儲最大數一個存儲次大數
    # two 存儲次大值,one 存儲最大值,遍歷一次數組便可,先判斷是否大於 one,若大於將 one 的值給 two,將 num_list[i] 的值給 one,不然比較是否大於two,若大於直接將 num_list[i] 的值給two,不然pass
    one = num_list[0]
    two = num_list[0]
    for i in range(1, len(num_list)):
        if num_list[i] > one:
            two = one
            one = num_list[i]
        elif num_list[i] > two:
            two = num_list[i]
    print("方法二\nSecond_large_num is :", two)
    
    # 方法三
    # 用 reduce 與邏輯符號 (and, or)
    # 基本思路與方法二同樣,可是不須要用 if 進行判斷。
    from functools import reduce
    num = reduce(lambda ot, x: ot[1] < x and (ot[1], x) or ot[0] < x and (x, ot[1]) or ot, num_list, (0, 0))[0]
    print("方法三\nSecond_large_num is :", num)
    
    
if __name__ == '__main___':
    num_list = [34, 11, 23, 56, 78, 0, 9, 12, 3, 7, 5]
    find_second_large_num(num_list)

39.閱讀一下代碼他們的輸出結果是什麼?

def multi():
    return [lambda x : i*x for i in range(4)]
print([m(3) for m in multi()])

正確答案是[9,9,9,9],而不是[0,3,6,9]產生的緣由是Python的閉包的後期綁定致使的,這意味着在閉包中的變量是在內部函數被調用的時候被查找的,由於,最後函數被調用的時候,for循環已經完成, i 的值最後是3,所以每個返回值的i都是3,因此最後的結果是[9,9,9,9]spa

40.統計一段字符串中字符出現的次數

# 方法一
def count_str(str_data):
    """定義一個字符出現次數的函數"""
    dict_str = {} 
    for i in str_data:
        dict_str[i] = dict_str.get(i, 0) + 1
    return dict_str
dict_str = count_str("AAABBCCAC")
str_count_data = ""
for k, v in dict_str.items():
    str_count_data += k + str(v)
print(str_count_data)

# 方法二
from collections import Counter

print("".join(map(lambda x: x[0] + str(x[1]), Counter("AAABBCCAC").most_common())))
相關文章
相關標籤/搜索