DOC PREVIEW
TAMU CSCE 110 - List comprehension in simulations
Type Lecture Note
Pages 4

This preview shows page 1 out of 4 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 4 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 4 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CSCE 110 1nd EditionLecture 17Outline of Last Lecture:I. Continuation on Properties of GraphsA. Formatting the axesB. Changing the type of graphOutline of Current Lecture:I. List comprehension in simulationsA. Simulation ExampleB. Example 2II. Input/Output with list comprehensionCurrent Lecture:I. List comprehension in writing programsA. Simulation ExampleThe following program will roll a die a specified number of times and will give back the user the faces seen, (in list form, as an integer, and as a visual representation). Typing the entire visual representation for each die face is an option, but below is a program that utilizes list comprehension to shorten the program. Explanations in italics are written below certain lines.1 import random2 def roll_dice(num_dice):3 dice = []This initializes the list that will keep track of which die faces were rolled.4 for i in range(num_dice):5 dice += [random.randint(1,6)]These two lines add a random die face (this is the main part of the simulation) to the list,however many times indicated by the user in line 24.6 return dice7 def make_die(value):8 top_bottom = '+-------+'9 left_one = '| * |'10 empty = '| |'11 center = '| * |'12 right_one = '| * |'13 two = '| * * |'14 three = '| * * * |'These notes represent a detailed interpretation of the professor’s lecture. GradeBuddy is best used as a supplement to your own notes, not as a substitute.In lines 8-14, we create a line for every section that could possibly be used for any face of a die.Later on, using list comprehension, we can join these different sections to make a full visual,vertically stacked representation of a die face. 15 face1 = [top_bottom, empty, center, empty, top_bottom]16 face2 = [top_bottom, left_one, empty, right_one, top_bottom]17 face3 = [top_bottom, left_one, center, right_one, top_bottom]18 face4 = [top_bottom, two, empty, two, top_bottom]19 face5 = [top_bottom, two, center, two, top_bottom]20 face6 = [top_bottom, three, empty, three, top_bottom] Lines 15-20 establish the necessary die sections (from lines 8-14) that are needed to create thewhole die face for each number rolled. We have not yet joined these sections, but we knowwhich sections are needed for each number. 21 die = ['', face1, face2, face3, face4, face5, face6] 22 print '\n'.join(die[value])Here, we are saying that we want to join each value that is in the list "die[value]", which is oneof the lists face1-6, with a new line. This means that every element of the list will be printed on anew line (in order). This will print out each section of the die face, creating a complete visualrepresentation of an entire die face corresponding to the number rolled.23 def main():24 num_dice = int(raw_input('Number of dice? '))25 random_dice = roll_dice(num_dice)26 print 'Random dice:', random_dice27 for i in random_dice:28 make_die(i) 29 main()B. Example 2Write a program that asks the user to enter a list of integers and then prints a histogram tothe screen. The integers are entered as a string separated with spaces. See example below.Example:Enter a string of positive integers separated by spaces : 1 3 20 5*****************************Our program will look like this:1 num = (raw_input("Enter a string of positive integers separated by spaces: ")).split(" ")2 print '\n'.join(int(i)*"*" for i in num)The split in line 1 automatically makes the variable "num" a list type, since it is storing multipleobjects. We then print separate lines for each value using '\n'.join, and this is for every integerin the list, which we then represent with asterisks. Because we have list comprehension, we cancompile most of the code into very few lines. In this case we only needed two. If we wanted, we could shorten this to only one line, but this is a little messy/confusing:1 print '\n'.join(int(i)*"*" for i in ((raw_input("Enter a string of positive integers separated byspaces: ")).split(" ")))II. Input/Output>>> Consider the following program.>>> fruits = [’cherry’, ’pecan’, ’apple’]>>> print [fruit + ’ pie’ for fruit in fruits] # Line A>>> vec = [2, 4, 6]>>> print [3*x for x in vec] # Line B>>> print [[x,x**2] for x in vec] # Line C>>> vec2 = [4, 3, -9]>>> print [x*y for x in vec for y in vec2] # Line Da) What output does Line A produce?>>> ['cherry pie', 'pecan pie', 'apple pie']Here, for every item in the list fruits, we added " pie" to the end. We can change the elements in the list like this because lists are mutable. b) What output does Line B produce?>>> [6, 12, 18]Here, for every item in the list vec, we multiplied the integer by 3. This is the same concept as inpart a. c) What output does Line C produce?>>> [[2, 4], [4, 16], [6, 36]]Here, for every item in the list vec, we completely replaced the lone integer with a list comprised of the original integer, followed by the original integer squared. This created three lists within one.d) What output does Line D produce?>>> [8, 6, -18, 16, 12, -36, 24, 18, -54]This one is a lot more complicated. The first three elements in this list are the first value in the list vec multiplied separately by each value in vec2, producing three different elements. Then, we move on the second value in vec, as we are doing this with each value in vec2 for each value in vec. We do the same for the last value in vec as well, creating a complete list with 9 different elements total. Let's look at line D again:>>> print [x*y for x in vec for y in vec2] # Line DWe can look at this as:>>> print [(x*y for x in vec) for y in vec2] # Line DThis means that we look first at the function in parentheses, and complete it, before looking at different values of y in vec2. This is why we multiply every value in vec by the first value in vec2 before moving on, and multiplying each value in vec by the second value in vec2, and so


View Full Document

TAMU CSCE 110 - List comprehension in simulations

Type: Lecture Note
Pages: 4
Documents in this Course
06-IO

06-IO

29 pages

21-OOP

21-OOP

8 pages

key

key

6 pages

21-OOP

21-OOP

8 pages

Load more
Download List comprehension in simulations
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view List comprehension in simulations and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view List comprehension in simulations 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?