# Maximum of two numbers in Python
# Python program to find the
# maximum of two numbers
# def maximum(a, b):
# if a >= b:
# return a
# else:
# return b
# Driver code
# a = 2
# b = 4
# print(maximum(a, b))
#compare a list
fruit1=["apple","banana","kiwi"]
fruit2=["apple","banana","kiwi"]
# fruit3=["orange","watermelon"]
# print(fruit1==fruit2)#same value
# print(fruit1 is fruit2)#different momory location
# def negative_list(l):
# negative= []
# for i in l:
# [Link](-i)
# return negative
#
# print(negative_list(numbers))
nums=[1,2,3,4,5,6,7,8]
# def square_list(l):
# square=[]
# for i in l:
# [Link](i**2)
# return square
# print(square_list(numbers))
num=[1,2,3,4,5,6,7,8,9]
# def reverse_list(l):
# return l[::-1]
# print(reverse_list(numbers))
nums=[1,2,3,4,5,6,7,8]
#reverse element in list
words=["xuv","yas","zds"]
# def reverse_element(l):
# element=[]
# for i in l:
# [Link](i[::-1])
# return element
# print(reverse_element(words))
# def common_list(l1,l2):
# output=[]
# for i in l1:
# if i in l2:
# [Link](i)
# return output
# print(common_list(l1,l2))
l1=[1,2,3,4]
l2=[1,2,3]
#minus min number to max num
# def greatest_diff(l):
# return max(l)-min(l)
# print(greatest_diff(numbers))
num=[12,34,2]
#count how many lists in list
# numbers=[[1, 2, 3], [ 4, 5, 6 ,7],[8, 9, 10]]
# def sublist_count(l):
# count=0
# for i in l:
# if type(i)==list:
# count+=1
# return count
# print(sublist_count(numbers))
list1=[[1,2,3],[4,5,6],[6,7,8]]
#cube finder using dict
# def cube_finder(n):
# cubes={}
# for i in range(n+1):
# cubes[i]=i**3
# return cubes
# print(cube_finder(10))
#word count using for loop
# temp=""
# name=input("enter your name")
# for i in range(len(name)):
# if name[i] not in temp:
# print(f"{name[i]}:{[Link](name[i])}")
# temp+=name[i]
# word count using dictionary
# def word_counter(s):
# count={}
# for char in s:
# count[char]=[Link](char)
# return count
# print(word_counter("gaurav"))
#string methods
# name="gaUrav mAHalle"
#
# print(len(name))
# print([Link]())
# print([Link]())
# print([Link]())
# print([Link]("a"))
# name=" Gau rav "
# dots="............"
# print(name+dots)
# print([Link]()+dots)
# print([Link]()+dots)
# print([Link]()+dots)
# print([Link](" ",""))
string="my name is gaurav what is your name"
# print([Link](" ","_"))
# print([Link]("zx"))
# print([Link]("is","was"))
# pos1=([Link]("is"))
# pos2=([Link]("is",pos1 + 1))
# print(pos2)
# name="gaurav"
# print([Link](8,"*"))
#continue and break
# for i in range(1,11):
# if i==5:
# break
# print(i)
#
# for i in range (1,11):
# if i==5:
# continue
# print(i)
# i=1
# while i<=10:
# print("hello world")
# i+=1
# for i in range(1,11):
# print("hello world")
# i=1
# total=0
# while i<=10:
# total+=i
# print(total)
# i+=1
# total=0
# for i in range(1,11):
# total+=i
# print(total)
# i=1
# total=0
# num=int(input("enter a number:"))
# while i<=num:
# total+=i
# print(total)
# i+=1
# total=0
# num=int(input("enter a number:"))
# for i in range(num+1):
# total+=i
# print(total)
# i=0
# total=0
# num=input("enter your numbers:")
# while i<len(num):
# total+=int(num[i])
# print(total)
# i+=1
# total=0
# num=input("enter your numbers:")
# for i in range(len(num)):
# total+=int(num[i])
# print(total)
# exaple of lambda function
# is_even=lambda a:a%2==0
# print(is_even(4))
#use enumerate func
#enumerate function track position of index or
element in list
names=["gaurav","vijay","sham"]
# for pos, name in enumerate(names):
# print(f"{pos}:{name}")
#square in list of element using lambda func
nums=[1,2,3,4,5]
# squares=list(map(lambda a:a**2,nums))
# print(squares)
num=[1,2,3,4,5]
#count uppercase letters in string
# string=input("Enter string:")
# count=0
# for i in string:
# if([Link]()):
# count1=count+1
#
# print(count)
#any and all
# num1=[2,4,6,8,10]
# num2=[1,3,6,7,9]
# print(all([num%2==0 for num in num1] ))
# print(any([num%2==0 for num in num2] ))
#output the following
# x=["ëabí","ícdí"]
# print(len(list(map(list,x))))
# display most duplicate element in a list
l = [2, 1, 2, 2, 1, 3]
# def duplicate(l):
# return max(set(l),key=[Link])
#
# print(duplicate(list))
# removing duplicated from list
# res=[]
# for i in l:
# if i not in res:
# [Link](i)
# print(res)
#iterartor example
# nums=[1,2,3,4]
# it=iter(nums)
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
#find second highest no in given list
# list1 = [10, 20, 4, 45, 99]
# [Link]()
# print("Second largest element is:", list1[-2])
list1=[55,6,7,33,12]
#.sort list without using 'sort'function.
# unsorted_list = [3, 1, 0, 9, 4]
# sorted_list = []
#
# while unsorted_list:
# minimum = unsorted_list[0]
# for item in unsorted_list:
# if item < minimum:
# minimum = item
# sorted_list.append(minimum)
# unsorted_list.remove(minimum)
#
# print(sorted_list)
#reverse intergers in python
# number = int(input("Enter the integer number: "))
# revs_number = 0
# while (number > 0):
# remainder = number % 10
# revs_number = (revs_number * 10) + remainder
# number = number // 10
# print(f"The reverse number is : {revs_number}")
# num = 123456
# print(str(num)[::-1])
num=12345
#remove empty tuple from list
# def Remove(tuples):
# tuples = [t for t in tuples if t]
# return tuples
#
# # Driver Code
# tuples = [(), ('ram','15','8'), (), ('laxman',
'sita'),
# ('krishna', 'akbar', '45'), ('',''),()]
# print(Remove(tuples))
# add element in list
# L = (1,2,[3,5])
# L[2].append(4)
# print(L)
#if it is possible to change in nested list L
# L = (1,2,[3,4])
# L[2][1]=5
# print(L)
#how to access dict element
# d = { 1 : {'A','B'} , 2 :'C'}
# print([Link](1))
#factorial prog
# def factorial(n):
# return 1 if (n==0 or n==1) else n* factorial(n-
1)
# print(factorial(5))
# find path of file
# import os
# print('Get current working directory : ',
[Link]())
# print('Get current file name : ', __file__)
#multiply two list
# Python code to demonstrate
# Multiplying two lists
# naive method
# initializing lists
# l1= [1, 3, 4, 6, 8]
# l2 = [4, 5, 6, 2, 10]
#
# res_list = []
# for i in range(0, len(l1)):
# res_list.append(l1[i] * l2[i])
# print(res_list)
l1=[1,2,3,4]
l2=[5,6,7,8]
#remove int char from given string
# string1 = "Geeks123for127geeks"
# res = ''.join([i for i in string1 if not
[Link]()])
# print(res)
#type of tuple having only one element
thistuple = ("apple",)
print(type(thistuple))
#to find occurrence of each character in given string
# Str = “geeksforgeeks
# s1="gaurav"
# def count(s, c):
# res = 0
#
# for i in range(len(s)):
#
# if (s[i] == c):
# res+=1
# return res
#
#
# c = 'g'
# print(count(s1, c))
#deep copy
# import copy
#
# l1=[1,3],[11,13]
# cp=[Link](l1)
# cp[0][0]=6
# print(cp)
# print(l1)
#shallow copy
# l2=[4,5],[8,9]
# sh=[Link](l2)
# sh[0][0]=7
# print(sh)
# print(l2)
#string reverse in 2 ways
# string="my name is gaurav"
# print(string[::-1])
# for i in range(len(string)-1,-1,-1):
# print(string[i],end="")
#print even no using list comprehension
# Python program to print even Numbers in a List
# list of numbers
# list1 = [10, 21, 4, 45, 66, 93]
#
# # using list comprehension
# even_nos = [num for num in list1 if num % 2 == 0]
#
# print("Even numbers in the list: ", even_nos)
# def odd_even (l):
# odd_num=[]
# even_num=[]
# for i in l:
# if i % 2==0:
# even_num.append(i)
# else:
# odd_num.append(i)
# output=[odd_num,even_num]
# return output
# print(odd_even(numbers))
#even_numbers
# nums=[]
# for i in numbers:
# if i%2==0:
# [Link](i)
# print(nums
# #print odd no using list comprehension
# list1 = [11,23,45,23,64,22,11,24]
# #list comprehension
# odd_nos = [num for num in list1 if num % 2 != 0]
# print("Odd numbers : ", odd_nos)
# nums=[]
# for i in numbers:
# if i%2!=0:
# [Link](i)
# print(nums)
# nums=[1,2,3,4,5,6,7]
# new_list=[]
# for i in nums:
# if i%2==0:
# new_list.append(i*2)
# else:
# new_list.append(-i)
# print(new_list)
num=[1,2,3,4,5,6,7,8,9]
#write palidrome programme
# def is_palidrom(word):
# if word==word[::-1]:
# return True
# return False
# print(is_palidrom("naman"))
# print(is_palidrom("horse"))
#addition of two list of element
# l1 = [1, 3, 4, 6, 8]
# l2 = [4, 5, 6, 2, 10]
#
# res_list = []
# for i in range(0, len(l1)):
# res_list.append(l1[i] + l2[i])
#
# print(res_list)
#what is the output
a = enumerate([i for i in range(1,10)])
b = [str(x)+str(y) for x,y in a]
print(b[-1])
#add "_" middle of name
string1="gauravmahalle"
string1=string1[:6]+"_"+string1[6:]
print(string1)
#add "k" replace of only first "a" element
name="gaurav"
print(name[:1]+"k"+name[2:])
name="gaurav"
print([Link]("a","k",1))
def fibonacci(n):
a=0
b=1
if n==1:
print(a)
else:
if n==2:
print(a,b)
else:
print(a,b,end=" ")
for i in range(1,n-2):
c=a+b
a=b
b=c
print(c,end=" ")
fibonacci(20)
#write PYRAMID pattern program ?
# rows = int(input("Enter number of rows: "))
#
# for i in range(rows):
# for j in range(i+1):
# print("* ", end="")
# print("\n")
# add "_" in given string by using split and join
string
a = "this is a string"
a = [Link](" ") # a is converted to a list of
strings.
a = "_".join(a)
print(a)
#remove duplicates from 2 dict
d1 = {(1,1):1 , (2,1):1 , (2,2):1 , (1,2):1}
d2 = {(1,2):1 , (2,2):1}
# for key in d2:
# if key in d1:
# del d1[key]
# print(d1)
#count the element in list
your_list = ["a", "b", "a", "c", "c", "a", "c"]
# def func(s):
# count={}
# for char in s:
# count[char]=[Link](char)
# return count
# print(func(your_list))
#find out max out of element in string
# string = "geeks"
# print(max(string))
#
# # maximum alphabetical character in
# # "raj"
# string = "raj"
# print(max(string))
#sort the numbers
scores = [0,0,1,1,1,0,0,1]
[Link]()
print(scores)
#reverse sring without indexing
# s = 'Python' #initial string
# reversed=''.join(reversed(s))
# print(reversed) #print the reversed string
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
#
# for key in sorted(mydict):
# print(key, mydict[key])
#remove duplicates from two list
a = ["abc", "def", "ijk", "lmn", "opq", "rst", "xyz"]
b = ["ijk", "lmn", "opq", "rst", "123", "456", ]
# for i in b:
# if i in a:
# [Link](i)
# print(a)
a1=['apple', 'mango', 'grapes', 'banana']
a2 = ['cham', 'sun', 'lily', 'rose']
xx=['key1', 'key2']
# a = [{xx[0]: a, xx[1]: b} for a, b in zip(a1, a2)]
# print(a)
# string1="gauravmahalle"
# string1=string1[:6]+"_"+string1[6:]
# print(string1)
a = [1,2,3,4,5]
# print(a[6])
print(a[6:0])
#write doc string
# def add(a,b):
# """this function takes two numbers and return
their sum"""
# return a+b
# print(add.__doc__)#how to see doc string
# exaple of decorator
# def decorator_func(any_funcyion):
# def wrapper_func():
# print("this is awesome function")
# any_funcyion()
# return wrapper_func
#
# @decorator_func
# #@ use for decorater and shortcut also
# #this is awesome function
# def func1():
# print("this is function 1")
# func1()
#how much time take to run a code
#custom decorator
# def decorator(func):
# def inner(a,b):
# if func(a,b):
# return a+b
# return inner
# @decorator
# def addition(a,b):
# return a*b
# print(addition(12,4))
# from functools import wraps
# import time
# def calculate_time(function):
# @wraps(function)
# def wrapper(*args,**kwargs):
# print(f"excution {function.__name__}")
# t1=[Link]()
# return_value=function(*args,**kwargs)
# t2=[Link]()
# total_time=t2-t1
# print(f"this function took {total_time}
seconds")
# return return_value
# return wrapper
#
# @calculate_time
# def sqauare_finder(n):
# return [i**2 for i in range(n+1)]
# print(sqauare_finder(1000))
#decorator in fibonacci_seq:
from functools import wraps
import time
def calculate_time(function):
@wraps(function)
def wrapper(*args,**kwargs):
print(f"excution {function.__name__}")
t1=[Link]()
return_value=function(*args,**kwargs)
t2=[Link]()
total_time=t2-t1
print(f"this function took {total_time}
seconds")
return return_value
return wrapper
@calculate_time
def fibonacci(n):
a=0
b=1
if n==1:
print(a)
else:
if n==2:
print(a,b)
else:
print(a,b,end=" ")
for i in range(1,n-2):
c=a+b
a=b
b=c
print(c,end=" ")
fibonacci(20)
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
# def simpleGeneratorFun():
# yield 1
# yield 2
# yield 3
#
# # Driver code to check above generator function
# for value in simpleGeneratorFun():
# print(value)
#generator in fibonacci
def fib(num):
a = 0
b = 1
for i in range(num):
yield a
a, b = b, a + b
for x in fib(20):
print(x)
# write a class
# class Person:
# def __init__(self, first_name, last_name, age):
#below is instance variable
# self.first_name = first_name
# self.last_name = last_name
# [Link] = age
#
#
# p1 = Person("gaurav", "mahalle", 28)
# print(p1.first_name)
# Python program to remove common elements
# in the two lists using remove method
#simple create empty class
class Geeks:
pass
obj = Geeks()
print(obj)
# Python program showing
# abstract base class work
from abc import ABC, abstractmethod
class Animal(ABC):
def move(self):
pass
class Human(Animal):
def move(self):
print("I can walk and run")
class Snake(Animal):
def move(self):
print("I can crawl")
class Dog(Animal):
def move(self):
print("I can bark")
class Lion(Animal):
def move(self):
print("I can roar")
# Driver code
R = Human()
[Link]()
K = Snake()
[Link]()
R = Dog()
[Link]()
K = Lion()
[Link]()
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part
as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(3, 2)
#polymorphism
class Rabbit():
def age(self):
print("This function determines the age of
Rabbit.")
def color(self):
print("This function determines the color of
Rabbit.")
class Horse():
def age(self):
print("This function determines the age of
Horse.")
def color(self):
print("This function determines the color of
Horse.")
obj1 = Rabbit()
obj2 = Horse()
for type in (obj1, obj2): # creating a loop to
iterate through the obj1, obj2
[Link]()
[Link]()
#mutliple inheritace
#also interviewer asked create two class
# Python Program to depict multiple inheritance
# when method is overridden in both classes
class Class1:
def m(self):
print("In Class1")
class Class2(Class1):
def m(self):
print("In Class2")
class Class3(Class1):
def m(self):
print("In Class3")
class Class4(Class2, Class3):
pass
obj = Class4()
obj.m()
#class method example
class geeks:
course = 'DSA'
def purchase(obj):
print("Puchase course : ", [Link])
[Link] = classmethod([Link])
[Link]()
#static method example
class Mathematics:
def addNumbers(x, y):
return x + y
# create addNumbers static method
[Link] =
staticmethod([Link])
print('The sum is:', [Link](5, 10))
#instance method
# Python program to demonstrate
# classes
class Person:
# init method or constructor
def __init__(self, name):
[Link] = name
# Sample Method
def say_hi(self):
print('Hello, my name is', [Link])
p = Person('Nikhil')
p.say_hi()
#example in mro
# Python program showing
# how MRO works
class A:
def rk(self):
print(" In class A")
class B(A):
def rk(self):
print(" In class B")
r = B()
[Link]()
#prime number prog
# for number in range (1,101):
# if number > 1:
# for i in range (2, number):
# if (number % i) == 0:
# break
# else:
# print (number)
#zero move to last
def moveZeros(l):
return [nonZero for nonZero in l if nonZero != 0]
+ \
[Zero for Zero in l if Zero == 0]
list1 = [1, 2, 0, 0, 0, 0, 11, 7]
print(moveZeros(list1))