mirror of
https://github.com/donnemartin/interactive-coding-challenges
synced 2026-01-06 01:18:02 +00:00
Simplify reverse string code, improve algorithm readability (#183)
This commit is contained in:
committed by
Donne Martin
parent
1d2b138344
commit
83ad7ff23a
@@ -65,7 +65,7 @@
|
|||||||
"Since Python strings are immutable, we'll use a list of chars instead to exercise in-place string manipulation as you would get with a C string.\n",
|
"Since Python strings are immutable, we'll use a list of chars instead to exercise in-place string manipulation as you would get with a C string.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"* Iterate len(string)/2 times, starting with i = 0:\n",
|
"* Iterate len(string)/2 times, starting with i = 0:\n",
|
||||||
" * Swap i and len(string) - 1 - i\n",
|
" * Swap char with index (i) and char with index (len(string) - 1 - i)\n",
|
||||||
" * Increment i\n",
|
" * Increment i\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Complexity:\n",
|
"Complexity:\n",
|
||||||
@@ -97,12 +97,11 @@
|
|||||||
"class ReverseString(object):\n",
|
"class ReverseString(object):\n",
|
||||||
"\n",
|
"\n",
|
||||||
" def reverse(self, chars):\n",
|
" def reverse(self, chars):\n",
|
||||||
" if chars is None or not chars:\n",
|
" if chars:\n",
|
||||||
" return chars\n",
|
" size = len(chars)\n",
|
||||||
" size = len(chars)\n",
|
" for i in range(size // 2):\n",
|
||||||
" for i in range(size // 2):\n",
|
" chars[i], chars[size - 1 - i] = \\\n",
|
||||||
" chars[i], chars[size - 1 - i] = \\\n",
|
" chars[size - 1 - i], chars[i]\n",
|
||||||
" chars[size - 1 - i], chars[i]\n",
|
|
||||||
" return chars"
|
" return chars"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -126,14 +125,14 @@
|
|||||||
"class ReverseStringAlt(object):\n",
|
"class ReverseStringAlt(object):\n",
|
||||||
"\n",
|
"\n",
|
||||||
" def reverse_string_alt(string):\n",
|
" def reverse_string_alt(string):\n",
|
||||||
" if string is None or not string:\n",
|
" if string:\n",
|
||||||
" return string\n",
|
" return string[::-1]\n",
|
||||||
" return string[::-1]\n",
|
" return string\n",
|
||||||
"\n",
|
"\n",
|
||||||
" def reverse_string_alt2(string):\n",
|
" def reverse_string_alt2(string):\n",
|
||||||
" if string is None or not string:\n",
|
" if string:\n",
|
||||||
" return string\n",
|
" return ''.join(reversed(string))\n",
|
||||||
" return ''.join(reversed(string))"
|
" return string"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user