2012-05-24 23 views
5

これを行うにはどうしたらいいですか?これに 'これはしようとする文字列である': '文字列aにしてみてください。これは'str.split()を持たない文字列の逆順が可能

私の最初の推測があった。このことから

for w in 'This is a string to try'.split(' ')[::-1]: 
    print w, 

しかしstr.split()許可されていません。そして、私はこの思い付いた:

def reverse_w(txt): 
    tmp = [] 
    while (txt.find(' ') >= 0): 
     tmp.append(txt[:txt.find(' ')]) 
     txt = txt[txt.find(' ')+1:] 
    if (txt.find(' ') == -1): 
     tmp.append(txt) 
    return tmp[::-1] 
+0

が文字列全体を逆。個々の単語を逆にしてください。 –

+4

これは宿題ですか? – FallenAngel

+0

あなた自身の分割を書くだけです。 –

答えて

3
def reverse(sentence): 
sentence = 'This is a string to try' 
    answer = '' 
    temp = '' 
    for char in sentence: 
     if char != ' ': 
      temp += char 
     else: 
      answer = temp + ' ' + answer 
      temp = '' 
    answer = temp + ' ' + answer 
    return answer 
+0

'+'を使って連結してみると、効率的ではありません... – Darthfett

-3

編集:str.splitが許可された場合も、それはこれをだろう;-)また、あなたはもちろんのスプリットの独自のバージョンを書くことができます。

>>> s = 'This is a string to try' 
>>> r = s.split(' ') 
['This', 'is', 'a', 'string', 'to', 'try'] 
>>> r.reverse() 
>>> r 
['try', 'to', 'string', 'a', 'is', 'This'] 
>>> result = ' '.join(r) 
>>> result 
'try to string a is This' 

は、以下の3つのステップがあります。スペースで分け、言葉でリストを逆にして、間にスペースを1つの文字列に文字列のリストを連結します。

+0

タイトルを読んでいないのですか? :) –

+0

本当にあまりにも速いです。 –

+0

'str.split()は許可されていません。 ' – inspectorG4dget

0

各文字を取得するために文字列インデックスを使用して、文字列を逆順に反復するループを作成します。要求されるように( '輸入再' ビットを除く)

s = "Strings!" 
sOne = s[1] // == "t" 
0
>>> import re 
>>> s = 'This is a string to try' 
>>> z = re.split('\W+', s) 
>>> z.reverse() 
>>> ' '.join(z) 
'try to string a is This' 

ワンライナー::ここで

>>> reduce(lambda x, y: u'%s %s' % (y, x), re.split('\W+', 'This is a string to try')) 
u'try to string a is This' 
+0

'str.split'ではなく' re.split'を使用していますか?まあ、**宿題**の場合、教師**はこのトリックについてとても幸せではありません:) –

3

Pythonでは、あなたは以下を使用して文字列にアクセスすることができ、覚えておいてくださいO(n)実装(+による連結は使用しない):

def reverse_w(txt): 
    words = [] 
    word = [] 

    for char in txt: 
     if char == ' ': 
      words.append(''.join(word)) 
      word = [] 
     else: 
      word.append(char) 
    words.append(''.join(word)) 

    return ' '.join(reversed(words)) 

これは分割アルゴリズムを文字通りに実装します。手動で文字列を単語に分割し、次に単語のリストを逆にします。

def reversed_words(s): 
    out = [] 
    while s: 
     word, _, s = s.partition(' ') 
     out.insert(0, word) 
    return ' '.join(out) 

それ以外のstring.Findにフォールバック:string.partitionは、代替として許可されている場合

+0

これは、文ではなく言葉を逆転させるものです。 – Stiggo

+0

@ Stiggo whoops、私はそれを修正したであろう最終的な逆を加えるのを忘れた。私はそれを固定し最適化しましたので、現在ははるかに簡単です。 – Darthfett

0

使用は

import re 
myStr = "Here is sample text" 
print " ".join(re.findall("\S+",myStr)[::-1]) 
0

を再

def reversed_words(s): 
    out = [] 
    while s: 
     pos = s.find(' ') 
     if pos >= 0: 
      word, s = s[:pos], s[pos+1:] 
     else: 
      word, s = s, '' 
     out.insert(0, word) 
    return ' '.join(out) 
0

をあなたがしているいくつかのインタビューでPythonを使用するときに制約があります。 reversed,[::-1]、または.split()を使用しないでください。これらの場合において

Python 2.7で次のコードは、(上記Darthfettの回答から採用)動作することができる:

def revwords(sentence): 
    word = [] 
    words = [] 

    for char in sentence: 
     if char == ' ': 
      words.insert(0,''.join(word)) 
      word = [] 
     else: 
      word.append(char) 
    words.insert(0,''.join(word)) 

    return ' '.join(words) 
0

最も簡単なプログラムを任意の方法で構築された使用せず:

def reverse(sentence): 
    answer = '' 
    temp = '' 
    for char in sentence: 
     if char != ' ': 
      temp += char 
      continue 
     rev = '' 
     for i in range(len(temp)): 
      rev += temp[len(temp)-i-1] 
     answer += rev + ' ' 
     temp = '' 
    return answer + temp 
reverse("This is a string to try") 
関連する問題