2012-05-24 8 views
5

Qual è il modo pitone per farlo?Ordine inverso di una stringa senza str.split() consentito

Da questo: 'Questa è una stringa di provare' a questo: 'cercare di stringa di un Questo è l''

La mia prima risposta è stata:

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

ma str.split() non è permesso. Poi sono arrivato fino a questo:

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

invertire l'intera stringa. quindi invertire (indietro) ogni singola parola. –

+4

È un compito? – FallenAngel

+0

Scrivi la tua divisione quindi. –

risposta

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

Mentre si usa '+' per concatenare un aspetto piacevole, non è molto efficiente ... – Darthfett

-3

Edit: bene, se str.split era permesso, sarebbe questo ;-) In alternativa, si potrebbe scrivere la propria versione di scissione naturalmente.

>>> 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' 

ci sono tre fasi: raggruppati per lo spazio, invertire la lista con le parole e concatenare la lista di stringhe per una stringa con spazi in mezzo.

+0

non ha letto il titolo eh? :) –

+0

Ah anzi, troppo veloce :) –

+0

'str.split() non è consentito' – inspectorG4dget

0

Creare un ciclo che scorre la stringa all'indietro, utilizzando l'indicizzazione delle stringhe per ottenere ciascun carattere. Ricordate, in Python, è possibile accedere le stringhe utilizzando il seguente:

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' 

uno di linea (ad eccezione po 'il 'importazione Re'), come richiesto:

>>> 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

Usare 're.split' invece di' str.split'? Bene, ** se fossero compiti a casa **, l'insegnante ** non sarebbe ** molto felice di questo trucco :) –

3

Ecco un'implementazione O (n) (non utilizza la concatenazione tramite +):

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)) 

Questo implementa letteralmente l'algoritmo di divisione, suddividendo manualmente la stringa in parole e quindi invertendo l'elenco di parole.

+0

Questo invertire le parole non la frase. – Stiggo

+0

@Stiggo whoops, ho dimenticato di aggiungere un finale invertito, che avrebbe risolto. L'ho risolto e ottimizzato in modo che ora sia molto più semplice. – Darthfett

0

Usa RE

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

Se string.partition è consentito in sostituzione:

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

altrimenti fallback su string.find:

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

In alcune interviste sei vincolato quando si utilizza Python, ad es non utilizzare reversed, [::-1] o .split().

In questi casi, il seguente codice nel Python 2.7 può funzionare (adottato dalla risposta di Darthfett sopra):

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

programma più semplice senza utilizzare alcun costruito in metodi:

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") 
Problemi correlati