Coursera Python Data Structures Solutions

Master Python’s data structures with solutions to problems from your Coursera course “Python Data Structures”. Learn how to use lists, dictionaries, and tuples to conquer complex data analysis tasks. This blog post provides solutions and explanations to help you solidify your understanding of Python’s fundamental building blocks for data organization.

About the course “Python Data Structures by University of Michigan”

  • Master Python’s data structures: Learn lists, dictionaries, and tuples, the fundamental building blocks for organizing data in Python.
  • Move beyond the basics: Explore how these data structures power complex data analysis tasks.
  • Hands-on practice: This course will guide you through exercises that leverage Python’s built-in data structures for data manipulation.
Coursera Python Data Structures Solutions
Python Data Structures – Coursera

There are seven modules in the course “Python Data Structures”

  1. Chapter Six: Strings
  2. Unit: Installing and Using Python
  3. Chapter Seven: Files
  4. Chapter Eight: Lists
  5. Chapter Nine: Dictionaries
  6. Chapter Ten: Tuples
  7. Graduation

Week 1 – Python Data Structures

Week 1 Quiz: Python Data Structures

1. What does the following Python Program print out?

str1 = "Hello";
str2 = 'there';
bob = str1 + str2;
print bob

Answer – Hellothere

2. What does the following Python program print out?

x = '40';
y = int(x) + 2;
print y

Answer – 42

3. How would you use the index operator [] to print out the letter q from the following string?

x = 'From [email protected]'

Answer – print(x[8])

4. How would you use string slicing [:] to print out ‘uct’ from the following string?

x = 'From [email protected]'

Answer – print(x[14:17])

5. What is the iteration variable in the following Python code?

for letter in 'banana' : 
    print letter

Answer – letter

6. What does the following Python code print out?

print len('banana')*7

Answer – 42

7. How would you print out the following variable in all upper case in Python?

greet = 'Hello Bob'

Answer – print(greet.upper())

8. Which of the following is not a valid string method in Python?

Answer – shout()

9. What will the following Python code print out?

data = 'From [email protected] Sat Jan 5 09:14:16 2008';
pos = data.find('.');
print(data[pos:pos+3])

Answer – .ma

10. Which of the following string methods removes whitespace from both the beginning and end of a string?

Answer – strip()

Week 1 Assignments:

Assignment 6.5 Code:

text = "X-DSPAM-Confidence:    0.8475";
pos=text.find(':')
value=text[pos+1:]
print(float(value))

Week 2 – Python Data Structures

No quizzes or assignments

Week 3 – Python Data Structures

Week 3 Quiz: Python Data Structures

1. Given the architecture and terminology we introduced in Chapter 1, where are files stored?

Answer – Secondary memory

2. What is stored in a “file handle” that is returned from a successful open() call?

Answer – The handle is a connection to the file’s data

3. What do we use the second parameter of the open() call to indicate?

Answer – Whether we want to read data from the file or write data to the file

4. What Python function would you use if you wanted to prompt the user for a file name to open?

Answer – input()

5. What is the purpose of the newline character in text files?

Answer – It indicates the end of one line of text and the beginning of another line of text

6. If we open a file as follows: xfile = open(‘mbox.txt’). What statement would we use to read the file one line at a time?

Answer – for line in xfile:

7. What is the purpose of the following Python code?

fhand = open('mbox.txt');
x = 0;
for line in fhand:
    x = x + 1;
    print x

Answer – Count the lines in the file ‘mbox.txt’

8. If you write a Python program to read a text file and you see extra blank lines in the output that are not present in the file input as shown below, what Python string function will likely solve the problem?

From: [email protected];
From: [email protected];
From: [email protected];
From: [email protected]

Answer – strip()

9. The following code sequence fails with a traceback when the user enters a file that does not exist. How would you avoid the traceback and make it so you could print out your own error message when a bad file name was entered?

fname = raw_input('Enter the file name: ');
fhand = open(fname)

Answer – try / except

10. What does the following Python code do?

fhand = open('mbox-short.txt');
inp = fhand.read()

Answer – Reads the entire file into the variable inp as a string

Week 3 Assignments:

Assignment 7.1 code:

# Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
for line in fh.readlines():
    print(line.upper().strip())

Assignment 7.2 code:

# Use the file name mbox-short.txt as the file name
total=0
count=0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : 
    	continue
    count=count+1
    pos=line.find(':')
    value=line[pos+1:]
    total=total+float(value)
    avg=total/count
print("Average spam confidence:",avg)

#Output:
#Average spam confidence: 0.750718518519

Week 4 – Python Data Structures

Week 4 Quiz: Python Data Structures

1. How are “collection” variables different from normal variables?

Answer – Collection variables can store multiple values in a single variable

2. What are the Python keywords used to construct a loop to iterate through a list?

Answer – for/in

3. For the following list, how would you print out ‘Sally’? friends = [ ‘Joseph’, ‘Glenn’, ‘Sally’]

Answer – print(friends[2])

4. fruit = ‘Banana’ fruit[0] = ‘b’; print(fruit)

Answer – Nothing would print the program fails with a traceback

5. Which of the following Python statements would print out the length of a list stored in the variable data?

Answer – print(len(data))

6. What type of data is produced when you call the range() function? x = range(5)

Answer – A list of integers

7. What does the following Python code print out? a = [1, 2, 3]; b = [4, 5, 6]; c = a + b; print len(c)

Answer – 6

8. Which of the following slicing operations will produce the list [12, 3]? t = [9, 41, 12, 3, 74, 15]

Answer – t[2:4]

9. What list method adds a new item to the end of an existing list?

Answer – append()

10. What will the following Python code print out? friends = [ ‘Joseph’, ‘Glenn’, ‘Sally’ ]; friends.sort(); print(friends[0])

Answer – Glenn

Week 4 Assignments:

Assignment 8.4 code:

#file used is romeo.txt
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    for i in line.split():
        if not i in lst:
            lst.append(i)
lst.sort()
print(lst)

#Output
#['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

Assignment 8.5 code:

fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fhand = open(fname)
count = 0
for line in fhand:
    line.rstrip()
    if line.startswith("From "):
        words = line.split()
        print(words[1])
        count += 1
print("There were",count, "lines in the file with From as the first word")

Week 5 – Python Data Structures

Week 5 Quiz: Python Data Structures

1. How are Python dictionaries different from Python lists?

Answer – Python lists maintain order and dictionaries do not maintain order

2. What is a term commonly used to describe the Python dictionary feature in other programming languages?

Answer – Associative arrays

3 What would the following Python code print out? stuff = dict(); print(stuff[‘candy’])

Answer – The program would fail with a traceback

4 What would the following Python code print out? stuff = dict(); print(stuff.get(‘candy’,-1))

Answer – -1

5. (T/F) When you add items to a dictionary they remain in the order in which you added them.

Answer – False

6. What is a common use of Python dictionaries in a program?

Answer – Building a histogram counting the occurrences of various strings in a file

7. Which of the following lines of Python is equivalent to the following sequence of statements assuming that counts is a dictionary? if key in counts: counts[key] = counts[key] + 1 else: counts[key] = 1

Answer – counts[key] = counts.get(key,0) + 1

8. In the following Python, what does the for loop iterate through? x = dict() … for y in x : …

Answer – It loops through the keys in the dictionary

9. Which method in a dictionary object gives you a list of the values in the dictionary?

Answer – values()

10. What is the purpose of the second parameter of the get() method for Python dictionaries?

Answer – To provide a default value if the key is not found

Week 5 Assignments:

Assignment 9.4 code:

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

count = dict()
for line in handle:
    if not line.startswith("From "):continue
    line = line.split()
    line = line[1]
    count[line] = count.get(line, 0) +1

bigcount = None
bigword = None
for k,v in count.items():
    if bigcount == None or v > bigcount:
        bigword = k
        bigcount = v 
print(bigword, bigcount)

#Output : [email protected] 5

Week 6 – Python Data Structures

Week 6 Quiz: Python Data Structures

1. What is the difference between a Python tuple and Python list?

Answer – Lists are mutable and tuples are not mutable

2. Which of the following methods work both in Python lists and Python tuples?

Answer – index()

3. What will end up in the variable y after this code is executed? x , y = 3, 4

Answer – 4

4. In the following Python code, what will end up in the variable y? x = { ‘chuck’ : 1 , ‘fred’ : 42, ‘jan’: 100}; y = x.items()

Answer – A list of tuples

5. Which of the following tuples is greater than x in the following Python sequence? x = (5, 1, 3); if ??? > x : …

Answer – (6, 0, 0)

6. What does the following Python code accomplish, assuming the c is a non-empty dictionary? tmp = list(); for k, v in c.items(): tmp.append( (v, k))

Answer – It creates a list of tuples where each tuple is a value, key pair

7. If the variable data is a Python list, how do we sort it in reverse order?

Answer – data.sort(reverse=True)

8. Using the following tuple, how would you print ‘Wed’? days = (‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’, ‘Sun’)

Answer – print(days[2])

9. In the following Python loop, why are there two iteration variables (k and v)? c = {‘a’:10, ‘b’:1, ‘c’:22}; for k, v in c.items() : …

Answer – Because the items() method in dictionaries returns a list of tuples

10. Given that Python lists and Python tuples are quite similar – when might you prefer to use a tuple over a list?

Answer – For a temporary variable that you will use and discard without modifying

Week 6 Assignment:

Assignment 10.2 code:

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
lst=list()
di=dict()
for line in handle:
    if line.startswith("From "):
    	pos=line.find(":")
    	lst.append(line[pos-2:pos])
for word in lst:
    di[word]=di.get(word,0)+1
newlst=list()
for key,val in di.items():
    newtup=(key,val)
    newlst.append(newtup)
newlst=sorted(newlst)
for key,val in newlst:
    print(key,val)

Week 7 – Python Data Structures

No quizzes or assignments.

You may like:

How to Become a Full-Stack Web Developer: A Step-by-Step Guide
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments