mirror of
https://github.com/donnemartin/interactive-coding-challenges.git
synced 2024-03-22 13:11:13 +08:00
Handled in a Single Function.
Tried to handle in a single function. Passes all test cases.
This commit is contained in:
parent
2865bdcf94
commit
92d10aed5e
|
@ -102,21 +102,15 @@
|
|||
" def compress(self, string):\n",
|
||||
" if string is None or not string:\n",
|
||||
" return string\n",
|
||||
" result = ''\n",
|
||||
" prev_char = string[0]\n",
|
||||
" count = 0\n",
|
||||
" for char in string:\n",
|
||||
" if char == prev_char:\n",
|
||||
" count += 1\n",
|
||||
" count = 1\n",
|
||||
" encodedString = \"\"\n",
|
||||
" for x in range(0,len(string)):\n",
|
||||
" if x + 1 < len(string) and string[x] == string[x + 1]:\n",
|
||||
" count = count + 1\n",
|
||||
" else:\n",
|
||||
" result += self._calc_partial_result(prev_char, count)\n",
|
||||
" prev_char = char\n",
|
||||
" count = 1\n",
|
||||
" result += self._calc_partial_result(prev_char, count)\n",
|
||||
" return result if len(result) < len(string) else string\n",
|
||||
"\n",
|
||||
" def _calc_partial_result(self, prev_char, count):\n",
|
||||
" return prev_char + (str(count) if count > 1 else '')"
|
||||
" encodedString = encodedString + string[x] + (str(count) if count > 1 else '')\n",
|
||||
" count = 1\n",
|
||||
" return encodedString if len(encodedString) < len(string) else string"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
Loading…
Reference in New Issue
Block a user