mirror of
https://github.com/rasbt/python_reference.git
synced 2024-11-24 12:31:14 +00:00
123 lines
2.7 KiB
Plaintext
123 lines
2.7 KiB
Plaintext
{
|
|
"metadata": {
|
|
"name": "",
|
|
"signature": "sha256:c78a9ef71605847c90e18bf10abda603339de473905dc928bd17aacd1ae5bee9"
|
|
},
|
|
"nbformat": 3,
|
|
"nbformat_minor": 0,
|
|
"worksheets": [
|
|
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### String formatting - `.format()` vs. `%s`"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"collapsed": false,
|
|
"input": [
|
|
"import timeit\n",
|
|
"\n",
|
|
"def test_format():\n",
|
|
" return ['{}'.format(i) for i in range(1000000)]\n",
|
|
"\n",
|
|
"def test_binaryop():\n",
|
|
" return ['%s' %i for i in range(1000000)]\n",
|
|
"\n",
|
|
"%timeit test_format()\n",
|
|
"%timeit test_binaryop()\n",
|
|
"\n",
|
|
"#print('{}: {}\\n{}: {}'.format('format()', format_res, '%s', binaryop_res))\n",
|
|
"\n",
|
|
"################################\n",
|
|
"# On my machine\n",
|
|
"################################\n",
|
|
"#\n",
|
|
"# Python 3.4.0\n",
|
|
"# MacOS X 10.9.2\n",
|
|
"# 2.5 GHz Intel Core i5\n",
|
|
"# 4 GB 1600 Mhz DDR3\n",
|
|
"#"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"1 loops, best of 3: 400 ms per loop\n",
|
|
"1 loops, best of 3: 241 ms per loop"
|
|
]
|
|
},
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 3
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### String Reversing - `[::-1]` vs. `''.join(reversed())`"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"collapsed": false,
|
|
"input": [
|
|
"def reverse_join(my_str):\n",
|
|
" return ''.join(reversed(my_str))\n",
|
|
" \n",
|
|
"def reverse_slizing(my_str):\n",
|
|
" return my_str[::-1]\n",
|
|
"\n",
|
|
"\n",
|
|
"# Test to show that both work\n",
|
|
"a = reverse_join('abcd')\n",
|
|
"b = reverse_slizing('abcd')\n",
|
|
"assert(a == b and a == 'dcba')\n",
|
|
"\n",
|
|
"%timeit reverse_join('abcd')\n",
|
|
"%timeit reverse_slizing('abcd')\n",
|
|
"\n",
|
|
"# Python 3.4.0\n",
|
|
"# MacOS X 10.9.2\n",
|
|
"# 2.4 GHz Intel Core Duo\n",
|
|
"# 8 GB 1067 Mhz DDR3\n",
|
|
"#"
|
|
],
|
|
"language": "python",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"1000000 loops, best of 3: 1.28 \u00b5s per loop\n",
|
|
"1000000 loops, best of 3: 337 ns per loop"
|
|
]
|
|
},
|
|
{
|
|
"output_type": "stream",
|
|
"stream": "stdout",
|
|
"text": [
|
|
"\n"
|
|
]
|
|
}
|
|
],
|
|
"prompt_number": 13
|
|
}
|
|
],
|
|
"metadata": {}
|
|
}
|
|
]
|
|
} |