1. 程式人生 > >Python刷題筆記(2)- 取5位大數字

Python刷題筆記(2)- 取5位大數字

In the following 6 digit number:

283910

91 is the greatest sequence of 2 digits.

Complete the solution so that it returns the largest five digit number found within the number given.. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.

Adapted from ProjectEuler.net

中文簡介

從輸入的若干連續數字(輸入為字串)中提取其中連續的最大5位數(整數輸出)

想法:

1.最大連續5位數,首先想到的是歷遍每個數位,然後擷取連續的5位進行,不過這樣數字位太多的時候過於繁雜

2.數字大小可以根據首位數的大小進行篩選,這樣可以減少一大部分運算,可以通過集合來判斷首位最大數

3.從原字串中擷取首位為最大數的5位連續數字,建立列表,然後進行排序

實現:

def solution(digits):
    big = sorted([ i for i in set(digits) ])[-1]    #獲取digits中最大數字
    num_list = [digits[:5]]    #僅有5位數
    for i in range(len(digits)-4):
        if digits[i] == big:
            num_list.append(digits[i:i+5])    #獲取首位跟最大數字相等的5位數,放入列表
    return int(sorted(num_list)[-1])    #將列表排序,獲取列表中最大數切片,並轉化為整數

對比總結:

提交後,發現原來有max()函式可以直接取最大值,不用我用的sorted()再取切片那麼麻煩,另外最好練習的人是直接歷遍函式取切片然後用max獲取最大值的,看來先比較首字母可能反而是我想多了。。