COSI 2a Lecture Notes - Lecture 8: List Comprehension

48 views2 pages

Document Summary

Write a function, square_list(n), which returns the list of squares of numbers from 1 through n. The easiest way is to use a list comprehension. For example, squares(4) --> [1,4,9,16] squares(2) --> [1,4] Solution: def squares_list(n): squares=[x*x for x in range(1,n+1)] return(squares) Hint: use a list comprehension to generate the list l of all tuples that add up to n, and then return len(l). Also, you might first want to just have it return l to see if your list_comprehension is working correctly! Solution: def three_dice(n): vals=[(x,y,z) for x in range(1,7) for y in range(1,7) for z in range(1,7) if x+y+z==n] return len(vals) Write a function, pos_vals(vals), which accepts a list of numbers and returns the sublist of positive numbers, e. g. pos_vals([4,-2,-1,3,-5,6]) --> [4,3,6] pos_vals([-1,0,-7,0,-3]) --> [] pos_vals([8,2,0,6,4]) --> [8,2,6,4] Solution: def pos_vals(vals): val=[(x) for x in vals if x>0] return val.

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents