Skip to content

Instantly share code, notes, and snippets.

@robsonpiere
Created November 14, 2023 22:35
Show Gist options
  • Save robsonpiere/a779529bc45a72e140d34a28a6f3d835 to your computer and use it in GitHub Desktop.
Save robsonpiere/a779529bc45a72e140d34a28a6f3d835 to your computer and use it in GitHub Desktop.
Compression challenge
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Implement a method to perform basic string compression using the counts\n",
"of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the\n",
"\"compressed\" string would not become smaller than the original string, your method should return\n",
"the original string. You can assume the string has only lowercase letters (a-z)."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"def zip_string(original: str):\n",
" final = ''\n",
" queue = []\n",
" for char in original:\n",
" if len(queue):\n",
" if char != queue[-1]:\n",
" final += f'{queue[-1]}{len(queue)}'\n",
" queue = []\n",
" queue.append(char)\n",
" else:\n",
" final += f'{queue[-1]}{len(queue)}'\n",
" if len(final) > len(original):\n",
" final = original\n",
" return final"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'a2b1c5a3'"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"zip_string('aabcccccaaa') # needs return zip"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'abc'"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"zip_string('abc') # returns original"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment