Home > Software design >  Reverse a specific word function
Reverse a specific word function

Time:10-27

I'm having trouble doing the next task:

So basically, I need to build a function that receives a (sentence, word, occurrence) and it will search for that word and reverse it only where it occurs for example:

function("Dani likes bananas, Dani also likes apples", "lik", "2") returns: "Dani likes bananas, Dani also kiles apples"

As you can see, the "word" is 'lik' and at the second time it occurred it reversed to 'kil'.

I wrote something but it's too messy and that part still doesn't work for me,

def q2(sentence, word, occurrence):
    count = 0
    reSentence = ''
    reWord = ''
    for char in word:
        if sentence.find(word) == -1:
            print('could not find the word')
            break
        for letter in sentence:
            if char == letter:
                if word != reWord:
                    reWord  = char
                    reSentence  = letter
                    break
                elif word == reWord:
                    if count == int(occurrence):
                        reWord = word[::-1]
                        reSentence  = reWord
                    elif count > int(occurrence):
                        print("no such occurrence")
                    else:
                        count  = 1
            else:
                reSentence  = letter
    print(reSentence)

sentence = 'Dani likes bananas, Dani also likes apples'
word = 'li'
occurrence = '2'
q2(sentence,word,occurrence)

the main problem right now is that, after it breaks it goes back to check from the start of the sentence so it will find i in "Dani". I couldn't think of a way to make it check from where it stopped. I tried using enumerate but still had no idea how.

CodePudding user response:

This will work for the given scenario

scentence = 'Dani likes bananas, Dani also likes apples'
word = 'lik'
st = word
occ = 2
lt = scentence.split(word)
op = ''
if (len(lt) > 1):
    for i,x in enumerate(lt[:-1]):
        if (i 1) == occ:
            word =  ''.join(reversed(word))  
        op = op   x   word
        word = st
        
print(op lt[-1])

Please test yourself for other scenario

CodePudding user response:

Your approach shows that you've clearly thought about the problem and are using the means you know well enough to solve it. However, your code has a few too many issue to simply fix, for example:

  • you only check for occurrence of the word once you're inside the loop;
  • you loop over the entire sentence for each letter in the word;
  • you only compare a character at a time, and make some mistakes in keeping track of how much you've matched so far.
  • you pass a string '2', which you intend to use as a number 2

All of that and other problems can be fixed, but you would do well to use what the language gives you. Your task breaks down into:

  • find the n-th occurrence of a substring in a string
  • replace it with another word where found and return the string

Note that you're not really looking for a 'word' per se, as your example shows you replacing only part of a word (i.e. 'lik') and a 'word' is commonly understood to mean a whole word between word boundaries.

def q2(sentence, word, occurrence):
    # the first bit
    position = 0
    count = 0
    while count < occurrence:
        position = sentence.find(word, position 1)
        count  = 1
        if position == -1:
            print (f'Word "{word}" does not appear {occurrence} times in "{sentence}"')
            return None

    # and then using what was found for a result
    return sentence[0:position]   word[::-1]   sentence[position len(word):]

print(q2('Dani likes bananas, Dani also likes apples','lik',2))
print(q2('Dani likes bananas, Dani also likes apples','nope',2))

A bit of explanation on that return statement:

  • sentence[0:position] gets sentence from the start 0 to the character just before position, this is called a 'slice'
  • word[::-1] get word from start to end, but going in reverse -1. Leaving out the values in the slice implies 'from one end to the other'
  • sentence[position len(word):] gets sentence from the position position len(word), which is the character after the found word, until the end (no index, so taking everything).

All those combined is the result you need.

Note that the function returns None if it can't find the word the right number of times - that may not be what is needed in your case.

CodePudding user response:

import re
from itertools import islice

s = "Dani likes bananas, Dani also likes apples"
t = "lik"
n = 2

x = re.finditer(t, s)
try:
    i = next(islice(x, n - 1, n)).start()
except StopIteration:
    i = -1

if i >= 0:
    y = s[i: i   len(t)][::-1]
    print(f"{s[:i]}{y}{s[i   len(t):]}")
else:
    print(s)

Finds the 2nd starting index (if exists) using Regex. May require two passes in the worst case over string s, one to find the index, one to form the output. This can also be done in one pass using two pointers, but I'll leave that to you. From what I see, no one has offered a solution yet that does in one pass.

CodePudding user response:

  1. index = Find index of nth occurence
  2. Use slice notation to get part you are interested in (you have it's beginning and length)
  3. Reverse it
  4. Construct your result string:
result = sentence[:index]   reversed part   sentence[index len(word):]
  • Related