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!
Go have a look at the Python documentation regarding lists here . 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.
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. Hint: Take a look at the built in function "enumerate()". BONUS: Use a boolean test to check whether all of the elements of y indexed by the entries of x are even.
For all of the odd numbers between zero and 100 (N = 1, 3, ... 99), generate a new 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 how you did.
Read in the 'jabberwocky.txt' file accompanying these exercises to a single string.
Compare the raw string and the output from print. What is the difference?
Use built in methods to split the poem into lines using the '\n' line break marker. What is still a problem with these strings? How is their formatting different? What characters are still a problem?
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.
Remove all punctuation, replace the remaining unicode markers for appostrophes with actual appostrophes, remove those corresponding to quotes, and convert the text to lower-case.
Split the poem into words, ending up with a list of words. That means your list should be one dimensional! Check this by running len(words). Is the result a single number or several?
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!
In [2]:
x = []
y = [i for i in range(1,101)]
print(x,y)
In [4]:
for index, item in enumerate(y):
if item%2 == 0: x.append(index)
print(x)
#BONUS!
print(any([y[i]%2 == 1 for i in x]))
#Just to show you that this worked, change one entry in x
x[0] = 0
print(any([y[i]%2 == 1 for i in x]))
#Let's change x back so we don't have more problems:
x[0] = 1
In [5]:
z = [i for i in [y[:I] for I in x]]
print(z[:3])
In [8]:
f = open('jabberwocky.txt')
poem = f.read()
print(poem)
poem
Out[8]:
Notice that the raw string contains the line seperators, tab markers, etc., while print processes these and prints the desired styling. This is an important point, as if your raw strings contain these characters (the \ is the break character in Python) you will have errors.
In [9]:
lines = poem.split('\n')
lines
Out[9]:
You'll now notice that some of the strings contain leading white space that could be a problem for some algorithms or programs. Also, the quotation marks and appostrophes are still marked with their unicode markers.
In [10]:
lines = [line.lstrip() for line in lines]
lines
Out[10]:
In [24]:
#NOTE: I've shown two ways to do this here. I understand there are packages that make
#this much more efficient, but I'm seeking to make this set of exercises solely built in python.
lines = ["".join(c for c in line if c not in (':', '.', '!', ';', '?')) for line in lines]
lines = [line for line in lines if not line == '']
lines = [line.replace('\xe2\x80\x9c', r"") for line in lines]
lines = [line.replace('\xe2\x80\x94', r"") for line in lines]
lines = [line.replace('\xe2\x80\x99', r"'") for line in lines]
lines = [line.replace('\xe2\x80\x9d', r"") for line in lines]
lines = [line.lower() for line in lines]
lines
Out[24]:
This solution worked in Python 2, but in Python 3 I can't get the " out. If you can, good on you!
In [12]:
words = [word for line in lines for word in line.split()]
words
Out[12]:
In [20]:
import random
print("So, you think Jabberwocky is ridiculous? I bet I can do one better!")
print("How long should my poem be? (be nice and put in an integer) ")
number_of_words = int(input())
#Generate a string of random numbers, implying indices
ind = [random.randint(0, len(words) - 1) for i in range(0, number_of_words)]
#Generate a list of random numbers to represent words per line
words_per_line = [random.randint(0, 10) for i in range(number_of_words)]
#Create the lines of the poem in a loop
line = 0
k = 0
crazy_poem_lines = ['']
for i in ind:
crazy_poem_lines[line] += words[i] + " "
k += 1
if k >= words_per_line[line]:
k = 0
line += 1
crazy_poem_lines.append('')
#When done, strip the trailing white space and add line breaks
crazy_poem_lines = [line.rstrip() for line in crazy_poem_lines]
crazy_poem_lines = [line + '\n ' for line in crazy_poem_lines]
#Finally, create a single poem
crazy_poem = "\n Here's a crazier poem: \n\n"
for line in crazy_poem_lines:
crazy_poem += line
print(crazy_poem)
In [ ]:
len(words)