Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To reverse a string you use <code>'this is a string'[::-1]</code>.</p> <p><code>[::-1]</code> Is slice notation which says include everything from the start to the end of the string but do it in reverse. <code>'abcdefghijk'[6:1:-2]</code> outputs <code>'gec'</code> because it goes from the 6th index (starting with 0) up to but not including the first index, in reverse steps of 2.</p> <p>Read up more on slice notation:<a href="https://stackoverflow.com/questions/509211/pythons-slice-notation">Explain Python&#39;s slice notation</a>, <a href="http://docs.python.org/2.3/whatsnew/section-slices.html" rel="nofollow noreferrer">http://docs.python.org/2.3/whatsnew/section-slices.html</a></p> <pre><code>def semordnilap(str1, str2): if str1 == str2[::-1]: return True else: return False </code></pre> <p>One way to do it recursively:</p> <pre><code>def semordnilap(str1, str2): if not (len(str1) or len(str2)): return True if not (len(str1) and len(str2)): return False if str1[0] != str2[-1]: return False return semordnilap(str1[1:], str2[:-1]) </code></pre> <p>The first line checks if both strings are empty (<code>0</code> evaluates to <code>False</code>, any other number is <code>True</code>). <code>len(str1)</code> returns the length as an integer.</p> <p>Then it checks if only one of the strings is empty in which case they are not equal.</p> <p>Then it checks if the first letter is the same as the last letter.</p> <p>Then it repeats the process with the each string (minus the first letter of str1 and minus the last letter of str2). It goes until one of the base cases is reached. The base case is what is returned. So it will only return <code>True</code> when then first letter was equal to the last letter each round until both strings ran out of characters at the same time.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload