CSCE 110 1nd EditionLecture 15Outline of Last Lecture:I. Graphing data from a .csv fileA. Getting the dataB. Creation of the graphOutline of Current Lecture:I. List ComprehensionA. BasicsB. Making programs shorterCurrent Lecture:I. List comprehensionA. List comprehension allows us to greatly shorten the length of our code. There are four different user-defined functions in the program below, but they all do the same thing, which is create a pyramid of a size and symbol given by the user. We should be familiar with the first three functions. The fourth function has a new concept introduced, and we notice that it is only two lines long. See the examples and explanations below of some new concepts:>>> x = ['p', 'y', 't', 'h', 'o', 'n'] >>> print 'X'.join(x)>>> pXyXtXhXoXnTo insert a symbol between each element of a list, we write 'symbol'.join(listname).>>> x = ['a', 'b', 'c', 'd', 'e'] >>> print '\n'.join(x)>>> a>>> b>>> c>>> d>>> e"\n" signifies the start of a new line. We combined this with the use of the .join(). >>> x = [i for i in range (1, 10)]>>> x>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]1 def pyramid(size, symbol):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.2 space = size / 23 i = 14 while i <= size:5 print ' ' * space + symbol * i6 space -= 17 i += 2 8 def pyramid2(size, symbol):9 space = size / 210 for i in range(1, size+1, 2): 11 print ' ' * space + symbol * i12 space -= 113 def pyramid3(size, symbol):14 for i in range(1, size+1, 2): 15 print ' ' * ((size - i)/2) + symbol * i16 def pyramid4(size, symbol):17 print '\n'.join([' ' * ((size - i)/2) + symbol * i for i in range(1, size+1, 2)])18 def main():19 symbol = raw_input('Enter symbol: ')20 size = int(raw_input('Size: '))21 pyramid4(size, symbol)22 main() Notice that each function is shorter than the last. Lines 13-15 seem like a good place to stop, but we can actually make a function with the same purpose that's even shorter! We use list comprehension (the joining with the '\n' and the "for i" operation that serves to replace the necessity of a for loop) to shorten the code as much as
View Full Document