联系方式

  • QQ:99515681
  • 邮箱:99515681@qq.com
  • 工作时间:8:00-21:00
  • 微信:codinghelp

您当前位置:首页 >> Python编程Python编程

日期:2021-01-14 10:34

Quiz #1: Review of Python, Python Data Types, and Iteration ICS-33 Winter 2021

When working on this quiz, recall the rules stated on the Academic Integrity statement that you signed. You

can download the q1helper project folder (available for Friday, on the Weekly Schedule link) in which to

write/test/debug your code. Submit your completed q1solution.py module online by Thursday, 11:30pm. I will

post my solutions to EEE reachable via the Solutions link on Saturday morning (after Problem #1 is due).

1. (5 pts) Draw a picture illustrating how Python executes the following code. Standard pictures show each

name above a square box that contains the tail of an arrow, whose head points to an object. An object is

shown as an oval (or rounded-corner square) labelled by the type of the object, whose inside shows its value

(which may contain more names, arrows/references: lists can include or omit index numbers). When you

change an existing reference, lightly cross out the old arrow and then draw the new one appropriately. Draw

the picture with no crossing arrows (practice on a whiteboard and move things around if necessary).

script module (execution starts here) m module (imported by script)

import m x = [1,2]

x = m.y y = [x[0],x[1]]

x.append(m.x)

m.y[1] = x

m.x[0] = m.y[1]

x[1][2][1] = 'a’

del m.y

script m

module module

Print only this page, answer problem #1 on it, and then submit it as a .pdf file by Friday

at 11:30pm on Gradescope.

2. (3+1 pts) Define the chooser function, which takes a sequence of arguments fs that are all predicates (one

parameter functions returning a bool) followed by two bool values: keep_when (specifying what value a

predicate must have to keep it – see details about keeping predicates below; its default is True) and except_as

(specifying what value to use for a predicate that raises an exception; its default is False). If called with no

predicates, chooser must raise the TypeError exception with an appropriate message. The chooser function

will store the tuple of parameter fs as a set (see details of how this set is manipulated below) and returns a

reference to a function object defined inside it: name this internal function sieve, which takes one argument

(name its parameter x) on which some predicates will be called.

When the returned function is called, it recomputes and returns the set of fs to include only those currently

in fs that evaluate to keep_when when called on x. The fs set can shrink every time the returned function is

called. For example, executing (note except_53 returns True, but raises ValueError for an argument of 53)

demo = chooser (is_even, is_prime, endsin_3, except_53, keep_when = True, except_as = False)

and then calling demo(53) returns {<function is_prime at 0x0...>, <function ends_3 at 0x0...>},

because the is_even and except_53 predicates return False for the argument 53 (technically except_53

raises a ValueError exception, which is treated like returning False because of except_as); calling demo(7)

returns {<function is_prime at 0x0...>}, because the endsin_3 functions return False for the argument

7. The current fs set contains all function objects that have returned keep_when on all calls to demo.

For the last point of credit, determine how chooser‘s returned function object can store an attribute named

arg_history, which stores a list of 2-tuples, one for every time chooser‘s returned function object is called.

The first index in the 2-tuple is the argument of the call and the second index is the remaining predicates that

were removed because they returned the opposite of keep_when (in the example above, False) when called on

this argument. For the example above, after the two call to demos then demo.arg_history is [(53, {<function

is_even at 0x0...>, <function except_53 at 0x0...>}), (7, {<function ends_3 at 0x0...>})].

Hints: use rebinding with a nonlocal declaration; function objects can store attributes, but they must be setup

and manipulated carefully. Also write a local helper function that is passed a predicate and its argument and

returns either the value of calling the predicate on the argument or except_as (if the call raises any exception).

3-4. (16 pts) A stock trading company stores a database that is a dictionary (dict) whose keys are client

names (str); associated with each client name is a list of 3-tuples representing the transaction history

of that client: in the 3-tuple, the first index is a stock name (str), the second index is the number of shares

traded for that transaction (int: positive means buying shares; negative means selling shares), and the third

index is the price per share in dollars (int for simplicity) for that transaction. The list shows the order in

which the transactions occurred. A simple/small database can look like

{

'Carl': [('Intel',30,40), ('Dell', 20,50), ('Intel',-10,60), ('Apple', 20,55)],

'Barb': [('Intel',20,40), ('Intel',-10,45), ('IBM', 40,30), ('Intel',-10,35)],

'Alan': [('Intel',20,10), ('Dell', 10,50), ('Apple', 80,80), ('Dell', -10,55)],

'Dawn': [('Apple',40,80), ('Apple', 40,85), ('Apple',-40,90)]

}

Define the following functions. For full credit, all functions in part 3 only require their bodies to contain

exactly one statement: just a return statement; long return statements can be written over multiple lines

by using the \ character: so, the requirement is one statement, not one line. Hint: write these functions using

multiple statements first to get partial credit (all but 1 point), then if you can, transform that code into a single

statement using combinations of comprehensions (sometime with multiple loops) and calls to sorted, to get

full credit. No function should alter its argument.

?Use sequence unpacking (use _ for unneeded names); avoid indexing tuples anywhere but in a key lambda.

? In the notes, see how multiple statements can be rewritten as an equivalent statement comprehension.

? Sometimes use two loops in one comprehension. Complicated problems might require multiple

comprehensions each with its own loop.

? For sorting problems, sometimes build the thing that must be sorted using a comprehension and call sorted

on it, figuring out a key function; sometimes, sort something and then use the result in a comprehension to

build what needs to be returned.

3a. (2 pts) The stocks function takes a database (dict) as an argument and returns a set: all stock names

traded. E.g., if db is the database above, calling stocks(db) returns {'Dell', 'Apple', 'Intel', 'IBM'}.

3b. (2 pts) The clients_by_volume function takes a database (dict) as an argument and returns a list: client

names (str) in decreasing order of their volume of trades (the sum of the number of shares they traded); if two

clients have the same volume, they must appear in increasing alphabetical order. Important: selling 15 shares

(appearing as -15 shares) counts as 15 shares traded: add up the absolute values of the number of shares traded.

E.g., if db is the database above, calling clients_by_volume(db) returns ['Alan', 'Dawn', 'Barb',

'Carl']. Alan and Dawn each have a volume of 120 shares (they appear first in increasing alphabetical

order); Barb and Carl each have a volume of 80 shares (they appear next in increasing alphabetical order).

3c. (4 pts) The stocks_by_volume function takes a database (dict) as an argument and returns a list: 2-

tuples of stock names (str) followed its volume (shares of that stock name traded among all clients) in

decreasing order of volume; if two stocks have the same volume, they must appear in increasing alphabetical

order. For example, if db is the database above, calling stocks_by_volume(db) returns [('Apple',220),

('Intel',100), ('Dell',40), ('IBM',40)]. Dell and IBM each had a volume of 40 shares (they appear

last in increasing alphabetical order). Hint: you can use/call the stocks function you wrote in part 3a here.

4a. (2 pts) Define the by_stock function, which takes a database (dict) as an argument; it returns a dictionary

(dict or defaultdict) associating a stock name with an inner dictionary (dict or defaultdict) of all the

clients (str) as keys associated with their trades for that stock (a list of 2-tuples of int). E.g., if db is the

database above, calling by_stock(db) returns a dictionary whose contents are

{

'Intel': {'Carl': [(30,40), (-10,60)], 'Barb': [(20,40), (-10,45), (-10,35)], 'Alan': [(20,10)]},

'Dell': {'Carl': [(20,50)], 'Alan': [(10,50), (-10, 55)]},

'Apple': {'Carl': [(20,55)], 'Alan': [(80,80)], 'Dawn': [(40,80), (40,85), (-40,90)]},

'IBM': {'Barb': [(40,30)]}

}

4b. (2 pts) Define the summary function, which takes as arguments a database (dict) and a dict of current

stock prices. It returns a dictionary (dict or defaultdict) whose keys are client names (str) whose

associated values are 2-tuples: the first index is a dictionary (dict or defaultdict) whose keys are stock

names (str) and values are the number of shares (int) the client owns. The second index is the amount

of money (int) the portfolio is worth (the sum of the number of shares of each stock multiplied by its

current price). Assume each client starts with no shares of any stocks, and if a client owns 0 shares of a

stock, the stock should not appear in the client’s dictionary. Recall positive numbers are a purchase of the

stock and negative numbers a sale of the stock. E.g., if db is the database above, calling summary(db,

{'IBM':65, 'Intel':60, 'Dell':55, 'Apple':70}) would return

{

'Carl': ({'Intel': 20, 'Dell': 20, 'Apple': 20}, 3700),

'Barb': ({'IBM': 40}, 2600),

'Alan': ({'Intel': 20, 'Apple': 80}, 6800),

'Dawn': ({'Apple': 40}, 2800)

}


版权所有:编程辅导网 2021 All Rights Reserved 联系方式:QQ:99515681 微信:codinghelp 电子信箱:99515681@qq.com
免责声明:本站部分内容从网络整理而来,只供参考!如有版权问题可联系本站删除。 站长地图

python代写
微信客服:codinghelp