Files
Python/Sorting Algorithms/Radix_Sort.ipynb
Joe James f97b3a2391 Revised function call.
Moved __get_num_digits() function call into the radix() function, so the only parameter when calling radix() is a List.
2020-10-21 19:57:42 -07:00

122 lines
2.7 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Radix Sort\n",
"(c) 2020, Joe James"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# get number of digits in largest item\n",
"def __get_num_digits(A):\n",
" m = 0\n",
" for item in A:\n",
" m = max(m, item)\n",
" return len(str(m))"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# flatten into a 1D List\n",
"from functools import reduce\n",
"def __flatten(A):\n",
" return reduce(lambda x, y: x + y, A)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Changed from YouTube video:\n",
"It's much cleaner to put the _get_num_digits call inside the radix function rather than in main as shown in the video. That way you only need to pass a List to the radix function. Thanks to Brother Lui for this suggestion."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def radix(A):\n",
" num_digits = __get_num_digits(A)\n",
" for digit in range(0, num_digits):\n",
" B = [[] for i in range(10)]\n",
" for item in A:\n",
" # num is the bucket number that the item will be put into\n",
" num = item // 10 ** (digit) % 10\n",
" B[num].append(item)\n",
" A = __flatten(B)\n",
" return A"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 45, 53, 55, 213, 288, 289]\n",
"[0, 1, 2, 3, 4, 5] [999994, 999995, 999996, 999997, 999998, 999999]\n"
]
}
],
"source": [
"def main():\n",
" A = [55, 45, 3, 289, 213, 1, 288, 53, 2]\n",
" A = radix(A)\n",
" print(A)\n",
" \n",
" B = [i for i in range(1000000)]\n",
" from random import shuffle\n",
" shuffle(B)\n",
" B = radix(B)\n",
" print(B[:6], B[-6:])\n",
"\n",
"main()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.7.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}