給定一個數字字串,請依這些子字串出現的順序,輸出該字串中所有長度為n的連續子字串。
例如,字串「49142」有以下這些 3 位數的數列:
以及以下這些 4 位數的數列:
如果你向一個 5 位數的字串要求 6 位數的數列,那不管得到什麼,都怨不得別人。
請注意,這些數列只需要佔據輸入中_相鄰的位置_;這些數字不需要在_數值上連續_。
有時候,你需要引發例外。這麼做時,一定要附上有意義的錯誤訊息,指出錯誤的來源。這能讓程式碼更好讀,對除錯也有很大的幫助。如果你已知錯誤來源屬於某種類型,可以選擇引發其中一種內建錯誤類型,但仍然要附上有意義的訊息。
這個練習要求你在傳入 slice() 函式的 series 和/或 length 參數為空或超出範圍時,使用 raise 陳述式「拋出」ValueError。只有同時 raise 例外並附上訊息,測試才會通過。
若要引發帶有訊息的 ValueError,請把訊息寫成 exception 類型的引數:
# if the slice length is zero.
raise ValueError("slice length cannot be zero")
# if the slice length is negative.
raise ValueError("slice length cannot be negative")
# if the series provided is empty.
raise ValueError("series cannot be empty")
# if the slice length is longer than the series.
raise ValueError("slice length cannot be greater than series length")