0

we have just begun our unit on recursion, and I had a question regarding non-recursive functions and strings

I understand that strings are inherently recursive, as each character within a string has its own positive or negative index value, but I am a little unclear on how to create this function.

EDIT: Please disregard above text

What I meant to say:

I understand that a sequence is recursive in nature, that a string is a character followed by another string, just as a list is an element followed by another list.

Imagine we had a function called:

def flipside(s)

And when we input a string into our s parameter of the function, for example, the string:

'homework'

It takes the first half of the string (s) and moves it to the back while taking the second half of the string moving it the front, effectively generating the output:

'workhome'

I guess what I am having an issue with, is regarding string operations. If I do not know the length of s because it can take on any value due to it being a parameter, how do I create a non-recursive program to take 1//2 of s and move that half of the string to the back while simultaneously pushing the second half forward.

I have only gone so far as to set my base case:

def flipside(s):
    if s == (''):
        return 0
    else:
        fliprest = 
        return fliprest

Thank you, I would appreciate any information on the thought process behind your logic, or any feedback regarding any bad habits that I may be developing with how I have started off my code.

  • 2
    "I understand that strings are inherently recursive, as each character within a string has its own positive or negative index value" -- I have no idea what you mean by that. – John Coleman Jul 13 '21 at 17:28
  • 2
    Is the question how to ask Python what the length of a string is? It's not clear what specific technical problem is preventing you from implementing your program without needing to recurse; note that Stack Overflow questions should be narrow and specific. – Charles Duffy Jul 13 '21 at 17:28
  • Are you asking for a recursive, or non-recursive solution? Because a non-recursive one doesn't have a base case. Also, you seem to be conflating recursive functions and the "recursive nature" of strings - the fact that single characters are also strings. – Paul M. Jul 13 '21 at 17:35
  • You're absolutely right, that made no sense, I have created a new paragraph explaining what I meant initially. I think I poorly worded my explanation, my problem is that I am trying to create a function that swaps the first half and second half of string. I am unclear on the rules of non-recursive functions and I did not know if it would require extra steps beyond just having a base case. Apologies – Mark Donovan Jul 13 '21 at 17:37

1 Answers1

0

You can use slicing

def flipside(s):
    return s[len(s)//2:] + s[:len(s)//2]

>>> flipside('homework')
'workhome'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218