2016-09-15 5 views
0

私は分かりませんが、文字列s = "azcbobobegghakl"の索引付けは、最長部分文字列アルファベット順。このコードはどのように 'beggh'がアルファベット順であることをコンピュータに伝えますか?索引付けは、文字列内の各文字に文字列が終わるまで1ずつ増やされた数字を与えたと思いましたか?コードをちょっと微調整してもうまくいきましたが、最初のコードの動作を実際には理解していません。Python-Indexing-このコードがどのように動作しているのか分かりません

s = "azcbobobegghakl" 
longest = s[0] 
current = s[0] 
for c in s[1:]: 
    if c >= current[-1]: 
     current += c 
    else: 
     if len(current) > len(longest): 
      longest = current 
     current = c 
print "Longest substring in alphabetical order is:", longest 
+0

私は非常識なので、これは同等のビッグオーバで楽しい1対1のようです(素朴なソリューションを使用することができれば簡単です):from itertools import chain、groupby'、 'from演算子import itemgetter、le'、 's'を定義すると、その一行は次のようになります:' longest = max(( "join")is_orderedのためのchain(next(g)、map(itemgetter(1)、g))) 、key = lambda p:le(* p))is_orderedの場合、key = len) 'を指定すると、groupby内のg(zip(chain((" '、)、s [: - 1])、s)これは実際には、あなたが 'itertools'と' operator'を使って行うことができる恐ろしい/素晴らしいことを誇示するだけでは、あまり役に立たないことを意図したものではありません。 :-) – ShadowRanger

答えて

1

>=は、字句順で2文字を比較します。式

if c >= current[-1]: 

試験c(単一文字)場合は、同じであるか、またはcurrent[-1](別の単一の文字よりも「大きい」である文字列は、それらのコードポイント値によって辞書式順序付けられる; a文字ためbよりも小さいです彼らは「後で」来ればこのよう

>>> 'a' > 'b' 
False 
>>> 'a' < 'b' 
True 

、文字だけの最後の文字よりもアルファベットでcurrentに追加されます。aは、Unicode標準でb前に来ます。そうでない場合は、これまでのシーケンスの長さがテストされ、新しい部分文字列がcから開始されます。

1

c >= current[-1]は、各文字と文字列の前の文字とを辞書編集で比較します。もっと単純に:

>>> 'a' >= 'a' 
True 
>>> 'b' >= 'a' 
True 
>>> 'b' >= 'c' 
False 
>>> 'z' >= 'a' 
True 

だから、すべてのコードが実行される各文字>=最後のものを持っている文字のランを蓄積する、と見最長の1を維持することです。

1
s = "azcbobobegghakl" 

# initialize vars to first letter in string 
longest = s[0] 
current = s[0] 

# start iterating through rest of string 
for c in s[1:]: 

    # c is the letter of current iteration and current[-1] 
    # is the last letter of the current string. Every character 
    # has an ASCII value so this is checking the character's 
    # numerical values to see if they are in alphabetical order (a<b<c etc.) 
    if c >= current[-1]: 

     # so if c is bigger than current[-1] (meaning it comes 
     # after in the alphabet, then we want to add it to current 
     current += c 
    else: 
     # if c was smaller then we want to check if the alphabetic 
     # string we just read is longer than the previous longest 
     if len(current) > len(longest): 
      longest = current 

     # start the current string over beginning with the letter in c 
     current = c 
print "Longest substring in alphabetical order is:", longest 
+0

だから、pythonはこれを自動的に行い、関数を呼び出す必要はありませんか? ASCII値を割り当てるコードの初期化(?)と比較 – durander

+0

ASCIIは、情報交換のためのアメリカンスタンダードコードを表し、50,000年前に各文字の価値が何であるかを決めました。 ASCIIについては、https://en.wikipedia.org/wiki/ASCIIで読むことができます。ビット値をそれぞれの文字に変換するのは、OSとコンパイラの仕事です。ここをクリックしてください:http://programmers.stackexchange.com/questions/273334/how-are-ascii-code-associations-actually-stored-and-retrieved – sbru

関連する問題