Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

1. Please write the following Python 3 program. Please also show all output. list, set and dict comprehensions List comprehensions Note: this is a bit

1. Please write the following Python 3 program. Please also show all output.

list, set and dict comprehensions

List comprehensions

Note: this is a bit of a backwards exercise we show you code, you figure out what it does.

As a result, not much to submit dont worry about it youll have a chance to use these in other exercises.

>>> feast = ['lambs', 'sloths', 'orangutans', 'breakfast cereals', 'fruit bats'] >>> comprehension = [delicacy.capitalize() for delicacy in feast] 

What is the output of:

>>> comprehension[0] ??? >>> comprehension[2] ??? 

(figure it out before you try it)

Filtering lists with list comprehensions

>>> feast = ['spam', 'sloths', 'orangutans', 'breakfast cereals', 'fruit bats'] >>> comp = [delicacy for delicacy in feast if len(delicacy) > 6] 

What is the output of:

>>> len(feast) ??? >>> len(comp) ??? 

(figure it out first!)

Unpacking tuples in list comprehensions

>>> list_of_tuples = [(1, 'lumberjack'), (2, 'inquisition'), (4, 'spam')] >>> comprehension = [ skit * number for number, skit in list_of_tuples ] 

What is the output of:

>>> comprehension[0] ??? >>> len(comprehension[2]) ??? 

Double list comprehensions

>>> eggs = ['poached egg', 'fried egg'] >>> meats = ['lite spam', 'ham spam', 'fried spam'] >>> comprehension = \ [ '{0} and {1}'.format(egg, meat) for egg in eggs for meat in meats] 

What is the output of:

>>> len(comprehension) ??? >>> comprehension[0] ??? 

Set comprehensions

>>> comprehension = { x for x in 'aabbbcccc'} 

What is the output of:

>>> comprehension ??? 

Dictionary comprehensions

>>> dict_of_weapons = {'first': 'fear', 'second': 'surprise', 'third':'ruthless efficiency', 'forth':'fanatical devotion', 'fifth': None} >>> dict_comprehension = \ { k.upper(): weapon for k, weapon in dict_of_weapons.items() if weapon} 

What is the output of:

>>> 'first' in dict_comprehension ??? >>> 'FIRST' in dict_comprehension ??? >>> len(dict_of_weapons) ??? >>> len(dict_comprehension) ??? 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

=+ What would it look like? Who should deliver it?

Answered: 1 week ago