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:
thank you.
A problem-solving approach is a technique people use to better understand the problems they face and to develop optimal solutions. They empower people to devise more innovative solutions by helping them overcome old or binary ways of thinking.
There are three approaches to team problem solving: descriptive, which examines how teams solve problems; functional, which identifies the behaviors of effective problem solving; and prescriptive, which recommends techniques and approaches to improve team problem solving (Beebe & Masterson, 1994).
Here is an attempt to classify these approaches into 4 categories β system centric, problem centric, solution centric and solver centric approach.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With