1

したがって、プログラムの出力を次のようにする必要があります。

ababa
ab ba 
 xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
 no dot at the end
The largest run of consecutive whitespace characters was 47.

しかし、私が得ているのは次のとおりです。

ababa

ab ba

xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
no dot at the end
The longest run of consecutive whitespace characters was 47.

私が書いたコードをさらに調べたところ、print(c)これが起こるというステートメントが見つかりました:

['ababa', '', 'ab           ba ', '', '                                      xxxxxxxxxxxxxxxxxxx', 'that is it followed by a lot of spaces                         .', '                                               no dot at the end']

いくつかの行の間に が, '',あります。おそらく、これが print ステートメントが機能しない原因です。

どうすればそれらを削除できますか? さまざまなリスト関数を使用してみましたが、構文エラーが発生し続けます。

これは私が作ったコードです:

  a = '''ababa

    ab           ba 

                                      xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces                         .
                                               no dot at the end'''


c = a.splitlines()
print(c)

#d = c.remove(" ") #this part doesnt work
#print(d)

for row in c:
    print(' '.join(row.split()))

last_char = ""
current_seq_len = 0
max_seq_len = 0

for d in a:
    if d == last_char:
        current_seq_len += 1
        if current_seq_len > max_seq_len:
            max_seq_len = current_seq_len
    else:
        current_seq_len = 1
        last_char = d
    #this part just needs to count the whitespace

print("The longest run of consecutive whitespace characters was",str(max_seq_len)+".")
4

3 に答える 3

2

正規表現時間:

import re

print(re.sub(r"([\n ])\1*", r"\1", a))
#>>> ababa
#>>>  ab ba 
#>>>  xxxxxxxxxxxxxxxxxxx
#>>> that is it followed by a lot of spaces .
#>>>  no dot at the end

re.sub(matcher, replacement, target_string)

マッチャーとはr"([\n ])\1*、次のことを意味します。

([\n ]) → match either "\n" or " " and put it in a group (#1)
\1*     → match whatever group #1 matched, 0 or more times

そして、交換はちょうど

\1 → group #1

で最長の空白シーケンスを取得できます

max(len(match.group()) for match in re.finditer(r"([\n ])\1*", a))

これは同じマッチャーを使用しますが、代わりに長さを取得してからmaxs します。

于 2013-09-20T11:51:48.253 に答える
1

filterこれは、組み込み関数を使用して簡単に解決できます。

c = filter(None, a.splitlines())
# or, more explicit
c = filter(lambda x: x != "", a.splitlines())

最初のバリアントは、空の文字列のように、 によって返されたリストから、a.splitlines()に評価されないすべての要素を含むリストを作成します。2 番目のバリアントは、指定された要素が空の文字列かどうかをチェックし、そうであれば返すFalse小さな無名関数を ( を使用して) 作成します。これは、最初のバリアントよりも明確です。lambdaFalse

別のオプションは、同じことを達成するリスト内包表記を使用することです。

c = [string for string in a.splitlines if string]
# or, more explicit
c = [string for string in a.splitlines if string != ""]
于 2013-09-20T11:45:07.913 に答える