Skip to content

Commit b997794

Browse files
additional (advanced ) topic added + Cheatsheet
1 parent 89b4994 commit b997794

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+570
-1
lines changed

10. Generators/fibonacci_list.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
def fib(num):
3+
a = 0
4+
b= 1
5+
li=[]
6+
for i in range(num):
7+
li.append(a)
8+
temp = a
9+
a = b
10+
b = temp + b
11+
print(li)
12+
13+
num = int(input("Enter a number: "))
14+
fib(num)

10. Generators/fibonacci_range.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
def fib(num):
3+
a = 0
4+
b= 1
5+
for i in range(num):
6+
yield a
7+
temp = a
8+
a = b
9+
b = temp + b
10+
11+
num = int(input("Enter a number: "))
12+
13+
for i in fib(num):
14+
print(i)

10. Generators/generator.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
# here we are generating our own generator function, just like a range().
3+
4+
def generator_fn(num):
5+
print("check")
6+
#yield
7+
for i in range(num):
8+
print("****")
9+
yield i*2
10+
print("####")
11+
12+
g = generator_fn(3)
13+
print(g)
14+
print(next(g))
15+
print(next(g))
16+
print(next(g))
17+
#print(next(g)) # StopIteration error
18+
print(g)
19+
20+
for item in generator_fn(5):
21+
print(item)
22+
23+
# here it goes to the generator_fn(), gets the 'i' value, pauses the function, until called for the 2nd time,
24+
# and so on, it doesn't store all the no.s in the memory (just the most recent one).
25+
26+
'''
27+
'yield' pauses the function and comes back to it when we do something to it, which is called 'next'.
28+
29+
if there is the keyword 'yield' written inside the function, then python recognises that its a
30+
generator function, and won't run the function until the function is being iterated.
31+
'''

10. Generators/our_own_forloop.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
def my_own_forloop(iterable):
3+
iterator = iter(iterable)
4+
while True:
5+
try:
6+
print(iterator)
7+
print(next(iterator))
8+
except StopIteration:
9+
break
10+
11+
my_own_forloop([1,2,3,4,5])

10. Generators/our_own_range.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2+
class OurOwnRange():
3+
current = 0
4+
def __init__(self,first,last):
5+
self.first = first
6+
self.last = last
7+
8+
def __iter__(self):
9+
return self
10+
11+
def __next__(self):
12+
print("hehehheh")
13+
# if self.current < self.last:
14+
# num = OurOwnRange.current
15+
# OurOwnRange.current += 1
16+
# return num
17+
# raise StopIteration
18+
19+
gen = OurOwnRange(0,10)
20+
print(gen)
21+
22+
for i in gen:
23+
print(i)
24+
25+
'''
26+
loops by default deal with StopIteration error. they have build in functionality to handle them.
27+
'''
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
2+
import re
3+
4+
email_pattern = re.compile(r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
5+
check_email = email_pattern.fullmatch('saurabh_1089@gmail.com')
6+
7+
password_patter = re.compile(r"([a-zA-Z0-9@#$%]{8,}$)")
8+
check_password = password_patter.fullmatch('12345678')
9+
10+
if check_email and check_password:
11+
print("Both email and password are correct.")
12+
else:
13+
print("Try again.")
14+
15+
'''
16+
password is also checking for minimum 8 chars
17+
'''
+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import re
2+
3+
string = "this is a really cool string really!"
4+
5+
a = re.search('really',string)
6+
print(a)
7+
8+
# the below 4 commands will give error if the searching string does not exist.
9+
print(a.span())
10+
print(a.start())
11+
print(a.end())
12+
print(a.group())
13+
14+
pattern = re.compile('really')
15+
16+
b = pattern.search(string)
17+
c = pattern.findall(string)
18+
19+
pattern = re.compile('this is a really cool string really!')
20+
d = pattern.fullmatch('this is a really cool string really!')
21+
e = pattern.fullmatch('hello this is a really cool string really!') # this should be exact match, otherwise returns none
22+
23+
pattern = re.compile('really')
24+
f = pattern.match('really cool feature') # it starts matching from the first character otherwise returns none
25+
g = pattern.match('yo really')
26+
27+
print(f"b: {b}")
28+
print(f"c: {c}")
29+
print(f"d: {d}")
30+
print(f"e: {e}")
31+
print(f"f: {f}")
32+
print(f"g: {g}")
Binary file not shown.
Binary file not shown.
392 Bytes
Binary file not shown.
394 Bytes
Binary file not shown.
384 Bytes
Binary file not shown.
1.44 KB
Binary file not shown.
859 Bytes
Binary file not shown.
Binary file not shown.

12. Unit Testing/guess_game.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
import random
3+
4+
def run_guess(guess, answer):
5+
if 0 < guess < 11:
6+
if guess == answer:
7+
print('you are a genius!')
8+
return True
9+
else:
10+
print('hey bozo, I said 1~10')
11+
return False
12+
13+
if __name__ == '__main__': # so that the game don't start while testing.
14+
answer = random.randint(1, 10)
15+
while True:
16+
try:
17+
guess = int(input('guess a number 1~10: '))
18+
if (run_guess(guess, answer)):
19+
break
20+
except ValueError:
21+
print('please enter a number')
22+
continue
23+
24+
'''
25+
we test a function at a time.
26+
that is why it is called unit testing.
27+
hence we try to make pure functions and test them.
28+
'''

12. Unit Testing/script.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
2+
def add(num):
3+
try:
4+
return int(num) + 5
5+
except ValueError as err:
6+
return err

12. Unit Testing/test.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
import unittest
3+
import script
4+
5+
class TestMain(unittest.TestCase): # inheriting TestCase class
6+
7+
def setUp(self): # this method will run before starting all the other test methods
8+
print("Starting a method/test: ")
9+
10+
def test_add(self):
11+
'''This is the info for this particular test'''
12+
test_param = 10
13+
result = script.add(test_param)
14+
self.assertEqual(result,15)
15+
16+
def test_add2(self):
17+
test_param = 'random string'
18+
result = script.add(test_param)
19+
self.assertTrue(isinstance(result,ValueError))
20+
21+
def tearDown(self): # this method will run after every test method. Generally used to reset/cleaning up data variables.
22+
print("Cleaning up....")
23+
24+
25+
class A:
26+
print("\nClass A")
27+
28+
if __name__ == '__main__':
29+
unittest.main() # this will run the entire classes present in the file
30+
31+
32+
class B:
33+
print("Class B")

12. Unit Testing/test2.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
2+
import unittest
3+
import script
4+
5+
class TestMain(unittest.TestCase): # inheriting TestCase class
6+
def test_add(self):
7+
test_param = 10
8+
result = script.add(test_param)
9+
self.assertEqual(result,15)
10+
11+
def test_add2(self):
12+
test_param = 'random string'
13+
result = script.add(test_param)
14+
self.assertTrue(isinstance(result,ValueError))
15+
16+
if __name__ == '__main__':
17+
unittest.main()

12. Unit Testing/test_guess_game.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
import unittest
3+
import guess_game
4+
5+
class testGame(unittest.TestCase):
6+
def test_game(self):
7+
result = guess_game.run_guess(5,5)
8+
self.assertTrue(result)
9+
10+
def test_game2(self):
11+
result = guess_game.run_guess(0,5)
12+
self.assertFalse(result)
13+
14+
def test_game3(self):
15+
result = guess_game.run_guess(15,4)
16+
self.assertFalse(result)
17+
18+
if __name__ == '__main__':
19+
unittest.main()
20+
File renamed without changes.
File renamed without changes.

6. Error Handling/error_handling.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
while True:
3+
try:
4+
age = int(input("Enter your age: "))
5+
age_in_dogs_year = 10/age
6+
7+
except ZeroDivisionError:
8+
print("enter age greater than 0")
9+
continue
10+
11+
except ValueError:
12+
print("Please enter a no.")
13+
break
14+
15+
except ValueError:
16+
print("!!!!")
17+
18+
else:
19+
print(f"thank you, and your age is {age}")
20+
break
21+
22+
finally:
23+
print("I will always get printed no matter what :)")
24+
25+
print("can you hear me??????")
26+

6. Error Handling/error_handling2.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
2+
def division_fn(num1, num2):
3+
try:
4+
return num1/num2
5+
except (ZeroDivisionError, TypeError) as err:
6+
print(f'error: {err}')
7+
8+
print(division_fn(1,'0'))
9+
print(division_fn(1,0))
10+
print(division_fn(1,4))

6. Error Handling/raise_error.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
2+
# we can stop the program by raising our own errors.
3+
4+
print("Hello!!!!")
5+
# raise TypeError("yo")
6+
raise Exception("Any message ")
7+
print("bye")

6. Error Handling/raise_error2.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# -*- coding: utf-8 -*-
2+
3+
try:
4+
age = int(input("age: "))
5+
age = 10/age
6+
raise ValueError("Ending the program")
7+
# raise Exception("quit")
8+
9+
except ValueError:
10+
print("Please enter a no.")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
my_dict = {num:num**2 for num in range(1,11)}
3+
print(my_dict)
4+
5+
random_dict = {
6+
'a': 1,
7+
'b': 2,
8+
'c': 3,
9+
'd': 4
10+
}
11+
12+
my_new_dict = {k:v**2 for k,v in random_dict.items()}
13+
print(my_new_dict)
14+
15+
my_new_dict2 = {k:v**2 for k,v in random_dict.items() if v % 2 == 0}
16+
print(my_new_dict2)

7. Functional Programming/filter().py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
2+
def only_even(item):
3+
return item % 2 == 0
4+
5+
my_list = [5,8,9,2,5,6,98,56,62]
6+
7+
print(filter(only_even, my_list))
8+
print(list(filter(only_even, my_list)))
9+
print(list(map(only_even, my_list)))
10+
print(my_list)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
3+
import functools
4+
5+
my_list = [1,2,3,4,5]
6+
7+
print(list(map(lambda item: item*2, my_list)))
8+
9+
print(list(filter(lambda item: item % 2 != 0, my_list)))
10+
11+
print(functools.reduce(lambda acc,item: item+acc, my_list))
12+
13+
'''
14+
syntax:
15+
lambda param: action(param)
16+
it automatically returns the action taken,
17+
it do not have any name, doesn't get stored in the memory.
18+
and so used only once.
19+
and behaves exactly like a function.
20+
'''
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
2+
3+
a = [(0,2),(4,4),(10,-1),(5,3)]
4+
5+
a.sort(key=lambda x:x[1], reverse=False)
6+
print(a)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
my_list = []
3+
4+
for item in 'hello':
5+
my_list.append(item)
6+
7+
print(my_list)
8+
9+
my_list1 = [item for item in 'Saurabh']
10+
print(my_list1)
11+
12+
my_list2 = [num**2 for num in range(1,11)]
13+
print(my_list2)
14+
15+
# only even squares
16+
my_set = {num**2 for num in range(1,11) if num**2 % 2 == 0}
17+
print(my_set)
18+
# remember that set don't contain duplicate values

0 commit comments

Comments
 (0)