def first_non_repeating(string):
dict = {}
for items in range(len(string)):
key = string[items]
if key not in dict:
dict[key] = 1
else:
dict[key]+=1
counter = 0
for i in range(len(string)):
if dict[string[i]] == 1:
return string[i], counter
counter += 1
# for key, value in dict.items():
# if value == 1:
# return(key)
# break
s = 'ABCDEFGHABCDE'
print(first_non_repeating(s))
Author: Sayan Dey
How to implement a Stack in Python
class Stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
def peek(self):
if not self.is_empty():
return self.items[-1]
def get_stack(self):
return self.items
s = Stack()
print(s.is_empty())
Passing arguments in decorators
from functools import wraps
def only_datatype_allow(datatype):
def deco(function):
@wraps(function)
def wrapper(*args, **kwargs):
if all([type(arg) == datatype for arg in args]):
return function(*args, **kwargs)
print("Invalid Argument. Should only be of type integer !!")
return wrapper
return deco
@only_datatype_allow(str)
def string_join(*args):
string = ""
for items in args:
string += items
return string
print(string_join('Sayan', 'Dey'))
Program Using Decorators
from functools import wraps
def allow_only_int(func):
@wraps(func)
def wrapper(*args, **kwargs):
if all([type(arg) == int for arg in args]):
return func(*args, **kwargs)
print("Invalid Argument. Should only be of type integer !!")
return wrapper
@allow_only_int
def add_all(*args):
total = 0
for items in args:
total+=items
return total
print(add_all(1, 2, 3.2, 4.9, [1, 2, 3, 4]))
Using functools, decorators and time module in Python
from functools import wraps
import time
def calculate_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"You are running {func.__name__} function")
t1 = time.time()
returned = func(*args, **kwargs)
t2 = time.time()
total = t2 - t1
print(f"This function took {total} seconds to run")
return returned
return wrapper
@calculate_time
def squares(l):
return[items**2 for items in range(1, l+1)]
print(squares(10000))
Print function name and docstrings using decorators in Python
from functools import wraps
def print_function_data(func):
@wraps(func)
def wrapper_function(*args, **kwargs):
print(f"You are calling {func.__name__}")
print(f"This function {func.__doc__}")
return func(*args, **kwargs)
return wrapper_function
@print_function_data
def add(a, b):
'''takes two integers as input and returns their sum as output'''
return a+b
print(add(5,6))
enumerate() in Python
What is enumerate ?
Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.
list1 = []
n = 10
for items in range(n):
a = int(input("Enter your items : "))
list1.append(a)
print(list1)
for e, items in enumerate(list1):
print(f"The index is {e} and the value of index is {items}")
Decorators in Python
What is a decorator ?
A decorator in Python is any callable Python object that is used to modify a function or a class. A reference to a function “func” or a class “C” is passed to a decorator and the decorator returns a modified function or class.
Sample Program of Decorator
def decorator_function(func):
def msg():
print("Hey...")
func()
return msg
@decorator_function
def deco1():
print("This is a decorator function.")
deco1()
def deco2():
print("This is also a decorator function")
# abc = decorator_function(deco2)
# abc()
*args and **kwargs in Python
*args – The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list.
**kwargs – The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them).
Sample Program using both *args and **kwargs
def f(*args, **kwargs):
if kwargs.get('reverse_str') == True:
return [i[::-1].title() for i in args]
else:
return [i.title() for i in args]
a = ['sayan', 'dey']
print(f(*a, reverse_str = True))
sort() and sorted() in Python
# names = ["Sayan", "Dey", "SD"]
# names.sort()
# print(names)
# Not possible to sort names in Tuples or Sets
# names1 = ("Sayan", "Dey", "SD")
# sorted(names1)
# print(names1)
# names2 = {"Sayan", "Dey", "SD"}
# sorted(names2)
# print(names2)
dictionary = [
{"name" : "Sayan",
"stream" : "MCA",
"roll" : 11,
"marks" : 99},
{"name" : "Dey",
"stream" : "MCA",
"roll" : 12,
"marks" : 79},
{"name" : "SD",
"stream" : "MCA",
"roll" : 13,
"marks" : 98},
]
print(sorted(dictionary, key = lambda d:d.get('marks'), reverse = True))
print(sorted(dictionary, key = lambda d:d['marks'], reverse = True))