Python Forum

Full Version: Code discussion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone, I came across this problem(which is quite interesting):
input: a sentence
output: that sentence in reverse
E.g: input: 'abc 123 abcd'
output:'abcd 123 abc'
I succeeded in solving this problem but my code is too long.
sentence=input('enter a sentence: ')
new_sen=[]
def split(sen):
    if len(sen)==0:
        return new_sen
    else:
        if sen.find(' ')!= -1:
            for i in range(0,len(sen)):
                if sen[len(sen)-i-1]!=' ':
                    pass
                else:
                    first=sen[:(len(sen)-i)]
                    second=sen[(len(sen)-i):]
                    new_sen.append(second)
                    break
            count=0
            for i in range(0,len(first)):
                if first[len(first)-i-1]==' ':
                    count+=1
                else:
                    break
            new_sen.append(' '*count)
            global third
            third=first[:(len(first)-count)]
            split(third)
        else:
            new_sen.append(third)
        return new_sen
final_list=split(sentence)
emp_list=''
for i in range(0,len(final_list)):
    emp_list+=final_list[i]
print(emp_list)
I'm trying to find many others ways to solve this. I'm looking forward to listening to your ideas and algorithm.
>>> ' '.join('abc 123 abcd'.split()[::-1])
'abcd 123 abc
the magic of Python :-)
But what if [Image: p6nz]
can join and split function do this?
I almost did your homework. Put a little effort and use what I show you...