PyShop Session 1

Exercises


These exercises are meant to help you to get to know the standard Python data types, their methods, and some useful built-in functions. Keep in mind that there are always many ways to solve these problems, but I encourage you to do so WITHOUT IMPORTING ANYTHING! That will help you to familiarize yourself with the native functionality.

The questions are in increasing difficulty, where the first question should take you less than a minute and the last one you might not be able to figure out. Good luck!

Note: I appologize for the solutions and questions not being next to each other, but there is a numbering issue in the Markdown that generates this text. Sorry, but it is a known bug that has yet to be fixed!

Lists

  1. Go have a look at the Python documentation regarding lists here: https://docs.python.org/3/tutorial/datastructures.html. Once you've done that, define an empty list, called x and a list containing the numbers 1 through 100, called y. Finally, print your variables using a single line of code.

  2. Loop over your list y and fill x with the indices of y for all of the entries that are even. That is, if y[5] is even, add the index 5 to x. Again, print x and check your work. BONUS: Use a boolean test to check whether all of the elements of y indexed by the entries of x are even.

  3. Difficult. For all of the odd numbers between zero and 100 (N = 1, 3, ... 99), generate a list containing all of the integers less than N. Do this in one line using your two lists x and y. Your results should be contained in a list of lists, call it z. Use a slice and print only part of z to see if how you did.

Strings

  1. Read in the 'jabberwocky.txt' file accompanying these exercises to a single string.

  2. Compare the "raw string" and the output from print. What is the difference?

  3. Use built in methods to split the poem into lines, delineated by a unicode line break marker. What is still a problem with these strings? How is their formatting different? What characters are still a problem?

  4. Use built in methods to 'strip' (hint, hint!) the leading white space from the lines. Bonus points if you do it in a single line.

  5. Remove all punctuation, replace the remaining unicode markers for appostrophes with appostrophes, remove those corresponding to quotes, and convert the text to lower-case.

  6. Split the poem into words, ending up with a list of words. That means your list should be one dimensional!

  7. Finally, write a small script that takes input from the user and generates a random poem from the words in Jabberwocky! My inputs are simply the number of words, but you can be as creative as you want!