Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 613
Ali Azfar Avatar asked Dec 19 '19 14:12

Ali Azfar


People also ask

What is an approach to a problem?

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.

What are the different approaches to solve a problem?

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

What are the 4 approaches to problem-solving?

Here is an attempt to classify these approaches into 4 categories – system centric, problem centric, solution centric and solver centric approach.


Video Answer


1 Answers

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)))
like image 150
DeepSpace Avatar answered Sep 21 '22 10:09

DeepSpace