Ali Azfar
Ali Azfar

Reputation: 63

What is different approach to my problem?

I am new to python and having a problem: my task was "Given a sentence, return a sentence with the words reversed"

e.g. Tea is hot --------> hot is Tea

my code was:

def funct1 (x):
    a,b,c = x.split()
    return c + " "+  b + " "+ a

funct1 ("I am home")

It did solve the answer, but i have 2 questions:

  1. how to give space without adding a space concatenation
  2. is there any other way to reverse than splitting?

thank you.

Upvotes: 6

Views: 63

Answers (2)

DeepSpace
DeepSpace

Reputation: 81664

Your code is heavily dependent on the assumption that the string will always contain exactly 2 spaces. The task description you provided does not say that this will always be the case.

This assumption can be eliminated by using str.join and [::-1] to reverse the list:

def funct1(x):
    return ' '.join(x.split()[::-1])

print(funct1('short example'))
print(funct1('example with more than 2 spaces'))

Outputs

example short
spaces 2 than more with example

A micro-optimization can be the use of reversed, so an extra list does not need to be created:

return ' '.join(reversed(x.split()))

2) is there any other way to reverse than spliting?

Since the requirement is to reverse the order of the words while maintaining the order of letters inside each word, the answer to this question is "not really". A regex can be used, but will that be much different than splitting on a whitespace? probably not. Using split is probably faster anyway.

import re

def funct1(x):
    return ' '.join(reversed(re.findall(r'\b(\w+)\b', x)))

Upvotes: 5

Ollin Boer Bohan
Ollin Boer Bohan

Reputation: 2401

A pythonic way to do this would be:

def reverse_words(sentence):
    return " ".join(reversed(sentence.split()))

To answer the subquestions:

  1. Yes, use str.join.
  2. Yes, you can use a slice with a negative step "abc"[::-1] == "cba". You can also use the builtin function reversed like I've done above (to get a reversed copy of a sequence), which is marginally more readable.

Upvotes: 2

Related Questions