Skip to content

Commit 4ad8cf2

Browse files
committed
more excercise
1 parent 2774039 commit 4ad8cf2

19 files changed

+444
-21
lines changed

Session7/Q1.py

Lines changed: 0 additions & 20 deletions
This file was deleted.

Session7/README.md

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# CLASS
1+
# Class (part1)
22

33

44
Python is an object oriented programming language.
@@ -76,6 +76,7 @@ person0.sayHello()
7676

7777
## Magic Functions or Dunder Functions
7878

79+
[docs for special functions](https://docs.python.org/3/reference/datamodel.html#special-method-names)
7980

8081
- `__lt__(self, other)`
8182

@@ -88,3 +89,76 @@ person0.sayHello()
8889
- `__gt__(self, other)`
8990

9091
- `__ge__(self, other)`
92+
93+
****
94+
95+
96+
- `__getitem__(self, key)`
97+
98+
- `__setitem__(self, key, value)`
99+
100+
- `__contains__(self, item)`
101+
102+
****
103+
104+
- `__add__(self, other)` ==> `+`
105+
106+
- `__sub__(self, other)` ==> `-`
107+
108+
- `__mul__(self, other)` ==> `*`
109+
110+
- `__matmul__(self, other)` ==> `@ `
111+
112+
> [ptyhonDoc](https://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations) says `The @ (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator.`
113+
114+
- `__truediv__(self, other)` ==> `/`
115+
116+
- `__floordiv__(self, other)` ==> `//`
117+
118+
- `__mod__(self, other)` ==> `%`
119+
120+
- `__pow__(self, other[, modulo])` ==> `**`
121+
122+
- `__lshift__(self, other)` ==> `<<`
123+
124+
- `__rshift__(self, other)` ==> `>>`
125+
126+
- `__and__(self, other)` ==> `&`
127+
128+
- `__xor__(self, other)¶` ==> `^`
129+
130+
- `__or__(self, other)` ==> `|`
131+
132+
- `__radd__(self, other)`
133+
- `__rsub__(self, other)`
134+
- `__rmul__(self, other)`
135+
- `__rmatmul__(self, other)`
136+
- `__rtruediv__(self, other)`
137+
- `__rfloordiv__(self, other)`
138+
- `__rmod__(self, other)`
139+
- `__rpow__(self, other)`
140+
- `__rlshift__(self, other)`
141+
- `__rrshift__(self, other)`
142+
- `__rand__(self, other)`
143+
- `__rxor__(self, other)`
144+
- `__ror__(self, other)¶`
145+
146+
- `__iadd__(self, other)` ==> `+=`
147+
- `__isub__(self, other)` ==> `-=`
148+
- `__imul__(self, other)` ==> `*= `
149+
- `__imatmul__(self, other)` ==> `@=`
150+
- `__itruediv__(self, other)` ==> `/=`
151+
- `__ifloordiv__(self, other)` ==> `//=`
152+
- `__imod__(self, other)` ==> `%=`
153+
- `__ipow__(self, other[, modulo])` ==> `**=`
154+
- `__ilshift__(self, other)` ==> `<<=`
155+
- `__irshift__(self, other)` ==> `>>=`
156+
- `__iand__(self, other)` ==> `&=`
157+
- `__ixor__(self, other)` ==> `^=`
158+
- `__ior__(self, other)` ==> `|=`
159+
160+
****
161+
162+
- `__str__(self)`
163+
164+
- `__len__(self)`

Session7/fastFib/README.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
> this is a answer to question which mentioned in lesson
2+
3+
4+
# Question
5+
think a pile of numbers that we should check whether they are in the Fibonacci series or not.
6+
- **fisrt** most of numbers are duplicated
7+
- **second** make it *fast*
8+
9+
> try to solve it by your own before looking at the answers
10+
11+
## Files Description
12+
- `fastFib.py` is **the main answer**(your answers are welcomed if you can make it faster 😉)
13+
- also I solved this question using a *regular* method and not taking care of time which is in the `regularFib.py`.
14+
- `speedChecker.py` simply examines the other codes speed
15+
16+
## Sample Output
17+
```
18+
generating numbers...
19+
numbers generated...
20+
biggest number generated: 121918
21+
smallest number generated:121053
22+
numbers counted...
23+
making the graph...
24+
qt5ct: using qt5ct plugin
25+
...
26+
time elapsed for fast fib is 2.676896810531616
27+
time elapsed for fast fib is 16.891290426254272
28+
NOTE: all answers match
29+
number of matched items: 20818
30+
number of unmatched items: 9979182
31+
```
32+
33+
![](./numbers_destribution.png)
34+
![](./answers_destribution.png)
927 Bytes
Binary file not shown.
Binary file not shown.
10.5 KB
Loading

Session7/fastFib/fastFib.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class FibMaker:
2+
def __init__(self):
3+
self.series={1,1}
4+
self.lastNum0=1
5+
self.lastNum1=1
6+
7+
def isFib(self,num):
8+
if num in self.series:
9+
return True
10+
if num<self.lastNum1:
11+
return False
12+
a,b=self.lastNum0,self.lastNum1
13+
while b<num:
14+
a,b=b,a+b
15+
self.series.add(b)
16+
if b==num:
17+
self.lastNum0=a
18+
self.lastNum1=b
19+
return True
20+
self.lastNum0=a
21+
self.lastNum1=b
22+
return False
23+
24+
if __name__ == '__main__':
25+
f=FibMaker()
26+
for i in [3,5,11,8,20,50,100,90]:
27+
print(f.isFib(i))
11.6 KB
Loading

Session7/fastFib/regularFib.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
def isFib(num):
2+
a,b=1,1
3+
while b<num:
4+
a,b=b,a+b
5+
if b==num:
6+
return True
7+
return False
8+
9+
if __name__ == '__main__':
10+
for i in [3,5,11,8,20,50,100,90]:
11+
print(isFib(i))

Session7/fastFib/speedChecker.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from time import time
2+
from random import randint,gauss
3+
from fastFib import FibMaker
4+
from regularFib import isFib
5+
from collections import Counter
6+
try:
7+
from matplotlib import pyplot as plt
8+
drawGraph=True
9+
except:
10+
print('''You dont have matplotlib!!So I cant show any graph...
11+
try installing it using:
12+
$pip install matplotlib''')
13+
drawGraph=False
14+
# This is a Fibonacci series chose your constant wiser...
15+
# 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393
16+
#
17+
TEST_SIZE=int(1e7)
18+
START_RANGE=int(1.21e5)
19+
END_RANGE=int(1.22e5)
20+
print('generating numbers...')
21+
# numbers=[randint(START_RANGE,END_RANGE) for _ in range(TEST_SIZE)]
22+
numbers=[int(gauss((START_RANGE+END_RANGE)/2,(END_RANGE-START_RANGE)/12)) for _ in range(TEST_SIZE)]
23+
print('numbers generated...')
24+
print(f'''\tbiggest number generated: {max(numbers)}
25+
\tsmallest number generated:{min(numbers)}''')
26+
if drawGraph:
27+
numbersDest=Counter(numbers)
28+
############this is not good(why?):
29+
#x=[i[0] for i in numbersDest.items()]
30+
#y=[i[1] for i in numbersDest.items()]
31+
############this is much faster
32+
x=[]
33+
y=[]
34+
for i in numbersDest:
35+
x.append(i)
36+
y.append(numbersDest[i])
37+
print("numbers counted...\nmaking the graph...")
38+
plt.bar(x,y)
39+
plt.show()
40+
ansfastFib=[]
41+
ansreguFib=[]
42+
print('...')
43+
fastFib=FibMaker()
44+
now=time()
45+
for i in numbers:
46+
ansfastFib.append(fastFib.isFib(i))
47+
fastFibTime=time()-now
48+
print(f"time elapsed for fast fib is {fastFibTime}")
49+
50+
now=time()
51+
for i in numbers:
52+
ansreguFib.append(isFib(i))
53+
reguFibTime=time()-now
54+
print(f"time elapsed for fast fib is {reguFibTime}")
55+
56+
if all([i==j for i,j in zip(ansfastFib,ansreguFib)]):
57+
print("\tNOTE: all answers match")
58+
else:
59+
print("\tNOTE: all answers does NOT match")
60+
61+
ansDest=Counter(ansfastFib)
62+
63+
# plt.bar(['True','False'],[ansDest[True],ansDest[False]],yerr=["sallaaam","rrrr"])
64+
print(f"number of mathed items: {ansDest[True]}\nnumber of unmathed items: {ansDest[False]}")
65+
# plt.show()
66+
67+
fig, ax = plt.subplots()
68+
y=[ansDest[True],ansDest[False]]
69+
ax.bar(['True','False'],y)
70+
for index,data in enumerate(y):
71+
plt.text(index, 10, s=f"{data}")
72+
plt.tight_layout()
73+
plt.show()

Session8/README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Class(part2)
2+
3+
lets make an stack...
4+
5+
## a Simple Example
6+
**lets make a class**
7+
### what is stack ?
8+
9+
![stack](./stack.jpg)
10+
11+
> TIP: The initial step to make a class is defining its API *(what is API?)*
12+
13+
### API
14+
15+
| function/variable | arguments|returns| description |
16+
| :-------------: | :-------:| :---:|:--- |
17+
| push | value:[anytype] | `None` | pushes `value` into stack
18+
pop|-|last item in the stack, `None` if stack is empty | removes the last item in the stack and returns it|
19+
lastItem|-|last item in the stack|like pop but without removing
20+
isEmpty|-|`True` or `False`|returns `True` if stack is empty
21+
size|-| `int` |returns the number of items stored in the stack
22+
str|-|?|?
23+
eq|other stack|?|?
24+
25+
26+
**Question**
27+
28+
1. Implement a stack class
29+
2. describe how to use it in other code
30+
31+
**How to force user not to have access to main data in class?**
32+
33+
### public, private and protected Access Modifiers
34+
35+
**Question**\
36+
define terms public, private and protected.
37+
38+
```Python
39+
class test:
40+
"""docstring for test."""
41+
42+
def __init__(self):
43+
self.public='public' # this is public
44+
self._protected="protected" # this is protected
45+
self.__private="private" # this is private
46+
```
47+
48+
> NOTE: that was all joke!!! :)

Session8/stack.jpg

8.9 KB
Loading

Session8/stack.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class stack:
2+
def __init__(self):
3+
self.values=[]
4+
def push(self,value):
5+
self.values.append(value)
6+
7+
8+
def pop(self):
9+
if len(self.values)==0:
10+
return None
11+
else:
12+
return self.values.pop(-1)
13+
14+
def lastItem(self):
15+
if len(self.values)==0:
16+
return None
17+
else:
18+
return self.values[-1]
19+
def isEmpty(self):
20+
if len(self.values)==0:
21+
return True
22+
else:
23+
return False
24+
def __len__(self):
25+
return len(self.values)
26+
def __str__(self):
27+
return f"[ {' '.join(self.values)} ]"
28+
def __eq__(self,other):
29+
if type(other)==type(self):
30+
return self.values==other.values
31+
raise Exception("other type is not stack")
32+
33+
if __name__ == '__main__':
34+
s=stack()
35+
s.push(1)
36+
s.push(4)
37+
s.push(6)
38+
s.push("kasra")
39+
s.push("hellllo")
40+
print(s.pop())
41+
print(s.lastItem())
42+
print(s.pop())
43+
print(s.pop())
44+
print(s.lastItem())
45+
print(s.pop())
46+
print(s.pop())
47+
print(s.pop())
48+
print(s.pop())
49+
print(s.lastItem())
50+
print(s.pop())
51+
print(s.pop())
52+

Session9/Linkedlist.png

4.59 KB
Loading

Session9/Linkedlist_deletion.png

5.77 KB
Loading

Session9/Linkedlist_insert_middle.png

5.7 KB
Loading

0 commit comments

Comments
 (0)