class to show implementation of custom sequence of list
class CustomList:
"""
This is the space to do documentation related to class.
"""
def __init__(self):
self.list_ = [1,2,3,4]
def __len__(self):
return len(self.list_)
def __getitem__(self, i):
if isinstance(i, int):
if i<0:
i = len(self.list_) + i
if i<0 or i>=len(self.list_):
raise IndexError('Invalid Input')
else:
return self.list_[i]
class to show implementation of custom sequence of tuple
class CustomTuple:
"""
This is the space to do documentation related to class.
"""
def __init__(self):
self.list_ = (1,2,3,4)
def __len__(self):
return len(self.list_)
def __getitem__(self, i):
if isinstance(i, int):
if i<0:
i = len(self.list_) + i
if i<0 or i>=len(self.list_):
raise IndexError('Invalid Input')
else:
return self.list_[i]
generate intereger random number between user choice
def gen_ran_int_number(lower, upper):
import random
final = [ random.randint(lower, upper) for _ in range(10) ]
return final
Function to show how to use f string
def f_string(msg: "user message"):
print(f'This is an f string with user paramter {msg}')
Function to show reading values from list is expensive in camparison to tuple
def compare_list_tuple():
from timeit import timeit
import random
l = [ random.randint(1,100) for _ in range(100) ]
tu = tuple(l)
list_time = timeit(stmt = 'max(l)', globals = locals(), number = 1)
tup_time = timeit(stmt = 'max(tu)', globals = locals(), number = 1)
if list_time > tup_time:
print('Hence proved')
else:
raise ValueError('You did something Wrong')
generate random number using the concept of iterators
class RandomInt:
"""
This is the space to do documentation related to class.
"""
def __init__(self):
self.n = 10
def __next__(self):
if self.n > 0:
print(random.randint(0,10))
self.n -= 1
else:
raise StopIteration
def __iter__(self):
return self
distinguish iter , iterables and iterator using example to print 10 random integers number
class RandomInt:
"""
This is the space to do documentation related to class.
"""
def __init__(self):
pass
def __iter__(self):
return self.RandomIntIterator(self)
class RandomIntIterator:
def __init__(self):
self.count = 10
def __iter__(self):
return self
def __next__(self):
if self.count > 0:
print(random.randint(0,10))
self.count -= 1
else:
raise StopIteration