Last active
August 29, 2015 14:01
-
-
Save cessor/38cc549f5456b0923f28 to your computer and use it in GitHub Desktop.
Reverse Recurse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Javascript | |
========== | |
function reverse(string) { | |
if(string.length > 0) { | |
var head = string.slice(0,1); | |
var tail = string.slice(1); | |
return reverse (tail) + head; | |
} else { | |
return []; | |
} | |
} | |
range = [0,1,2,3,4,5,6,7,8,9] | |
console.log(reverse(range)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Python | |
====== | |
def reverse(string): | |
if not string: | |
return [] | |
head = string[:1] | |
tail = string[1:] | |
return reverse(tail) + head | |
print reverse(range(10)) | |
Hier vielleicht ein bisschen weniger magic im Hintergrund (alles ein wenig sauberer). Damit du mal ein wenig Gefühl für Python bekommst hab ich den Code mal an den JS Code von oben angeleht. | |
In Python geht das allerdings auch Funktionaler: | |
reverse = lambda string: (reverse(string[1:]) + string[:1] if string else []) | |
Der Code ist genau der selbe Algorithmus wie oben, aber als Lambda Ausdruck. Das If Else wird über eine Conditional Expression abgebildet (so ne art Ternary) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment