2

入力の連続する空白の数を調べます。入力が次の場合を考えてみましょう:

'          hi there'

すべてのスペースの数である「11」ではなく、その文字列内で最も長い「連続した」スペースである「10」という数を取得したいと思います。

どんな種類の助けも大歓迎です。

ありがとう!1つの文字列に対してこれを行う方法は理解できましたが、入力は複数行であると想定されており、それを処理できないようです。入力は次のようなものです。

'hkhkh

 hk           hk`

1つの入力に約5つの異なる行があります。

4

2 に答える 2

4

あなたは見てみたいと思うでしょうitertools.groupby

from itertools import groupby

my_string = '          hi there'
current_max = 0

# First, break the string up into individual strings for each space
split_string = my_string.split(" ")

# Then, iterate over the list returning each string
# along with an iterator containing all the matches
# that follow it in a connected run
# e. g. "aaabbaa" would produce a data structure akin to this:
# [("a", ["a", "a", "a"]), ("b", ["b", "b"]), ("a", ["a", "a"])]
for c, sub_group in groupby(split_string):
    # If the string is not an empty string (e. g. it was not a space)
    # we are not interested in it - so skip this group.
    if c != '':
        continue

    # Get the length of the run of spaces
    i = len(list(sub_group))
    if i > current_max:
        current_max = i

print("The longest run of spaces is", current_max)
于 2012-09-20T02:46:06.720 に答える
0

空白として何を定義しますか。スペースだけ、または次の項目もあります:タブ(\t)キャリッジリターン(\r)改行(\n

some_string = """hkhkh

 hk           hk



           and here"""

ls = longest_streak = 0
cs = current_streak = 0

for character in some_string:

    # or some other test will depend on your use case (numbers? '"/%$!@#$ etc.).
    # if not character in (' ', '\n', '\r', '\t'): 
    if character.isalpha():
        if cs > ls:
            ls = cs
        cs = 0
        continue

    elif character in ('\r', '\n'):
        continue

    else:
        cs += 1


print(ls)

非表示の文字にelif遭遇した場合、現在のストリークを続行します。タブを考慮したい場合は、追加することもできます。\r \n\t

于 2012-09-20T16:03:48.147 に答える