當前位置: 華文世界 > 科技

Python第105題:重復較短的字串【PythonTip題庫300題】

2024-02-10科技

1、編程試題:

編寫一個程式,重復長度較小的字串,直到長度等於較長字串的長度。假設兩個輸入字串的長度不相等。

定義函式repeat_till_equal_length()的函式,有兩個參數string1和string2。

在函式內,重復較短的字串,直到它等於較長的字串的長度。

範例輸入

python

pythontip

範例輸出

pythonpyt

解釋:

較長字串pythontip的長度為9,較短字串的長度為6。短字串重復,直到其長度等於9。

2、程式碼實作:

可編輯程式碼如下:

#!/usr/bin/python3.9# -*- coding: utf-8 -*-## Copyright (C) 2024 , Inc. All Rights Reserved## @Time : 2024/2/10 9:22# @Author : fangel# @FileName : 105.重復較短的字串.py# @Software : PyCharmdef repeat_till_equal_length(string1, string2): #步驟1:先確定最長的字串和最短的字串 if len(string1) < len(string2): shortStr = string1 longStr = string2 else: shortStr = string2 longStr = string1 #步驟2:確定兩者之間的差值 lenDiff = len(longStr) - len(shortStr) #步驟3:確定兩者之間的差值和最短字串的關系,一個是倍數關系,一個是模關系 i = int(lenDiff / len(shortStr)) j = lenDiff % len(shortStr) #步驟4:重復長度較小的字串,直到長度等於較長字串的長度 strNew = shortStr + shortStr * i + shortStr[0:j] return strNew# 輸入兩個字串string1 = input()string2 = input()# 呼叫函式print(repeat_till_equal_length(string1, string2))

3、代分碼析:

本例首先要確定最長和最短的字串,可以透過長度來判斷,然後計算差值,再確定兩者之間的差值和最短字串的關系,一個是倍數關系,一個是模關系最後重復 長度較小的字串即可。

4、執行結果:

輸入:

school

scholar

輸出:

schools