-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathall_code.py
1866 lines (1803 loc) · 52.4 KB
/
all_code.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# def fib(x):
# """Assumes x an int >= 0
# Returns Fibonacci of x"""
# global numFibCalls
# numFibCalls += 1
# if x == 0 or x == 1:
# return 1
# else:
# return fib(x-1) + fib(x-2)
#
# def testFib(n):
# for i in range(n+1):
# global numFibCalls
# numFibCalls = 0
# print('fib of', i, '=', fib(i))
# print('fib called', numFibCalls, 'times.')
#
# print(testFib(6))
# nameHandle = open('kids', 'a')
# nameHandle.write('David\n')
# nameHandle.write('Andrea\n')
# nameHandle.close()
# nameHandle = open('kids', 'r')
# for line in nameHandle:
# print(line[:-1])
# nameHandle.close()
# t1 = ()
# t2 = (1, 'two', 3)
# t3 = (1, )
# print(t1)
# print(t2)
# print(t3)
# t1 = (1, 'two', 3)
# t2 = (t1, 3.25)
# print(t2)
# print((t1 + t2))
# print((t1 + t2)[3])
# print((t1 + t2)[2:5])
#
# def intersect(t1, t2):
# """Assumes t1 and t2 are tuples
# Returns a tuple containing elements that are in
# both t1 and t2"""
# result = ()
# for e in t1:
# if e in t2:
# result += (e,)
# return result
# def findExtremeDivisors(n1, n2):
# """Assumes that n1 and n2 are positive ints
# Returns a tuple containing the smallest common divisor > 1 and
# the largest common divisor of n1 and n2. If no common divisor,
# returns (None, None)"""
# minVal, maxVal = None, None
# for i in range(2, min(n1, n2) + 1):
# if n1%i == 0 and n2%i == 0:
# if minVal == None:
# minVal = i
# maxVal = i
# return (minVal, maxVal)
#
# print(findExtremeDivisors(5, 6))
# L1 = [1,2,3]
# L2 = [4,5,6]
# L3 = L1 + L2
# print('L3 =', L3)
# L1.extend(L2)
# print('L1 =', L1)
# L1.append(L2)
# print('L1 =', L1)
#
# def removeDups(L1, L2):
# """Assumes that L1 and L2 are lists.
# Removes any element from L1 that also occurs in L2"""
# for e1 in L1:
# if e1 in L2:
# L1.remove(e1)
# L1 = [1,2,3,4]
# L2 = [1,2,5,6]
# removeDups(L1, L2)
# print('L1 =', L1)
# def cube(x):
# x=x**3
# return x
#
# def applyToEach(L, f):
# for i in range(len(L)):
# L[i]=f(L[i])
#
# L=[1, 2, 3, 4, 5]
# print('L= ', L)
# print('Apply cube to each element of L.')
# applyToEach(L, cube)
# print('L= ', L)
#
# def fib(n):
# """Assumes n int >= 0
# Returns Fibonacci of n"""
# if n == 0 or n == 1:
# return 1
# else:
# return fib(n-1) + fib(n-2)
#
# def testFib(n):
# for i in range(n+1):
# print('fib of', i, '=', fib(i))
#
# for i in map(fib, [2, 6, 4]):
# print(i)
#
# L1 = [1, 36]
# L2 = [2, 57, 9]
# for i in map(min, L1, L2):
# print(i)
#
# L = []
# for i in map(lambda x, y: x**y, L1, L2):
# L.append(i)
# print(L)
# def keySearch(L, k):
# for elem in L:
# if elem[0] == k:
# return elem[1]
# return None
# birthStones = {'Jan':'Garnet', 'Feb':'Amethyst', 'Mar':'Acquamarine',
#'Apr':'Diamond', 'May':'Emerald'}
# months = birthStones.keys()
# print(months)
# birthStones['June'] = 'Pearl'
# print(list(months))
# def copy(L1, L2):
# """Assumes L1, L2 are lists
# Mutates L2 to be a copy of L1"""
# if L1 != L2:
# while len(L2) > 0: #remove all elements from L2
# L2.pop() #remove last element of L2
# for e in L1: #append L1's elements to initially empty L2
# L2.append(e)
# else:
# print("given lists are the same, no copying necessary")
#
# Ly=[1, 3, 5, 7, 9, 11, 13, 15]
# Lz=[2, 4, 6, 8, 10, 12, 14, 16]
#
# print(Lz)
# copy(Ly, Lz)
# print(Lz)
# L=["3", "5", "0", 9]
# def isEven(l):
# for i in l:
# if i % 2 == 0:
# return i
# raise ValueError("No even numbers in list!")
# print(isEven(L))
# def getRatios(vect1, vect2):
# """Assumes: vect1 and vect2 are equal length lists of numbers
# Returns: a list containing the meaningful values of
# vect1[i]/vect2[i]"""
# ratios = []
# for index in range(len(vect1)):
# try:
# ratios.append(vect1[index]/vect2[index])
# except ZeroDivisionError:
# ratios.append(float('nan')) #nan = Not a Number
# except:
# raise ValueError('getRatios called with bad arguments')
# return ratios
#
# try:
# print(getRatios([1.0,2.0,7.0,6.0], [1.0,2.0,0.0,3.0]))
# print(getRatios([], []))
# print(getRatios([1.0, 2.0], [3.0]))
# except ValueError as msg:
# print(msg)
# BAD CODE
# def getRatios(vect1, vect2):
# """Assumes: vect1 and vect2 are lists of equal length of numbers
# Returns: a list containing the meaningful values of
# vect1[i]/vect2[i]"""
# ratios = []
# if len(vect1) != len(vect2):
# raise ValueError('getRatios called with bad arguments')
# for index in range(len(vect1)):
# vect1Elem = vect1[index]
# vect2Elem = vect2[index]
# if (type(vect1Elem) not in (int, float))\
# or (type(vect2Elem) not in (int, float)):
# raise ValueError('getRatios called with bad arguments')
# if vect2Elem == 0.0:
# ratios.append(float('NaN')) #NaN = Not a Number
# else:
# ratios.append(vect1Elem/vect2Elem)
# return ratios
# def getGrades(fname):
# try:
# gradesFile = open(fname, 'r') #open file for reading
# except IOError:
# raise ValueError('getGrades could not open ' + fname)
# grades = []
# for line in gradesFile:
# try:
# grades.append(float(line))
# except:
# raise ValueError('Unable to convert line to float')
# return grades
#
# try:
# grades = getGrades('quiz1grades.txt')
# grades.sort()
# median = grades[len(grades)//2]
# print('Median grade is', median)
# assert median == 49.0, "Are you sure it is not 49.0?"
# except ValueError as errorMsg:
# print('Whoops.', errorMsg)
# except AssertionError as error:
# print(error)
# class IntSet(object):
# """An intSet is a set of integers"""
# #Information about the implementation (not the abstraction)
# #Value of the set is represented by a list of ints, self.vals.
# #Each int in the set occurs in self.vals exactly once.
#
# def __init__(self):
# """Create an empty set of integers"""
# self.vals = []
#
# def insert(self, e):
# """Assumes e is an integer and inserts e into self"""
# if e not in self.vals:
# self.vals.append(e)
#
# def member(self, e):
# """Assumes e is an integer
# Returns True if e is in self, and False otherwise"""
# return e in self.vals
#
# def remove(self, e):
# """Assumes e is an integer and removes e from self
# Raises ValueError if e is not in self"""
# try:
# self.vals.remove(e)
# except:
# raise ValueError(str(e) + ' not found')
#
# def getMembers(self):
# """Returns a list containing the elements of self.
# Nothing can be assumed about the order of the elements"""
# return self.vals[:]
#
# def __str__(self):
# """Returns a string representation of self"""
# self.vals.sort()
# result = ''
# for e in self.vals:
# result = result + str(e) + ','
# return '{' + result[:-1] + '}' #-1 omits trailing comma
#
# s = IntSet()
# s.insert(6)
# s.insert(4)
# print(s)
##Class Person
# import datetime
#
# class Person(object):
#
# def __init__(self, name):
# """Create a person"""
# self.name = name
# try:
# lastBlank = name.rindex(' ')
# self.lastName = name[lastBlank+1:]
# except:
# self.lastName = name
# self.birthday = None
#
# def getName(self):
# """Returns self's full name"""
# return self.name
#
# def getLastName(self):
# """Returns self's last name"""
# return self.lastName
#
# def setBirthday(self, birthdate):
# """Assumes birthdate is of type datetime.date
# Sets self's birthday to birthdate"""
# self.birthday = birthdate
#
# def getAge(self):
# """Returns self's current age in days"""
# if self.birthday == None:
# raise ValueError
# return (datetime.date.today() - self.birthday).days
#
# def __lt__(self, other):
# """Returns True if self precedes other in alphabetical
# order, and False otherwise. Comparison is based on last
# names, but if these are the same full names are
# compared."""
# if self.lastName == other.lastName:
# return self.name < other.name
# return self.lastName < other.lastName
#
#
# def __str__(self):
# """Returns self's name"""
# return self.name
#
##Class MIT Person
# class MITPerson(Person):
#
# nextIdNum = 0 #identification number
#
# def __init__(self, name):
# Person.__init__(self, name)
# self.idNum = MITPerson.nextIdNum
# MITPerson.nextIdNum += 1
#
# def getIdNum(self):
# return self.idNum
#
# def isStudent(self):
# return isinstance(self, Student)
#
# def __lt__(self, other):
# try:
# return self.idNum < other.idNum
# except AttributeError:
# print(MITPerson.getName(self) + ' has no ID Number. Get him one!')
#
##Class Student
# class Student(MITPerson):
# pass
#
# class UG(Student):
# def __init__(self, name, classYear):
# MITPerson.__init__(self, name)
# self.year = classYear
# def getClass(self):
# return self.year
#
# class Grad(Student):
# pass
#
##me = Person('Arjan Siddhpura')
##him = Person('Barack Obama')
##her = Person('Madonna')
##print(him.getLastName())
##him.setBirthday(datetime.date(1961, 8, 4))
##her.setBirthday(datetime.date(1958, 8, 16))
##print(him.getName(), 'is', him.getAge(), 'days old.')
##people = [me, him, her]
##people.sort()
##people.reverse()
##for p in people:
## print(p)
#
# p1 = MITPerson('Mark Guttag')
# p2 = MITPerson('Billy Bob Beaver')
# p3 = MITPerson('Billy Bob Beaver')
# p4 = Person('Billy Bob Beaver')
# p5 = Grad('Buzz Aldrin')
# p6 = UG('Billy Beaver', 1984)
#
##print(str(p1) + '\'s id number is ' + str(p1.getIdNum()))
##print('And ' + str(p2) + '\'s id number is ' + str(p2.getIdNum()))
# print(p5, 'is a graduate student is', type(p5) == Grad)
# print(p5, 'is an undergraduate student is', type(p5) == UG)
# print(p5, 'is a student is', p5.isStudent())
# print(p3, 'is a student is', p3.isStudent())
##print('p4 < p1 = ', p4 < p1)
##print('p1 < p4 = ', p1 < p4)
##Class Mortgage
#
# def findPayment(loan, r, m):
# """Assumes: loan and r are floats, m an int
# Returns the monthly payment for a mortgage of size
# loan at a monthly rate of r for m months"""
# return loan*((r*(1+r)**m)/((1+r)**m - 1))
#
# class Mortgage(object):
# """Abstract class for building different kinds of mortgages"""
#
# def __init__(self, loan, annRate, months):
# """Assumes: loan and annRate are floats, months an int
# Creates a new mortgage of size loan, duration months, and
# annual rate annRate"""
# self.loan = loan
# self.rate = annRate/12
# self.months = months
# self.paid = [0.0]
# self.outstanding = [loan]
# self.payment = findPayment(loan, self.rate, months)
# self.legend = None #description of mortgage
#
# def makePayment(self):
# """Make a payment"""
# self.paid.append(self.payment)
# reduction = self.payment - self.outstanding[-1]*self.rate
# self.outstanding.append(self.outstanding[-1] - reduction)
#
# def getTotalPaid(self):
# """Return the total amount paid so far"""
# return sum(self.paid)
#
# def __str__(self):
# return self.legend
#
# class Fixed(Mortgage):
# def __init__(self, loan, r, months):
# Mortgage.__init__(self, loan, r, months)
# self.legend = 'Fixed, ' + str(round(r*100, 2)) + '%'
#
# class FixedWithPts(Mortgage):
# def __init__(self, loan, r, months, pts):
# Mortgage.__init__(self, loan, r, months)
# self.pts = pts
# self.paid = [loan*(pts/100)]
# self.legend = 'Fixed, ' + str(round(r*100, 2)) + '%, '\
# + str(pts) + ' points'
#
# class TwoRate(Mortgage):
# def __init__(self, loan, r, months, teaserRate, teaserMonths):
# Mortgage.__init__(self, loan, teaserRate, months)
# self.teaserMonths = teaserMonths
# self.teaserRate = teaserRate
# self.nextRate = r/12
# self.legend = str(teaserRate*100)\
# + '% for ' + str(self.teaserMonths)\
# + ' months, then ' + str(round(r*100, 2)) + '%'
#
# def makePayment(self):
# if len(self.paid) == self.teaserMonths + 1:
# self.rate = self.nextRate
# self.payment = findPayment(self.outstanding[-1],
# self.rate,
# self.months - self.teaserMonths)
# Mortgage.makePayment(self)
#
# def compareMortgages(amt, years, fixedRate, pts, ptsRate,
# varRate1, varRate2, varMonths):
# totMonths = years*12
# fixed1 = Fixed(amt, fixedRate, totMonths)
# fixed2 = FixedWithPts(amt, ptsRate, totMonths, pts)
# twoRate = TwoRate(amt, varRate2, totMonths, varRate1, varMonths)
# morts = [fixed1, fixed2, twoRate]
# for m in range(totMonths):
# for mort in morts:
# mort.makePayment()
# for m in morts:
# print(m)
# print(' Total Payments = $' + str(int(m.getTotalPaid())))
#
# compareMortgages(amt=200000, years=30, fixedRate=0.07, pts=3.25,
# ptsRate=0.05, varRate1=0.045, varRate2=0.095, varMonths=48)
# Integer to String Convertor
# def intToStr(i):
# digits = '0123456789'
# result = ''
# if i == 0:
# return '0'
# while i > 0:
# result = digits[i%10] + result
# i //= 10
# return result
#
# def addDigits(n):
# stringRep = intToStr(n)
# val = 0
# for c in stringRep:
# val += int(c)
# return val
#
# print(addDigits(123))
# Implementation of a Subset Test
# def isSubset(L1, L2):
# for e1 in L1:
# matched = False
# for e2 in L2:
# if e1 == e2:
# matched = True
# break
# if not matched:
# return False
# return True
#
# print(isSubset(L1=[5, 3], L2=[1, 2, 3, 4, 5]))
##Generating a Power Set
# def getBinaryRep(n, numDigits):
# result = ''
# while n > 0:
# result = str(n%2) + result
# n //= 2
# if len(result) > numDigits:
# raise ValueError('not enough digits')
# for i in range(numDigits-len(result)):
# result = '0' + result
# return result
#
# def genPowerset(L):
# powerset = []
# for i in range(0, 2**len(L)):
# binStr = getBinaryRep(i, len(L))
# subset = []
# for j in range(len(L)):
# if binStr[j] == '1':
# subset.append(L[j])
# powerset.append(subset)
# return powerset
#
# print(genPowerset(L=[1, 3, 5]))
# Linear Search of a Sorted List
# def search(L, e):
# for i in range(len(L)):
# if L[i] == e:
# return True
# if L[i] > e:
# return False
# return False
#
# L=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# print(search(L, 12))
# Recursive Binary Search
# def search(L, e):
# """Assumes L is a sorted list in ascending order"""
#
# def bSearch(L, e, low, high):
# #Decrements high - low
# if high == low:
# return L[low] == e
# mid = (low + high)//2
# if L[mid] == e:
# return True
# elif L[mid] > e:
# if low == mid: #Nothing left to search
# return False
# else:
# return bSearch(L, e, mid + 1, high)
#
# if len(L) == 0:
# return False
# else:
# return bSearch(L, e, 0, len(L) - 1)
# Merge Sort Algorithm
# def merge(left, right, compare):
#
# result = []
# i, j = 0, 0
# while i < len(left) and j < len(right):
# if compare(left[i], right[j]):
# result.append(left[i])
# i += 1
# else:
# result.append(right[j])
# j += 1
# while (i < len(left)):
# result.append(left[i])
# i += 1
# while (j < len(right)):
# result.append(right[j])
# j += 1
# return result
#
# def mergeSort(L, compare = lambda x, y: x < y):
# if len(L) <= 1:
# return L[:]
# else:
# middle = len(L)//2
# left = mergeSort(L[:middle])
# right = mergeSort(L[middle:])
# return merge(left, right, compare)
#
# L = [1, 90, 15, 13, 11, 10, 9, 66, -5, -9, -99, 31, 2, 95, 82, 66, 3]
# sortedL = mergeSort(L)
# print(sortedL)
# Hashing Tables
# class intDict(object):
#
# def __init__(self, numBuckets):
# self.buckets = []
# self.numBuckets = numBuckets
# for i in range(numBuckets):
# self.buckets.append([])
#
# def addEntry(self, key, dictVal):
# hashBucket = self.buckets[key%self.numBuckets]
# for i in range(len(hashBucket)):
# if hashBucket[i][0] == key:
# hashBucket[i] = (key, dictVal)
# return
# hashBucket.append((key, dictVal))
#
# def getValue(self, key):
# hashBucket = self.buckets[key%self.numBuckets]
# for e in hashBucket:
# if e[0] == key:
# return e[1]
# return None
#
# def __str__(self):
# result = '{'
# for b in self.buckets:
# for e in b:
# result = result + str(e[0]) + ':' + str(e[1]) + ','
# return result[:-1] + '}'
#
# import random
# D = intDict(10)
# for i in range(20):
# key = random.choice(range(10**2))
# D.addEntry(key, i)
# print('\nThe value of the intDict is:')
# print(D)
# print('\n', 'The buckets are:')
# for hashBucket in D.buckets:
# print(' ', hashBucket)
##PyLab Works
# import pylab
#
# def findPayment(loan, r, m):
# """Assumes: loan and r are floats, m an int
# Returns the monthly payment for a mortgage of size
# loan at a monthly rate of r for m months"""
# return loan*((r*(1+r)**m)/((1+r)**m - 1))
#
# class Mortgage(object):
# def __init__(self, loan, annRate, months):
# self.loan = loan
# self.rate = annRate/12.0
# self.months = months
# self.paid = [0.0]
# self.outstanding = [loan]
# self.payment = findPayment(loan, self.rate, months)
# self.legend = None
#
# def makePayment(self):
# self.paid.append(self.payment)
# reduction = self.payment - self.outstanding[-1] * self.rate
# self.outstanding.append(self.outstanding[-1] - reduction)
#
# def getTotalPaid(self):
# return sum(self.paid)
# def __str__(self):
# return self.legend
#
# def plotPayments(self, style):
# pylab.plot(self.paid[1:], style, label = self.legend)
#
# def plotBalance(self, style):
# pylab.plot(self.outstanding, style, label = self.legend)
#
# def plotTotPd(self, style):
# totPd = [self.paid[0]]
# for i in range(1, len(self.paid)):
# totPd.append(totPd[-1] + self.paid[i])
# pylab.plot(totPd, style, label = self.legend)
#
# def plotNet(self, style):
# totPd = [self.paid[0]]
# for i in range(1, len(self.paid)):
# totPd.append(totPd[-1] + self.paid[i])
# equityAcquired = pylab.array([self.loan] * \
# len(self.outstanding))
# equityAcquired = equityAcquired - \
# pylab.array(self.outstanding)
# net = pylab.array(totPd) - equityAcquired
# pylab.plot(net, style, label = self.legend)
#
# class Fixed(Mortgage):
# def __init__(self, loan, r, months):
# Mortgage.__init__(self, loan, r, months)
# self.legend = 'Fixed, ' + str(r*100) + '%'
#
# class FixedWithPts(Mortgage):
# def __init__(self, loan, r, months, pts):
# Mortgage.__init__(self, loan, r, months)
# self.pts = pts
# self.paid = [loan*(pts/100.0)]
# self.legend = 'Fixed, ' + str(r*100) + '%, '\
# + str(pts) + ' points'
#
# class TwoRate(Mortgage):
# def __init__(self, loan, r, months, teaserRate, teaserMonths):
# Mortgage.__init__(self, loan, teaserRate, months)
# self.teaserMonths = teaserMonths
# self.teaserRate = teaserRate
# self.nextRate = r/12.0
# self.legend = str(teaserRate*100)\
# + '% for ' + str(self.teaserMonths)\
# + ' months, then ' + str(r*100) + '%'
#
# def makePayment(self):
# if len(self.paid) == self.teaserMonths + 1:
# self.rate = self.nextRate
# self.payment = findPayment(self.outstanding[-1],
# self.rate,
# self.months - self.teaserMonths)
# Mortgage.makePayment(self)
#
# def plotMortgages(morts, amt):
# def labelPlot(figure, title, xLabel, yLabel):
# pylab.figure(figure)
# pylab.title(title)
# pylab.xlabel(xLabel)
# pylab.ylabel(yLabel)
# pylab.legend(loc = 'best')
# styles = ['k-', 'k-.', 'k:']
# #Give names to figure numbers
# payments, cost, balance, netCost = 0, 1, 2, 3
# for i in range(len(morts)):
# pylab.figure(payments)
# morts[i].plotPayments(styles[i])
# pylab.figure(cost)
# morts[i].plotTotPd(styles[i])
# pylab.figure(balance)
# morts[i].plotBalance(styles[i])
# pylab.figure(netCost)
# morts[i].plotNet(styles[i])
# labelPlot(payments, 'Monthly Payments of $' + str(amt) +
# ' Mortgages', 'Months', 'Monthly Payments')
# labelPlot(cost, 'Cash Outlay of $' + str(amt) +
# ' Mortgages', 'Months', 'Total Payments')
# labelPlot(balance, 'Balance Remaining of $' + str(amt) +
# ' Mortgages', 'Months', 'Remaining Loan Balance of $')
# labelPlot(netCost, 'Net Cost of $' + str(amt) + ' Mortgages',
# 'Months', 'Payments - Equity $')
#
# def compareMortgages(amt, years, fixedRate, pts, ptsRate,
# varRate1, varRate2, varMonths):
# totMonths = years*12
# fixed1 = Fixed(amt, fixedRate, totMonths)
# fixed2 = FixedWithPts(amt, ptsRate, totMonths, pts)
# tworate = TwoRate(amt, varRate2, totMonths, varRate1, varMonths)
# morts = [fixed1, fixed2, tworate]
# for m in range(totMonths):
# for mort in morts:
# mort.makePayment()
# plotMortgages(morts, amt)
#
# compareMortgages(amt=200000, years=30, fixedRate=0.07, pts=3.25,
# ptsRate=0.05, varRate1=0.045, varRate2=0.095, varMonths=48)
#
# pylab.show()
# Graph Optimization Problems
# class Node(object):
# def __init__(self, name):
# self.name = name
# def getName(self):
# return self.name
# def __str__(self):
# return self.name
#
# class Edge(object):
# def __init__(self, src, dest):
# self.src = src
# self.dest = dest
# def getSource(self):
# return self.src
# def getDestination(self):
# return self.dest
# def __str__(self):
# return self.src.getName() + '->' + self.dest.getName()
#
# class WeightedEdge(Edge):
# def __init__(self, src, dest, weight = 1.0):
# self.src = src
# self.dest = dest
# self.weight = weight
# def getWeight(self):
# return self.weight
# def __str__(self):
# return self.src.getName() + '->(' + str(self.weight) + ')->' + \
# self.dest.getName()
#
# class Digraph(object):
# def __init__(self):
# self.nodes = []
# self.edges = {}
# def addNode(self, node):
# if node in self.nodes:
# raise ValueError('Duplicate Node')
# else:
# self.nodes.append(node)
# self.edges[node] = []
# def addEdge(self, edge):
# src = edge.getSource()
# dest = edge.getDestination()
# if not (src in self.nodes and dest in self.nodes):
# raise ValueError('Node not in Graph')
# self.edges[src].append(dest)
# def childrenOf(self, node):
# return self.edges[node]
# def hasNode(self, node):
# return node in self.nodes
# def __str__(self):
# result = ''
# for src in self.nodes:
# for dest in self.edges[src]:
# result = result + src.getName() + '->' \
# + dest.getName() + '\n'
# return result[:-1]
#
# class Graph(Digraph):
# def addEdge(self, edge):
# Digraph.addEdge(self, edge)
# rev = Edge(edge.getDestination(), edge.getSource())
# Digraph.addEdge(self, rev)
#
# def printPath(path):
# result = ''
# for i in range(len(path)):
# result = result + str(path[i])
# if i != len(path) - 1:
# result = result + '->'
# return result
#
# def DFS(graph, start, end, path, shortest, toPrint = False):
# path = path + [start]
# if toPrint:
# print('Current DFS Path:', printPath(path))
# if start == end:
# return path
# for node in graph.childrenOf(start):
# if node not in path:
# if shortest == None or len(path) < len(shortest):
# newPath = DFS(graph, node, end, path, shortest, toPrint)
# if newPath != None:
# shortest = newPath
# return shortest
#
# def BFS(graph, start, end, toPrint = False):
# initPath = [start]
# pathQueue = [initPath]
# if toPrint:
# print('Current BFS path:', printPath(initPath))
# while len(pathQueue) != 0:
# tmpPath = pathQueue.pop(0)
# print('Current BFS path:', printPath(tmpPath))
# lastNode = tmpPath[-1]
# if lastNode == end:
# return tmpPath
# for nextNode in graph.childrenOf(lastNode):
# if nextNode not in tmpPath:
# newPath = tmpPath + [nextNode]
# pathQueue.append(newPath)
# return None
#
# def shortestPath(graph, start, end, toPrint = False):
# return DFS(graph, start, end, [], None, toPrint)
#
# def testSP():
# nodes = []
# for name in range(6):
# nodes.append(Node(str(name)))
# g = Digraph()
# for n in nodes:
# g.addNode(n)
# g.addEdge(Edge(nodes[0], nodes[1]))
# g.addEdge(Edge(nodes[1], nodes[2]))
# g.addEdge(Edge(nodes[2], nodes[3]))
# g.addEdge(Edge(nodes[2], nodes[4]))
# g.addEdge(Edge(nodes[3], nodes[4]))
# g.addEdge(Edge(nodes[3], nodes[5]))
# g.addEdge(Edge(nodes[0], nodes[2]))
# g.addEdge(Edge(nodes[1], nodes[0]))
# g.addEdge(Edge(nodes[3], nodes[1]))
# g.addEdge(Edge(nodes[4], nodes[0]))
# sp = shortestPath(g, nodes[0], nodes[5], toPrint = True)
# print('Shortest path found by DFS:', printPath(sp), '\n')
# sp = BFS(g, nodes[0], nodes[5])
# print('Shortest path found by BFS:', printPath(sp))
#
# testSP()
# Fast Fibonacci with Dynamic Programming
# def fib(n):
# if n == 0 or n == 1:
# return 1
# else:
# return fib(n-1) + fib(n-2)
#
# def fastFib(n, memo = {}):
# if n == 0 or n == 1:
# return 1
# try:
# return memo[n]
# except KeyError:
# result = fastFib(n-1, memo) + fastFib(n-2, memo)
# memo[n] = result
# return result
#
# print(fastFib(500))
##0/1 Knapsach Problems and Dynamic Programming
# import random
#
# class Item(object):
# def __init__(self, n, v, w):
# self.name = n
# self.value = v
# self.weight = w
# def getName(self):
# return self.name
# def getValue(self):
# return self.value
# def getWeight(self):
# return self.weight
# def __str__(self):
# result = '<' + self.name + ', ' + str(self.value) \
# + ', ' + str(self.weight) + '>'
# return result
#
# def value(item):
# return item.getValue()
#
# def weightInverse(item):
# return 1.0/item.getWeight()
#
# def density(item):
# return item.getValue()/item.getWeight()
#
# def greedy(items, maxWeight, keyFunction):
# itemsCopy = sorted(items, key=keyFunction, reverse=True)
# result = []
# totalValue, totalWeight = 0.0, 0.0
# for i in range(len(itemsCopy)):
# if (totalWeight + itemsCopy[i].getWeight()) <= maxWeight:
# result.append(itemsCopy[i])
# totalWeight += itemsCopy[i].getWeight()
# totalValue += itemsCopy[i].getValue()
# return (result, totalValue)
#
# def buildItems():
# names = ['clock','painting','radio','vase','book','computer']
# values = [175,90,20,50,10,200]
# weights = [10,9,4,2,1,20]
# Items = []
# for i in range(len(values)):
# Items.append(Item(names[i], values[i], weights[i]))
# return Items
#
# def testGreedy(items, maxWeight, keyFunction):
# taken, val = greedy(items, maxWeight, keyFunction)
# print('Total value of items taken is', val)
# for item in taken:
# print(' ', item)
#