Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save battis/5536248 to your computer and use it in GitHub Desktop.
Save battis/5536248 to your computer and use it in GitHub Desktop.
{
"metadata": {
"name": "Python Challenge (Sample Solutions)"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": "###Python Challenge: Patterns, Round 1\nCan you write a script that will print out each of the following patterns, in order?\n\n<pre>***\n\n*\n*\n*\n\n*\n *\n *\n\n* * *\n * *\n* * *</pre>\n\n\nHint: I would recommend defining a function to print each pattern! It will make it easier to both debug and read your code\u2026 and probably set you up for better success on [Python Challenge: Patterns, Round 2](https://stmarksschool.instructure.com/courses/15/assignments/1393)!"
},
{
"cell_type": "code",
"collapsed": false,
"input": "'''Python Challenge: Patterns, Round 1\n Sample solution\n'''\n\ndef horizontalLineSimple():\n print('***')\n\ndef horizontalLine():\n stars = list(range(3))\n for star in stars:\n print('*', sep = '', end = '')\n print('')\n\ndef verticalLine():\n stars = list(range(3))\n for star in stars:\n print('*')\n\ndef diagonalLine():\n stars = list(range(3))\n for star in stars:\n spaces = list(range(star))\n for space in spaces:\n print(' ', sep = '', end = '')\n print('*')\n\ndef flag():\n rows = list(range(3))\n columns = list(range(5))\n for row in rows:\n for column in columns:\n if row % 2 == 0:\n if column % 2 == 0:\n print('*', sep = '', end = '')\n else:\n print (' ', sep = '', end = '')\n else:\n if column % 2 == 0:\n print (' ', sep = '', end = '')\n else:\n print ('*', sep = '', end = '')\n print('')\n\nhorizontalLine()\nverticalLine()\ndiagonalLine()\nflag()",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "##Python Challenge: CS Dictionary\n\nWorking from our [Glossary Of Vocabulary](https://stmarksschool.instructure.com/courses/15/wiki/glossary-of-vocabulary) (i.e. don't feel the need to write your own new definitions!), can you write a program that will act as a \"computer science dictionary\", looking up any term (load it with at least ten possibilities) that the user enters? Can you have this program run forever, until the user tells it to quit? Can you tell have it tell the user if they have asked for a term that's not in your dictionary?\n\nHint: you can use the len() function to ask for the length (the number of characters) of a string:\n\n<pre>>>> s = 'hello'\n>>> print(len(s))\n5</pre>"
},
{
"cell_type": "code",
"collapsed": false,
"input": "\"\"\"\nPython Challenge: Computer Science Dictionary\nSample Solution\n\"\"\"\n\ndef buildDictionary():\n d = dict()\n d['Bandwidth'] = 'The amount of data that can be transmitted in a fixed amount of time.'\n d['Bios'] = 'Basic Input/Output System, the built in software on the motherboard that does the most basicoperations on a computer.'\n d['Bit'] = 'Short for \u201cbinary digit\u201d, the smallest unit of information on a machine.'\n d['Boolean Logic'] = 'Named after the nineteenth-century mathematician George Boole, Boolean logic is a form of algebra in which all values are reduced to either TRUE or FALSE.'\n d['Byte'] = 'Abbreviation for \u201cbinary term\u201d, a unit of storage capable of holding a singlecharacter (1 byte = 8 bits).'\n d['Cpu'] = 'It stands for the central processing unit, the part of a computer thatcontrols the commands and helps interpret information for a computer to function.'\n d['Device'] = 'Any machine or component that attaches to a computer (examples: disk drives, printers, mice and modems).'\n d['Driver'] = 'A driver is a software that will help connect the hardware to other parts of the computer.'\n d['Stop'] = 'The end of this program. Good bye!'\n return d\n\ndef isInDictionary(term, dictionary):\n if term in dictionary:\n return True\n else:\n return False\n\ndef lookup(dictionary):\n term = input('What term would you like to define? ').title()\n if isInDictionary(term, dictionary):\n print('\"{}\" is defined as \"{}\"'.format(term, dictionary[term]))\n else:\n print('{} can\\'t be defined.'.format(term))\n return term\n\ndef main():\n dictionary = buildDictionary()\n term = ''\n while term != 'Stop':\n term = lookup(dictionary)\n\nmain()",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Python Challenge: Patterns, Round 2\nExpanding on [Python Challenge: Patterns, Round 1](https://stmarksschool.instructure.com/courses/15/assignments/1389), can you now ask the user for a number (or two) that will determine the size of the patterns? For example:\n\n<pre>Enter a number: 4\n****\n\n*\n*\n*\n*\n\n*\n *\n *\n *\n\nEnter another number: 5\n* * * * *\n * * * *\n* * * * *\n* * * *</pre>"
},
{
"cell_type": "code",
"collapsed": false,
"input": "\"\"\"\nPython Challenge: Patterns, Round 2\nSample solution\n\"\"\"\n\ndef horizontalLine(number):\n stars = list(range(number))\n for star in stars:\n print('*', sep = '', end = '')\n print('')\n\ndef verticalLine(number):\n stars = list(range(number))\n for star in stars:\n print('*')\n\ndef diagonalLine(number):\n stars = list(range(number))\n for star in stars:\n spaces = list(range(star))\n for space in spaces:\n print(' ', sep = '', end = '')\n print('*')\n\ndef flag(r, c):\n rows = list(range(r))\n columns = list(range(c))\n for row in rows:\n for column in columns:\n if row % 2 == 0:\n if column % 2 == 0:\n print('*', sep = '', end = '')\n else:\n print (' ', sep = '', end = '')\n else:\n if column % 2 == 0:\n print (' ', sep = '', end = '')\n else:\n print ('*', sep = '', end = '')\n print('')\n\nstars = int(input('How many stars? '))\nhorizontalLine(stars)\nverticalLine(stars)\ndiagonalLine(stars)\nrows = stars\ncolumns = int(input('How many columns? ')) * 2\nflag(rows, columns)",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Python Challenge: Sentence Exploder\nIt turns out that there are [some other helpful functions that you can use to manipulate strings](http://docs.python.org/2/library/string.html), beyond [format()](http://docs.python.org/2/library/string.html#string-formatting), which we have used extensively. Consider, for example, [split()](http://docs.python.org/2/library/string.html#string.split).\n\n<pre>>>> s = 'this is a long string'\n>>> s.split(' ')\n['this', 'is', 'a', 'long', 'string']</pre>\n\nIt seems that split() \"explodes\" the words in a string into a list of all the words in a string! (It did this because I told it to use ' ' \u2014 the space \u2014 as the separator. I could I have gotten bizarrely different results had I used, say, 's' as my separator. Try it!)\n\nCan you write a program that takes in any sentence the user gives you and prints it out vertically?\n\n<pre>Enter a sentence: I like wombats and aardvarks!\nI\nlike\nwombats\nand\naardvarks!</pre>\n\nCan you also find the last word in the sentence and print it first? (Hint, remember that every element of a list is automatically numbered with an index starting at zero\u2026 and it seems that the indices wrap-around \u2014 so if the last element of my list is index number 3, index 4 refers to the first element. And it wraps around in both directions\u2026)\n\n<pre>Enter a sentence: I like wombats and aardvarks!\naardvarks!\nI\nlike\nwombats\nand\naardvarks!</pre>"
},
{
"cell_type": "code",
"collapsed": false,
"input": "\"\"\"\nPython Challenge: Sentence Exploder\n\"\"\"\n\nsentence = input('''Please type a sentence.\n''')\nexplodedSentence = sentence.split(' ')\nprint('The last word in your sentence was \"{}\"'.format(explodedSentence[-1]))\nfor word in explodedSentence:\n print(word)",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "###Python Challenge: Eliza\nOne of the classic text-processing programs is a faux-therapist program named [ELIZA](http://en.wikipedia.org/wiki/ELIZA). Building on [Python Challenge: Sentence Exploder](https://stmarksschool.instructure.com/courses/15/assignments/1392) and [the annoying younger sibling simulator](https://stmarksschool.instructure.com/files/4909/download?verifier=SDgkMIiDM0eFeDzr3xD1STsbGEemGTAEg7Qein08), can you build a simple version of ELIZA?\n\nYou should ask for the user's name, then ask them how they're doing (or some similar question). From that point on, you should simply take the last word in whatever they say, and ask \"So, [name], how do you feel about [last word]?\", where you are simply taking the last word in whatever they tell you and asking them back about it. You should probably include the ability to quit this program as well (although control-C is a viable alternative initially). It might look something like this:\n\n<pre>Hello, what is your name?\nSeth\nHi Seth, what's your problem today?\nI'm sad because I have too much homework.\nSo, Seth, tell me how you feel about homework.\nIt makes me tired but I can't sleep at night!\nSo, Seth, tell me how you feel about night.\nIt's when I can't sleep because of my work.\nSo, Seth, tell me how you feel about work.</pre>\n\n\u2026and so forth. If you're feeling really fancy (like, extra credit fancy), you might explore the possibility of randomly switching up how you ask your question (or which word in the user's sentence you ask about) or whether you address the user by name. To accomplish this, you will need to import the random choice function:\n\n<pre>>>> from random import choice</pre>\n\nThis then lets you choose a random element of a list:\n\n<pre>>>> x = list(range(1,100))\n>>> print(choice(x))\n47</pre>"
},
{
"cell_type": "code",
"collapsed": false,
"input": "\"\"\"\nPython Challenge: Eliza (Alternate 1)\n\"\"\"\n\ndef chatInput(prompt):\n return input('''{}\n'''.format(prompt))\n\ndef question(name, lastResponse):\n wordList = lastResponse.split(' ')\n lastWord = wordList[-1]\n # select a response based on the length of the previous response\n if len(lastResponse) % 2 == 0:\n return chatInput('And how do you feel about {}, {}?'.format(lastWord, name))\n else:\n return chatInput('Why do you say that about {}?'.format(lastWord))\n\ndef eliza():\n name = chatInput('What\\'s your name?')\n response = chatInput('So, {}, why are you talking to me today?'.format(name))\n while response.lower() != 'good bye':\n response = question(name, response)\n print ('Good bye, {}.'.format(name))\n\neliza()",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": "\"\"\"\nPython Challenge: Eliza (Alternate 2)\n\"\"\"\n\nfrom random import choice\nquestions = ['And how do you feel about {lastWord}, {name}?',\n 'Why do you say that about {lastWord}, {name}?',\n '{name}, can you explain {lastWord} a bit more?',\n '{name}, tell me more about {lastWord}.']\n\ndef chatInput(prompt):\n return input('''{}\n'''.format(prompt))\n\ndef question(name, lastResponse):\n wordList = lastResponse.split(' ')\n lastWord = wordList[-1]\n intelligence = dict()\n intelligence['lastWord'] = lastWord\n intelligence['name'] = name\n # randomly choose a question from the list defined above\n return chatInput(choice(questions).format(**intelligence))\n\ndef eliza():\n name = chatInput('What\\'s your name?')\n response = chatInput('So, {}, why are you talking to me today?'.format(name))\n while response.lower() != 'good bye':\n response = question(name, response)\n print ('Good bye, {}.'.format(name))\n\neliza()\n",
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment