2017-12-28 4 views
-2

アルファベット順に文字が出現するsの最長部分文字列を表示するプログラムを書いてください。たとえば、s = 'azcbobobegghakl'の場合、プログラムはアルファベット順で最長の部分文字列を表示します:beggh。誰でもPythonの次のコードを説明することができます(私は新人です)

結び目の場合は、最初の部分文字列を出力します。例えば、

s = "azcbobobegghakl" 

x = s[0] 

y = s[0] 


for i in range (1, len(s)): 

    if s[i] >= s[i-1]: 
     y += s[i] 

    else: 
     y = s[i] 

    if len(y) > len(x): 
     x = y    
print(x) 

答えて

3

abcbc S =」場合、これは宿題のようなにおいが...ここで は説明するコメントです:

# assign a string to a variable named s 
s = "azcbobobegghakl" 

# assign the zeroth character of the string s to x 
x = s[0] 

# assign the zeroth character of the string s to y  
y = s[0] 


# loop through a range of numbers starting at 1 and going to the length of s 
# within each loop, the variable i tells us which iteration of the loop 
# we're currently in.  
for i in range(1, len(s)): 
    # compare the character in s at the position equal 
    # to the current iteration number to see if it's greater 
    # than or equal to the one before it. Alphabetic characters 
    # compared like this will evaluate as numbers corresponding 
    # to their position in the alphabet. 
    if s[i] >= s[i-1]: 
     # when characters are in alphabetical order, add them to string y 
     y += s[i] 
    else: 
     # when the characters are not in alphabetical order, replace y with 
     # the current character 
     y = s[i] 
    # when the length of y is greater than of x, assign y to x 
    if len(y) > len(x): 
     x = y 
# after finishing the loop, print x 
print(x) 
+0

本当に宿題ですが、私の欲求不満が私をここにもたらしました。私はあなたの答えを本当に感謝しています、あなたはまた、yとxを比較する背後にある目的は何ですか? – ZeeShan

+0

"プログラムでは、最長部分文字列" "を出力して部分文字列を作成する必要があります。また、部分文字列を作成するときに、変更するたびに最後の部分文字列と比較します。それが長くなると、それを保存します。それ以下であれば、アルファベット順の部分文字列を作成するだけです。 – TheAtomicOption

0

Pythonでstringクラスは__lt____eq__データ・モデルのメソッドが含まれています、やるために私たちを可能にする -

str1 = 'aaa' 
str2 = 'bbb' 
str3 = 'aaa' 

assert str2 < str1 # Will lead to AssertionError 
        # '<' calls the __lt__() method of the string class 

assert str1 == str3 # No AssertionError 
        #'==' calls the __eq__() method of the string class 

stringクラス共同でこれらの特定のデータ・モデルのメソッド文字列中の各文字のASCII値をmpareします。英字の各文字のASCII値は、 'A' < 'B' < 'C'の順に増加します。

時間(第二文字から始まる)で、文字列の1つの文字を通して、あなたのコード

あなたのループは、現在の文字が前のものよりも大きい(または同等の)ASCII値を持っているかどうかを確認。存在する場合、その文字はy文字列に追加され、結果の文字列はyとして格納されます。そうでない場合、yは現在の文字に置き換えられます。最後にyの文字数がxより大きい場合は、xの文字列をyで置き換えます。

+0

これは私が正確に探していたものです。おかげさまで本当にありがとうございます。神のお恵みがありますように。 – ZeeShan

+0

ようこそ。あなたが好きなら、あなたはこの答えを受け入れることができます。 –

関連する問題