euler/ipython/EulerProblem024.ipynb

110 lines
2.7 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Euler Problem 24 \n",
"\n",
"A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:\n",
"\n",
"012 021 102 120 201 210\n",
"\n",
"What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I tried to solve this by thinking and failed to be hones. So we implement a generator and get the millionth element."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from collections import deque\n",
"\n",
"def permutation_generator(xs):\n",
" if not xs:\n",
" yield deque()\n",
" r = []\n",
" for i in range(len(xs)):\n",
" x = xs[i]\n",
" ys = permutation_generator(xs[:i] + xs[i+1:])\n",
" for y in ys:\n",
" y.appendleft(x)\n",
" yield y\n",
" raise StopIteration\n",
"\n",
"assert(list(map(lambda s: \"\".join(s), permutation_generator(\"012\"))) == ['012', '021', '102', '120', '201', '210'])"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"All right, now we reuse the function to get the nth element from problem 7 and give ourselves a solution."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2783915460\n"
]
}
],
"source": [
"def get_nth(generator, n):\n",
" import itertools\n",
" return next(itertools.islice(generator, n - 1, n))\n",
"\n",
"ps = permutation_generator(\"0123456789\")\n",
"s = int(\"\".join(get_nth(ps, 1000000)))\n",
"assert(s == 2783915460)\n",
"print(s)"
]
}
],
"metadata": {
"completion_date": "Thu, 5 Nov 2015, 16:04",
"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.5.4"
},
"tags": [
"permutation"
]
},
"nbformat": 4,
"nbformat_minor": 0
}