Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code discussion
#1
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.
Reply
#2
>>> ' '.join('abc 123 abcd'.split()[::-1])
'abcd 123 abc
the magic of Python :-)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
But what if [Image: p6nz]
can join and split function do this?
Reply
#4
I almost did your homework. Put a little effort and use what I show you...
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020