/Section 3/Notebooks/Numbers in List.ipynb
Jupyter | 100 lines | 100 code | 0 blank | 0 comment | 0 complexity | 6bcb6f3ab44b18f72dc7f5cdb6ff69c0 MD5 | raw file
- {
- "cells": [
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": true
- },
- "outputs": [],
- "source": [
- "# Numbers in lists by SeanMc from forums\n",
- "# define a procedure that takes in a string of numbers from 1-9 and\n",
- "# outputs a list with the following parameters:\n",
- "# Every number in the string should be inserted into the list.\n",
- "\n",
- "# If a number x in the string is less than or equal \n",
- "# to the preceding number y, the number x should be inserted \n",
- "# into a sublist. Continue adding the following numbers to the \n",
- "# sublist until reaching a number z that\n",
- "# is greater than the number y. \n",
- "# Then add this number z to the normal list and continue."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 58,
- "metadata": {
- "collapsed": false
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[4, 5, [5, 5, 3, 2, 1, 2, 3, 2], 6, [6]]\n"
- ]
- }
- ],
- "source": [
- "myString = '455532123266'\n",
- "#result = [4, 5, [5, 5, 3, 2, 1, 2, 3, 2], 6, [6]]\n",
- "\n",
- "def numbers_in_lists(string):\n",
- " limit = len(string)\n",
- " i = 0\n",
- " z = int(string[0])\n",
- " blist = [int(string[0])]\n",
- " slist = []\n",
- " while i+1 < limit:\n",
- " if int(string[i+1]) <= z:\n",
- " slist.append(int(string[i+1]))\n",
- " i = i + 1\n",
- " else:\n",
- " if len(slist) > 0:\n",
- " blist.append(slist)\n",
- " slist = []\n",
- " else:\n",
- " z = int(string[i + 1])\n",
- " blist.append(int(string[i+1]))\n",
- " i = i + 1\n",
- " if len(slist) > 0:\n",
- " blist.append(slist)\n",
- " return blist\n",
- " \n",
- "print(numbers_in_lists(myString))\n",
- " "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "collapsed": true
- },
- "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.5.2"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 0
- }