Skip to content

Commit 352cae6

Browse files
committed
end of 6.2
1 parent 1f77047 commit 352cae6

11 files changed

Lines changed: 2690 additions & 18 deletions

File tree

Work/.vscode/settings.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
{
22
"workbench.editor.autoLockGroups": {
33
"terminalEditor": false
4-
}
4+
},
5+
"python.analysis.aiHoverSummaries": false,
6+
"chat.extensionUnification.enabled": false,
7+
"chat.disableAIFeatures": true,
8+
"python.analysis.autoImportCompletions": false
59
}

Work/Data/stocklog.csv

Lines changed: 2501 additions & 0 deletions
Large diffs are not rendered by default.

Work/exercise6.02.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
2+
3+
def countdown(n):
4+
# Added a print statement
5+
print('Counting down from', n)
6+
while n > 0:
7+
yield n
8+
n -= 1
9+
10+
def printtaa():
11+
x = countdown(10)
12+
print(x)
13+
print(x.__next__())
14+
print(x.__next__())
15+
print(x.__next__())
16+
print(x.__next__())
17+
print(x.__next__())
18+
print(x.__next__())
19+
print(x.__next__())
20+
print(x.__next__())
21+
print(x.__next__())
22+
print(x.__next__())
23+
print(x.__next__())
24+
25+
# printtaa()
26+
27+
def filematch(filename, substr):
28+
with open(filename, 'r') as f:
29+
for line in f:
30+
if substr in line:
31+
yield line
32+
33+
# for line in open('.\\Data\\portfolio.csv'):
34+
# print(line, end='')
35+
36+
f = filematch('.\\Data\\portfolio.csv', 'IBM')
37+
# print(f)
38+
# print(f.__next__(), end='')
39+
# print(f.__next__(), end='')
40+
41+
for line in f:
42+
print(line, end='')
43+
44+
45+
# for line in filematch('.\\Data\\portfolio.csv', 'IBM'):
46+
# print(line, end='')

Work/fileparse.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import csv
55
import gzip
66

7-
def parse_csv(source, select=None, types=None, has_headers=True, delimiter=',', silence_errors=False):
7+
def parse_csv(source, select=None, types=None, has_headers=True, delimiter=',', silence_errors=True):
88
'''
99
Parse an iterable source into a list of records.
1010
Returns a list of dictionaries if has_headers is True, otherwise returns a list of tuples.
@@ -37,7 +37,7 @@ def parse_csv(source, select=None, types=None, has_headers=True, delimiter=',',
3737
for rownum, row in enumerate(rows, start=start):
3838

3939
if not row: # Skip rows with no data
40-
print(f'Row {rownum}: Empty row')
40+
# print(f'Row {rownum}: Empty row')
4141
continue
4242
try:
4343
# Filter the row if specific columns were selected
@@ -47,7 +47,7 @@ def parse_csv(source, select=None, types=None, has_headers=True, delimiter=',',
4747
# Convert types if a list of types is provided
4848
if types:
4949
row = [func(val) for func, val in zip(types, row) ]
50-
print(f'Row {rownum}: Converted row: {row}')
50+
# print(f'Row {rownum}: Converted row: {row}')
5151

5252
except ValueError as e:
5353
if not silence_errors:
@@ -66,10 +66,10 @@ def parse_csv(source, select=None, types=None, has_headers=True, delimiter=',',
6666

6767

6868

69-
with open('.\\Data\\missing.csv') as f:
70-
d = parse_csv(f, types=[str, int, float])
69+
# with open('.\\Data\\missing.csv') as f:
70+
# d = parse_csv(f, types=[str, int, float])
7171

72-
print(d)
72+
# print(d)
7373

7474

7575

Work/follow.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
import os
3+
import time
4+
import report
5+
6+
def follow(filename):
7+
8+
f = open(filename)
9+
f.seek(0, os.SEEK_END) # Move file pointer 0 bytes from end of file
10+
11+
while True:
12+
line = f.readline()
13+
if line == '':
14+
time.sleep(0.1) # Sleep briefly and retry
15+
continue
16+
17+
yield line
18+
19+
20+
21+
if __name__ == '__main__':
22+
23+
portfolio = report.read_portfolio('.\\Data\\portfolio.csv')
24+
25+
for line in follow('.\\Data\\stocklog.csv'):
26+
fields = line.split(',')
27+
name = fields[0].strip('"')
28+
price = float(fields[1])
29+
change = float(fields[4])
30+
if name in portfolio:
31+
print(f'{name:>10s} {price:>10.2f} {change:>10.2f}')
32+

Work/pcost314.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@ def portfolio_cost(filename):
1010
:return: The total cost of the portfolio as a float.
1111
'''
1212

13-
portfolio = read_portfolio(filename)
13+
portfolio = read_portfolio(filename) # Portfolio class object
1414
# return sum([i['shares'] * i['price'] for i in portfolio ])
15-
return sum([i.shares * i.price for i in portfolio ])
15+
# return sum([i.shares * i.price for i in portfolio ])
16+
return portfolio.total_cost
1617

1718

1819

Work/portfolio.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# portfolio.py
2+
3+
class Portfolio:
4+
5+
def __init__(self, holdings):
6+
self._holdings = holdings
7+
8+
def __iter__(self): # usage: for i in object: ...
9+
return self._holdings.__iter__()
10+
11+
def __len__(self): # usage: len(object)
12+
return len(self._holdings)
13+
14+
def __getitem__(self, index): # usage: object[0], object[0:3]
15+
return self._holdings[index]
16+
17+
def __contains__(self, name): # usage: 'IBM' in object ? True
18+
return any([s.name == name for s in self._holdings])
19+
20+
21+
@property
22+
def total_cost(self): # usage: object.total_cost
23+
return sum([s.shares * s.price for s in self._holdings])
24+
25+
26+
def tabulate_shares(self):
27+
from collections import Counter
28+
29+
total_shares = Counter()
30+
for s in self._holdings:
31+
total_shares[s.name] += s.shares
32+
return total_shares
33+
34+
35+
36+
37+

Work/report.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
# import csv
55
# from pprint import pprint
66
from fileparse import parse_csv
7-
import stock
7+
from portfolio import Portfolio
8+
from stock import Stock
89
import tableformat
910

1011

@@ -27,8 +28,8 @@ def read_portfolio(filename):
2728
with open(filename) as f:
2829
portdicts = parse_csv(f, types=[str, int, float])
2930

30-
portfolio = [ stock.Stock(d['name'], d['shares'], d['price']) for d in portdicts]
31-
return portfolio
31+
portfolio = [ Stock(d['name'], d['shares'], d['price']) for d in portdicts]
32+
return Portfolio(portfolio)
3233

3334
def make_report(portfolio, prices):
3435
'''
@@ -93,7 +94,7 @@ def main(argv):
9394

9495
if __name__ == '__main__':
9596
import sys
96-
# print('hey this file is executed as main, not imported')
97+
# print('this prints when file is executed as main, not imported')
9798
if len(sys.argv) not in [3, 4]:
9899
raise SystemExit(f'Usage: {sys.argv[0]} ' 'portfile pricefile <format>')
99100

Work/using_pcost.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11

2-
import pcost314 as pcost
3-
# from pcost314 import portfolio_cost
2+
from pcost314 import portfolio_cost
43

5-
cost = pcost.portfolio_cost('.\\Data\\missing.csv')
6-
# cost = portfolio_cost('.\\Data\\portfolio.csv')
4+
# cost = portfolio_cost('.\\Data\\missing.csv')
5+
cost = portfolio_cost('.\\Data\\portfolio.csv')
76

87
print(f'Total cost of portfolio: ${cost:0.2f}')
98

Work/using_portfolio.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
import report
3+
4+
portfolio = report.read_portfolio('.\\Data\\portfolio.csv')
5+
print(len(portfolio))
6+
7+
print(portfolio[0])
8+
print(portfolio[1])
9+
print(portfolio[0:3])
10+
11+
print('IBM' in portfolio)
12+
print('YIT' in portfolio)
13+
14+
15+
16+
"""
17+
class Box:
18+
19+
def __init__(self, x=5, y=5):
20+
self.x = x
21+
self.y = y
22+
23+
# def __getattribute__(self, name):
24+
# if name == "x":
25+
# return 'No access.'
26+
# else:
27+
# # print(dir(name))
28+
# return self
29+
30+
@property
31+
def foo(self):
32+
return self.y
33+
34+
Box.g = 100
35+
b = Box(y=333)
36+
37+
f = b.foo
38+
print(b.x, b.g, f)
39+
# print(Box.__dict__)
40+
"""
41+
42+
"""
43+
t = (10,20,30)
44+
for i in range(len(t)):
45+
print('i:',i)
46+
print(t[:i], t[i]+i , t[i+1:])
47+
print('t ennen:',t)
48+
t = t[:i] + (t[i] + i,) + t[i+1:]
49+
print('t jälkeen:',t)
50+
print()
51+
"""

0 commit comments

Comments
 (0)