update from Atlas

This commit is contained in:
Luciano Ramalho 2014-12-30 15:53:07 -02:00
parent 691113636f
commit 174e952b2c
14 changed files with 426 additions and 10 deletions

View File

@ -211,8 +211,8 @@ class Vector:
return self._components[pos]
msg = '{.__name__!r} object has no attribute {!r}' # <5>
raise AttributeError(msg.format(cls, name))
# END VECTOR_V3_GETATTR
# BEGIN VECTOR_V3_SETATTR
def __setattr__(self, name, value):
cls = type(self)

View File

@ -0,0 +1,37 @@
"""
A line item for a bulk food order has description, weight and price fields.
A ``subtotal`` method gives the total price for that line item::
>>> raisins = LineItem('Golden raisins', 10, 6.95)
>>> raisins.weight, raisins.description, raisins.price
(10, 'Golden raisins', 6.95)
>>> raisins.subtotal()
69.5
But, without validation, these public attributes can cause trouble::
# BEGIN LINEITEM_PROBLEM_V1
>>> raisins = LineItem('Golden raisins', 10, 6.95)
>>> raisins.subtotal()
69.5
>>> raisins.weight = -20
>>> raisins.subtotal()
-139.0
# END LINEITEM_PROBLEM_V1
"""
# BEGIN LINEITEM_V1
class LineItem:
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
# END LINEITEM_V1

View File

@ -0,0 +1,63 @@
"""
A line item for a bulk food order has description, weight and price fields::
>>> raisins = LineItem('Golden raisins', 10, 6.95)
>>> raisins.weight, raisins.description, raisins.price
(10, 'Golden raisins', 6.95)
A ``subtotal`` method gives the total price for that line item::
>>> raisins.subtotal()
69.5
The weight of a ``LineItem`` must be greater than 0::
>>> raisins.weight = -20
Traceback (most recent call last):
...
ValueError: value must be > 0
No change was made::
>>> raisins.weight
10
The check is also performed on instantiation::
>>> walnuts = LineItem('walnuts', 0, 10.00)
Traceback (most recent call last):
...
ValueError: value must be > 0
The proteced attribute can still be accessed if needed for some reason, such as
white box testing)::
>>> raisins._LineItem__weight
10
"""
# BEGIN LINEITEM_V2
class LineItem:
def __init__(self, description, weight, price):
self.description = description
self.weight = weight # <1>
self.price = price
def subtotal(self):
return self.weight * self.price
@property # <2>
def weight(self): # <3>
return self.__weight # <4>
@weight.setter # <5>
def weight(self, value):
if value > 0:
self.__weight = value # <6>
else:
raise ValueError('value must be > 0') # <7>
# END LINEITEM_V2

View File

@ -0,0 +1,60 @@
"""
A line item for a bulk food order has description, weight and price fields::
>>> raisins = LineItem('Golden raisins', 10, 6.95)
>>> raisins.weight, raisins.description, raisins.price
(10, 'Golden raisins', 6.95)
A ``subtotal`` method gives the total price for that line item::
>>> raisins.subtotal()
69.5
The weight of a ``LineItem`` must be greater than 0::
>>> raisins.weight = -20
Traceback (most recent call last):
...
ValueError: value must be > 0
Negative or 0 price is not acceptable either::
>>> truffle = LineItem('White truffle', 100, 0)
Traceback (most recent call last):
...
ValueError: value must be > 0
No change was made::
>>> raisins.weight
10
"""
# BEGIN LINEITEM_V3
class Quantity: # <1>
def __init__(self, storage_name):
self.storage_name = storage_name # <2>
def __set__(self, instance, value): # <3>
if value > 0:
instance.__dict__[self.storage_name] = value # <4>
else:
raise ValueError('value must be > 0')
class LineItem:
weight = Quantity('weight') # <5>
price = Quantity('price') # <6>
def __init__(self, description, weight, price): # <7>
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
# END LINEITEM_V3

View File

@ -0,0 +1,59 @@
"""
WARNING: Broken implementation for demonstration purposes.
A line item for a bulk food order has description, weight and price fields::
>>> raisins = LineItem('Golden raisins', 10, 6.95)
>>> raisins.weight, raisins.description, raisins.price
(10, 'Golden raisins', 6.95)
A ``subtotal`` method gives the total price for that line item::
>>> raisins.subtotal()
69.5
The weight of a ``LineItem`` must be greater than 0::
>>> raisins.weight = -20
Traceback (most recent call last):
...
ValueError: value must be > 0
Negative or 0 price is not acceptable either::
>>> truffle = LineItem('White truffle', 100, 0)
Traceback (most recent call last):
...
ValueError: value must be > 0
No change was made::
>>> raisins.weight
10
"""
class Quantity:
def __init__(self, storage_name):
self.storage_name = storage_name
def __set__(self, instance, value):
if value > 0:
instance.__dict__[self.storage_name] = value
else:
raise ValueError('value must be > 0')
class LineItem:
weight = Quantity('weight')
price = Quantity('weight') # <-- this is the bug discussed in the book
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price

View File

@ -0,0 +1,74 @@
"""
A line item for a bulk food order has description, weight and price fields::
>>> raisins = LineItem('Golden raisins', 10, 6.95)
>>> raisins.weight, raisins.description, raisins.price
(10, 'Golden raisins', 6.95)
A ``subtotal`` method gives the total price for that line item::
>>> raisins.subtotal()
69.5
The weight of a ``LineItem`` must be greater than 0::
>>> raisins.weight = -20
Traceback (most recent call last):
...
ValueError: value must be > 0
No change was made::
>>> raisins.weight
10
The value of the attributes managed by the descriptors are stored in
alternate attributes, created by the descriptors in each ``LineItem``
instance::
>>> raisins = LineItem('Golden raisins', 10, 6.95)
>>> dir(raisins) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
['_Quantity_0', '_Quantity_1', '__class__', ...
'description', 'price', 'subtotal', 'weight']
>>> raisins._Quantity_0
10
>>> raisins._Quantity_1
6.95
"""
# BEGIN LINEITEM_V4
class Quantity:
__counter = 0 # <1>
def __init__(self):
cls = self.__class__ # <2>
prefix = cls.__name__ # <3>
index = cls.__counter # <4>
self.storage_name = '_{}_{}'.format(prefix, index) # <5>
cls.__counter += 1 # <6>
def __get__(self, instance, owner): # <7>
return getattr(instance, self.storage_name) # <8>
def __set__(self, instance, value): # <9>
if value > 0:
setattr(instance, self.storage_name, value) # <10>
else:
raise ValueError('value must be > 0')
class LineItem:
weight = Quantity() # <11>
price = Quantity()
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
# END LINEITEM_V4

View File

@ -6,7 +6,7 @@ __ http://code.activestate.com/recipes/355045-spreadsheet/
Demonstration::
>>> from math import sin, pi
>>> ss = Spreadsheet(sin=sin, pi=pi, abs=abs)
>>> ss = Spreadsheet(sin=sin, pi=pi)
>>> ss['a1'] = '-5'
>>> ss['a2'] = 'a1*6'
>>> ss['a3'] = 'a2*7'
@ -20,11 +20,6 @@ Demonstration::
>>> ss['c1'] = 'abs(a2)'
>>> ss['c1']
30
>>> ss['c2'] = 'len(a2)'
>>> ss['c2']
Traceback (most recent call last):
...
NameError: name 'len' is not defined
>>> ss['d1'] = '3*'
>>> ss['d1']
Traceback (most recent call last):
@ -37,8 +32,7 @@ class Spreadsheet:
def __init__(self, **tools):
self._cells = {}
self._tools = {'__builtins__' : {}}
self._tools.update(tools)
self._tools = tools
def __setitem__(self, key, formula):
self._cells[key] = formula

View File

@ -0,0 +1,49 @@
import java.math.BigInteger;
class CorrectFactorial {
static final BigInteger two = new BigInteger("2");
public static BigInteger factorial(BigInteger n) {
return n.compareTo(two) < 0 ? BigInteger.ONE
: n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
public static void main(String args[]) {
BigInteger upperBound = new BigInteger("25");
for (BigInteger i = BigInteger.ONE;
i.compareTo(upperBound) <= 0;
i = i.add(BigInteger.ONE)) {
System.out.println(i + "! = " + factorial(i));
}
}
}
/* output:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = 51090942171709440000
22! = 1124000727777607680000
23! = 25852016738884976640000
24! = 620448401733239439360000
25! = 15511210043330985984000000
*/

View File

@ -0,0 +1,43 @@
class SimpleFactorial {
public static long factorial(long n) {
return n < 2 ? 1 : n * factorial(n-1);
}
public static void main(String args[]) {
for (long i = 1; i <= 25; i++) {
System.out.println(i + "! = " + factorial(i));
}
}
}
/* output: ncorrect results starting with 21!
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = -4249290049419214848
22! = -1250660718674968576
23! = 8128291617894825984
24! = -7835185981329244160
25! = 7034535277573963776
*/

View File

@ -0,0 +1,36 @@
def factorial(n):
return 1 if n < 2 else n * factorial(n-1)
if __name__=='__main__':
for i in range(1, 26):
print('%s! = %s' % (i, factorial(i)))
"""
output:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = 51090942171709440000
22! = 1124000727777607680000
23! = 25852016738884976640000
24! = 620448401733239439360000
25! = 15511210043330985984000000
"""

View File

@ -67,8 +67,9 @@ class Order: # the Context
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
# <2>
def fidelity_promo(order): # <2>
def fidelity_promo(order): # <3>
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0