Swapnil Saurav

Python Class with Advait
#variables are used to store some values
var1 = 50
var2 = 100
print(var1 + var2)

var1 = 500
var2 = 100
print(var1 + var2)
#Basic

#datatypes: str, int, float, bool, complex
var1 = "HELLO" # str - you have the value in quoation
print(type(var1))
var1 = 100 #without any decimal part - integer(int)
print(type(var1))
var1 = 100.0 #float value
print(type(var1))
var1 = True #bool - False
print(type(var1))
var1 = 5j #complex (python)=imaginary (maths)
var2 = var1 * var1 #implicit conversion into complex since var1 is also complex
print(var2)
print(type(var1))
#
var1 = 100
var2 = 3.5
var3 = var1 + var2 #implicit conversion into float since var2 is a float
print()

str1 = "55"
str1 = int(str1) #explicit conversion
#int(), str(), float(), bool(), complex()
var1 = 0;var1 = bool(var1);print(var1); #False - bool

var1 = "";
var1 = bool(var1);
print(var1) ; #False - bool


len = float(input("Enter length of the rectangle: "))
breadth = float(input("Enter breadth of the rectangle: "))
area = len * breadth
print("Area of the rectangle is ",area)
print(f"Rectangle with length = {len} and breadth = {breadth} has an area of {area:.1f}")

player = "Imbababonbeta"
country = "Zimbabwe"
position = "wicket-keeper"
print(f"Player {player:<16} plays for {country:^10} and is {position:>15} of the team")
player = "Rohit"
country = "India"
position = "captain"
print(f"Player {player:<16} plays for {country:^10} and is {position:>15} of the team")

#Player Imbababonbeta plays for Zimbabwe and is wicket-keeper of the team
#Player Rohit plays for India and is captain of the team


########
## OPERATORS
### ARITHMETIC OPERATORS: + - * /
## input values have to be numeric (int, float, complex)
var1 = 50
var2 = 20
print(var1 + var2)
print(var1 - var2)
print(var1 * var2)
print(var1 / var2)
# ** power, 5 ** 4 => 5 * 5 * 5 * 5
print(var1 ** var2) # 50 to the power of 20

# how to find square root of 21 ?
print(21 ** 0.5) #4.58257569495584
#cube root of 21 =
print(21 ** (1/3))

# // - integer division
print(10 / 3)
print("Integer Division = ",10 // 3)

# % Modulo - remainder
#20 / 3 = 6 + 2/3
print(20 % 3)
print(50 % 30) # 20 is remainder

# Comparison operators: compare the values (bigger/smaller)
# input as numeric and output is BOOL
var1 = 15
var2 = 25
print(var1 > var2) #false
#Arithematic operations: + - * / , **, // and % (modulo)
## input as numbers and output was numbers
#Comparison operators: input are the numbers / output - bool
# > >= < <= == !=
val1 = 30
val2 = 40
val3 = 30
print(val1 > val2) #is leftside val greater than rightside value?
print(val1 > val3) #False
print(val1 >= val3) #is val1 greater than or equal to? - True
print(val1 < val2) #
print(val1 <= val3) #
print(val1 == val3) # == is for asking question, are they equal?
print(val1 == val2) #False
print(val1 != val3) #False
print(val1 != val2) #True

#bool operators - Logical operators : Input and Output- bool
#Prediction 1: Sachin and Laxman are going to do this job - F
#Prediction 2: Sachin or Laxman are going to do this job - T
#Actual: Sachin and Rahul did the job

#AND - even one False will make output False
#OR - even one TRUE will make output True
#NOT - opposite

val1 = 30
val2 = 40
val3 = 30
print("==>: ",val1 > val2 or val1 > val3 and val1 >= val3 or
val1 < val2 and val1 <= val3 or val1 == val3 and val1 == val2 or
val1 != val3 or val1 != val2)
#T

#membership operator - in
print(5 in [2,4,5,6,8])

#bitwise operator - works by converting the numbers to boolean
# binary equivalent of 33 ?
print(bin(33)) #0b100001
print(int(0b101111011111))

# and (&) or (|) >> (right shift) << (left shift)
print(22 & 33) #0
print(33 & 22) #0
print(bin(33), bin(22))
## 33 = 100001
## 22 = 010110
## (&) 000000
## (|) 110111
print(int(0b110111)) #55
print(33 | 22) # 55

##
print(55 >>2)
# 55 = 110111 >> 1 = 11011 >> 1 = 1101
print(int(0b1101)) #13
print(55 << 2) # 110111 << 1 = 1101110 << 1 = 11011100

###
# if - checking conditions
val1 = 30
if val1 > 0:
print("Value is positive")
print("Positive Positive Positive")

print("Thank you for using my program")

# 300 pts
## ? 300
print("You win")
print("You lose")
print("Tied")

#TUPLE - immutable version of List
str1 = "hello"
str2 = 'Good evening' \
'How are you?'
str3 = '''Hello there
hope you are doing good
we shall meet soon'''
str4 = """I am fine
how are you"""

print(str2)
print(str3)
print(type(str1))

#functions (global) v methods (belong to a class)
str1 = "hello"
print(str1.islower())
print(str1.isupper())
#isdigit()
val1 = input("Enter length of the rectangle: ")
if val1.isdigit():
val1 = int(val1)
print(val1)
else:
print("Sorry, this is not a valid number")

name1 = "Sachin Tendulkar"
print(name1.isalpha())
txt1 = "hello@123"
print(txt1.isalnum())

###
str1 = "HellOOO how are YOU?"
print(str1.lower())


#### Build a game - guessing number ####
import random
num = 55
attempt = 0
low,high = 1,100
while True:
#guess = int(input("Enter the number: "))
guess = random.randint(low, high)
attempt+=1
if guess ==num:
print(f"You got it in {attempt} attempts!")
break
elif guess > num:
print(f"Hint: Your value {guess} is higher")
high=guess-1
else:
print(f"Hint: Your value {guess} is lower")
low=guess+1


str1 = "Hello"
print(str1[-1] , str1[len(str1)-1])
print(str1[1])
print("Length = ",len(str1))
# range(a,b,c) - a=initial value, b = ending value, c=increment
# range(2,14,3) - 2,5,8,11
print(str1[0:4], str1[:4])
print(str1[-5:-1], str1[:-1])
# llo
print(str1[2:5], str1[2:])
print(str1[-3:])

vowel_count = 0
str1 = "This is a Sample STATEMENT to test"
for i in str1:
#print("Hello: ",i)
if i in 'aeiouAEOIU':
vowel_count+=1
print(f"Total vowels in '{str1}' is {vowel_count}")

# strings are immutable
str1 = "Hello"
str1=str1[0]+'E'+str1[2:]
print("New str1 = ", str1)

str2 = "This is a Sample STATEMENT to test"
str3="This,is,a,sample,text2,work,on,it"
output1 = str2.split()
output1 = str3.split(',')
print(output1)
print(str2)
print("Index: ",str2.index('i',3,len(str2)))

str4='abcd abc ab a'
#find all indices of b
tot = str4.count('ab')
print("Total bs = ",tot)
srt = 0
for i in range(3):
print(str4.index('ab',srt))
srt=str4.index('ab',srt)+1

### LIST: linear ordered mutable collection
l1 = []
print(type(l1))
l1=[3,"Hello",False,5.0, [2,4,6]]

l1.append(45)

#collection - stores multiple values with single variable name
#List, Tuple, Dictionary and Set
#List - linear collection
l1 = [5,"Hello",False,[4,8,12]]
print(type(l1)) #<class 'list'>

#accessing (similar to strings)
print(l1[1][0])
print(type(l1[1]))
print(l1[-1][1])

l2 = [5.6,"Good Evening"]
print(l1+l2)
print(l2 * 3)
l3=[-1]*10
print(l3)

for i in l1:
print(i)

for i in range(len(l1)):
print(l1[i])

l4=[]
#read the value from the user and if its number only then add to this list
val1 = input("Enter a number: ")
if val1.isdigit():
l4.append(int(val1))
print("After first step, L4 looks like: ",l4)

l5 = []
l5.append(100)
l5.append(200)
l5.insert(1,300) # takes- pos, value
l5.insert(1,400)
print("After addition: ",l5)
l5.pop(2) #input as position(index)
l5.remove(200) #takes values as input
print(l5)

### Stack & Queue ##
## Stack - LIFO data structure

stack=[]
while True:
print("Enter your options: ")
print("1. Display Your Stack")
print("2. Add a member to the stack")
print("3. Remove a member from the stack")
print("4. Exit")
ch=input("Choice : ")
if ch=="1":
print("Content of the stack is:\n",stack)
elif ch=="2":
pass
elif ch=="3":
pass
elif ch=="4":
break
else:
print("Sorry I dont understand you, try again!")

# Queue: First element added is the first one to go - FIFO (First In First Out)
l6 = [100,200,300,400,100,200,300,100,200,100]
print(l6.index(100)) #element
print(l6.index(100, 2)) # element with start position
print(l6.index(100, 5,8)) # element with start and end pos
print("count = ",l6.count(200))

#Deep and Shallow copy
l7 = l6 #Deep copy - 2 names for same set of values
l8 = l6.copy() #creates a duplicate copy -
print("1. L6 = ",l6)
print("1. L7 = ",l7)
print("1. L8 = ",l8)
l6.append(500)
l7.append(600)
l8.append(700)
print("2. L6 = ",l6)
print("2. L7 = ",l7)
print("2. L8 = ",l8)

# list is linear ordered mutable collection
l6[0] = 110 #edit the value unlike string
print(l6)
l7 = [2,4,6,8,10]
print(l6+l7) #l6 and l7 retains original values
l6.extend(l7) #l6 will get l7 values
print(l6)
print("Before Reverse: ",l6)
l6.reverse()
print("After Reverse: ",l6)
l6.sort()
print("After Sort: ",l6)
l6.sort(reverse=True)
print("After Reverse Sort: ",l6)

l6.clear()
print("Last: ",l6)

str1 = "HELLO HOW ARE YOU"
print(str1.split())
print(str1) #didnt change as it is immutable

l6.append(66)
print(l6) #existing list got changed as it is mutable
#Sequential search
list1 = [12,14,8,6,10,20,4,10,16,18,2]
num = 10
count_num=0
count_index = []
for i in range(len(list1)):
if list1[i]==num:
count_num+=1
count_index.append(i)

print(f"Number of values = {count_num} and indices are: {count_index}")

# Binary Search
list1 = [12,14,8,6,10,20,4,10,16,18,2]
list1.sort()


num = 22
first = 0
last = len(list1)-1
isFound = False
while True:
mid = (first+last) // 2
if list1[mid] ==num:
isFound = True
break
elif list1[mid] <num:
first = mid+1
else:
last = mid-1
if first> last:
break

if isFound:
print("Number is in the list")
else:
print("Number is not in the list")

Q_LIST = ["What is 1+3? (a) 4 (b) 8 (c) 2 (d) 10",
"What is 4+3? (a) 5 (b) 7 (c) 12 (d) 16",
"What is 4*3? (a) 6 (b) 8 (c) 12 (d) 16"]
A_LIST = ["A","B","C"]
import random
q_no = random.randint(0,2)
print("Let's play the Quiz!")
print(Q_LIST[q_no])
inp=input("Your answer please (select a/b/c/d) : ")
if inp.upper() ==A_LIST[q_no]:
print("Congratulations! You win")
else:
print("Sorry, thats not right")

### input: 29 3 2023 output: 29th March 2023
months= ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
date_ending = ['st','nd','rd']+17*['th']+['st','nd','rd'] + 7*['th']+['st']
month_val = 3
print(months[3-1])
date = 21
print(str(date)+date_ending[date-1])
#Tuple - linear ordered immutable collection
t1 = ()
print("type 1 = ",type(t1), len(t1))

t1 = (1,)
print("type 1 = ",type(t1), len(t1))
t1 = (1,2,3,4,1,2,3,1,2,1) #packcing
print("type 1 = ",type(t1), len(t1))
print("4th member - ", t1[3])
print("2s = ",t1.count(2))
print("Position of 3 = ",t1.index(3))
t2 = (2,4,6,8)
a,b,c,d = t2 #unpacking
print(c,d,b,a)

# you can convert tuple to list and list to tuple
t2 = list(t2)
t2 = tuple(t2)
# Tuple like String, is immutable
#advantage is - working with Tuples is faster than reading through a list

##### DICTIONARY
# Dictionary - mutable collection of key-value pair
d1 = {}
print(type(d1))
d1 = {"Advait":[45,34,89,81],"Saurav":[12,42,23,44]}
print(d1["Advait"])
d2 = {False: 45,45:"Cricket","Name": "Sachin",10:"Zeeeero"}
# dictionary should have unique keys
print(d2)
d2.update(d1)
print("After Update: ", d2)

print("Only Keys = ",d2.keys())
print("Only Values = ",d2.values())
print("Only Items = ",d2.items())
for j in d2.keys():
print(j," = " ,d2[j])
print("Printing Items: ")
for i,j in d2.items():
print("Key:",i," & Value: ",j)

# to remove: pop(), popitem()
#popitem removes the last updated KEY (not value)
d3 ={1:"Hello",2:"Hola",3:"Namaste",4:"Bon Jor"}
print("D3 = ",d3)
d3.popitem()
print("After Popitem: ",d3)
d3 ={1:"Hello",2:"Hola",3:"Namaste",4:"Bon Jor",1:"Good Morning"}
print("D3 = ",d3)
d3.popitem()
print("2. After Popitem: ",d3)
d3.pop(1)
print("1. After Pop = ",d3)

actors = {"David":32,"Tim":42,"Rebecca":21,"Mary":45}
male = {"David":"LA","Tim":"NY"}
female = {"Rebecca":"SD","Mary":"WS"}
# David who is a male of 32 years lives in LA
for name in actors.keys():
print_sentence=name +" who is a "
for male_city in male.keys():
if name==male_city:
print_sentence+="male of "+str(actors[name]) +" years lives in "+ male[name]

for female_city in female.keys():
if name==female_city:
print_sentence+="female of "+str(actors[name]) +" years lives in "+ female[name]
print(print_sentence)
# $100 – $57
total_amount = 28
#initially
Rs_5 = 2
Rs_2 = 2
Rs_1 = 2+3 #initial 2 plus change of 3
initial_total = 5*Rs_5 + 2 *Rs_2 + 1*Rs_1

yet_to_be_accounted = total_amount – initial_total

print(“yet_to_be_accounted: “,yet_to_be_accounted)
# 12
Rs_5 += yet_to_be_accounted //5
yet_to_be_accounted%=5
Rs_2 += yet_to_be_accounted //2
yet_to_be_accounted%=2
Rs_1 += yet_to_be_accounted

print(“Total Rs 5 stamps = “,Rs_5)
print(“Total Rs 2 stamps = “,Rs_2)
print(“Total Rs 1 stamps = “,Rs_1)
#SETS
A = {1,5,2,6,9}
B = {6,9,11,14,15}
A.add(5)
print(A)

# LIST, TUPLE, SETS => They can be converted to each others form\
l1 = [2,4,6,8,4,6,8,2,6,8]
l1 = list(set(l1))
print(l1)

#they are returning result as a new set, values of A and B will not change
print(A.union(B))
print(A.intersection(B))
print(A.difference(B))

#___update modifies the main set
A.update(B)
print(A)
print(A.intersection_update(B))
print(A.difference_update(B))
# SET - sets - linear unordered mutable collection - doesnt allow duplicate
set1 = {'Apple','Grapes','Banana','Orange'}
print(type(set1))
set1.add('Cherry')
set2 = {"Pineapple","Mango","Apple","Orange"}
# two ways to remove
set1.remove("Banana")
set1.discard("Apple")
#set1.remove("Rose") - if value isnt there throws error
set1.discard("Rose") #doesnt throw error
print("1. Set1: ",set1)
set1.pop()
set1.update(set2) #union
print("2. Set1: ",set1)
set1.clear()
print("3. Set1: ",set1)
### SET FUNCTIONS ####
set1 = {'Apple','Grapes','Banana','Orange'}
set2 = {"Pineapple","Mango","Apple","Orange"}
#UNION
print("UNION")
print(set1 | set2)
print(set1.union(set2))
print("INTERSECTION")
print(set1 & set2)
print(set1.intersection(set2))
print("DIFFERENCE")
print(set1 - set2)
print(set1.difference(set2))
print(set2 - set1)
print(set2.difference(set1))

print("SYMMETRIC DIFFERENCE")
print(set1 ^ set2)
print(set2 ^ set1)
print(set1.symmetric_difference(set2))
#update() will update the values of main set
# set1.union(set2) - this gives a new set as output
# set1.update(set2) - set1 is updated with the values
# union - update()
set1.update(set2)
print(set1)
# intersection: intersection_update()
set1.intersection_update(set2)
print(set1)
# difference_update()
set1.difference_update(set2)
print(set1)
#symmetric_difference_update()
set1.symmetric_difference_update(set2)
print(set1)

# set, list, tuple => they are inter-convertible
list1 = [3,6,9,12,3,6,9,3,6,3]
list1 = list(set(list1))
print(list1)
set1 = {'Apple','Grapes','Banana','Orange'}
set1 = list(set1)
set1.index("Grapes")
set1 = set(set1)
set1 = tuple(set1)
set1 = set(set1)
print(set1.issubset(set2))

#
list1 = [3,6,9,12,3,6,9,3,6,3]
list2 = [3,6,9,12,15]
#does all the elements of list2 present in list1?
t_list1 =set(list1)
if set(list1).issuperset(set(list2)):
print("yes, list2 value exists in list1")
else:
print("No, list2 has additional elements")
# MAP FILTER REDUCE
#MAP – large set of data and you want to apply same formula over all the values
list1 = [-3,-6,-15,0,5,999,67,34]
#find square of all these values
list2 = []
for i in list1:
list2.append(i*i)
print(list2)

# one line function / lambda function

result = list(map(lambda x:x**2,list1))
print(“Map result = “,result)


# FILTER -used to filter out data from a list based on a condition
# logic of the function in filter should be designed such a way that you get either True or False
result = list(filter(lambda x:x>=0,list1))
print(“Filter result = “,result)

#filter out numbers divisible by 3
result = list(filter(lambda x:x%3==0,list1))
print(“2. Filter result = “,result)

#Reduce
#import functools as ft
from functools import reduce
result = reduce(lambda x,y:(x+y)/2, list1)
print(“3. Result from Reduce: “,result)

# function
def my_qs():
print(“Whats your name?”)
print(“How are you today?”)
print(“Where do you live?”)

my_qs()
# function that doesnt take any input argument nor does it return
def mysum1():
a,b,c=10,20,30
sum=a+b+c
print(“Sum is”,sum)
#function with input arguments
def mysum2(a,b,c): #required positional arguments
print(“A,B and C are: “,a,b,c)
sum=a+b+c
#print(“Sum is”,sum)
return sum

out = mysum2(9,18,27)
print(“Out =”,out)


def mysum3(a,b,c=99): #c is default, a & b are required – positional arguments
print(“A,B and C are: “,a,b,c)
sum=a+b+c
#print(“Sum is”,sum)
return sum


out = mysum3(9,18,27)
print(“Out =”,out)

out = mysum3(9,18)
print(“Out =”,out)

# 0, 1,1,2,3,5… fibonacci numbers


def checkvalue(a,b):
global h
print(“H = “,h)
h = 99
print(“2 H = “,h)
if a>b:
return (“is”,a,“a”)
elif b>a:
return (“is”,b,“b”)
else:
return (“not”,)
h=100
result =checkvalue(10,20)

if result[0]==“not”:
print(“Both values are equal”)
else:
print(f”Variable {result[2]} with value {result[1]} is greater”)

# Session on MODULES

#Create a python file with name  p2.py and paste below programs there

 

#Functions
# positional and required
# keyword
# default values
# variable length arguments
def mysum1(a,b):
return a+b

def mymultiple(a,b):
print(“a * b = “,a*b)

def my_sample_func(a,b,c):
print(“A,B,C = “,a,b,c)

def myfunc1(*nums,**details):
“””This is a sample function to demonstrate working of a variable length parameters
Input:
nums: will take all the values as tuple. it can be empty as well
details: store all keyword arguments like a dictionary
Return:
doesnt return anything”””
print(type(nums), type(details)) #tuple, dictionary
for i in nums:
print(i,end=“, “)
print()
for k,v in details.items():
print(k,v)


if __name__ == “__main__”:
myfunc1(23,21,14,12,15,26,name=“Sachin”,age=49,place=“Mumbai”)

myfunc1(name=“Sachin”,age=49,place=“Mumbai”)

#DocString – this is

print(print.__doc__)
print(“===”)
print(input.__doc__)
print(“===”)
print(myfunc1.__doc__)

#Run below programs from different file


#import p2 as Amazing
from p2 import mymultiple, my_sample_func

#decorators

def my_main():
”’ Example of a function inside a function”’
print(“First line in function”)
def my_subfunc():
print(“First line inside sub func”)
print(“Second line in main function”)
my_subfunc()
print(“Third line in main function”)
my_subfunc()
print(“4th line in main function”)
my_main()

def my_fun2():
print(“First line from my_fun2”)

def my_fun3():
print(“First line from my_fun3”)

def my_fun1(var):
print(“First line from my_fun1”)
var()


if __name__ ==“__main__”:
mymultiple(10,20)
my_sample_func(10,50,80)

#calling my_fun2 from my_fun1
my_fun1(my_fun2) #passing function name as parameter
#calling my_fun3 from my_fun1
my_fun1(my_fun3) # passing function name as parameter
#Recursive functions – they call themselves
import time
def myfacto(n):
if n ==1:
return 1
return n * myfacto(n-1)

start1 = time.time()
out = myfacto(9)
end1 = time.time()
print(“Factorial of 10 is: “,out)
print(“Total time taken by recursion is:”,(end1-start1))

def myfacto2(n):
prod = 1
for i in range(1,n+1):
prod*=i
return prod
start2 = time.time()
out = myfacto2(9)
end2 = time.time()
print(“Factorial of 10 using Loops is: “,out)
print(“Total time taken by loop is:”,(end2-start2))

import random
var1 = random.randint(1,100)
print(“random number = “,var1)
print(“random number- between 0 and 1: “,random.random())
list1 = [1,2,3,4,5,6]
list2 = [“Apple”,“Banana”,“Cherry”,“Grapes”,“Guava”,“Mango”]
print(“Rolling the dice: “,random.choice(list2))

from datetime import date,datetime,time,timedelta,timezone, tzinfo
from pytz import timezone
#import datetime
print(“Current time = “,datetime.now())
print(“Yesterdat time = “,datetime.now()-timedelta(days=1))
print(“Today’s date: “,datetime.now().strftime(‘%Y-%m-%d’))
print(“This Month: “,datetime.now().month)
date_utc = datetime.now().replace(tzinfo=timezone(‘UTC’))
print(date_utc)
date_utc = datetime.now().replace(tzinfo=timezone(‘Asia/Kolkata’))
print(date_utc)
date_utc = datetime.now().replace(tzinfo=timezone(‘US/Eastern’))
print(date_utc)
# properties we mean – methods (functions) and variables
# class and object levels

class Books:
num_of_books = 0 #class variable

def __init__(self,title=“”,author=“”): #object method
self.title=title #object variable
self.author=author
Books.num_of_books+=1

def display_book(self):
print(“Title of the book is”,self.title)
print(“Author of the book is”,self.author)
print(“Total books created is”,Books.num_of_books)

@classmethod
def display_classdetails(cls):
print(“Total number of books =”,cls.num_of_books)

b1=Books(“Python Programming”,“Swapnil Saurav”)
#b1.create_book()
b1.display_book()
b2=Books(“Machine Learning”,“Saurav”)
b3=Books(“Retail Management”,“Swapnil”)
b4=Books(“Data Visualization”,“Swapnil”)
#b2.create_book()
b2.display_book()
b1.display_book()
b3.display_classdetails()
b4.display_classdetails()
b1.display_classdetails()
Books.display_classdetails()
b3.display_book()

# add and subtract

class MyMasthsOps:
def __init__(self,a,b):
self.num1 = a
self.num2 = b
def addition(self):
return self.num1 + self.num2
def subtraction(self):
return self.num1 – self.num2

op1 = MyMasthsOps(10,5)
print(“Addition: “,op1.addition())
print(“Subtraction: “,op1.subtraction())
#Class and Objects
class Cart:
items_in_store=[{“item_code”:“100”,“Item_Description”:“Blue color Shirt”,“Cost”:40},
{“item_code”:“101”,“Item_Description”:“Chips Packet”,“Cost”:2},
{“item_code”:“102”,“Item_Description”:“Chocolate Royal”,“Cost”:5},
{“item_code”:“103”,“Item_Description”:“Bread Big packet”,“Cost”:7},
{“item_code”:“104”,“Item_Description”:“Shoes 9C”,“Cost”:30},
{“item_code”:“105”,“Item_Description”:“Carry Bag 9in”,“Cost”:70},
{“item_code”:“106”,“Item_Description”:“Pen Blue Rey”,“Cost”:10}]
def __init__(self):
self.list_of_items=[]

def add_item(self):
available =“N”
temp_dict = {“item_code”:“”,“item_desc”:“”,“price”:0,“quantity”:0}
icode= input(“Enter the item code: “)
for item in Cart.items_in_store:
if icode ==item[‘item_code’]:
available = “Y”
temp_dict[‘item_code’] = item[‘item_code’]
temp_dict[‘item_desc’] = item[‘Item_Description’]
temp_dict[‘price’] = item[‘Cost’]

if available==“Y”:
quan = int(input(“Enter the quantity:”))
temp_dict[‘quantity’] = quan
self.list_of_items.append(temp_dict)
print(“Item has been added to your shopping cart!”)
else:
print(“This item is not available right now!”)

def display_items(self):
for item in self.list_of_items:
print(item)
def mainmenu(self):
print(“Main Menu:”)
print(“1. Add Item to the Cart”)
print(“2. Remove Item from the Cart”)
print(“3. Display the content of the cart”)
print(“4. Exit”)
choice=input(“Enter your choice: “)
return choice

if __name__ == ‘__main__’:
cart1 = Cart()
while True:
ch = cart1.mainmenu()
if ch==“1”:
cart1.add_item()
elif ch==“2”:
pass
elif ch==“3”:
cart1.display_items()
elif ch==“4”:
break
else:
print(“Invalid Option, try again!”)
# CRUD – Create new data, Read existing data, Update (edit the existing data) & Deleting existing data
# RDBMS – relational database management system
# database structure – logical (how we use the database) and physical (actual files that are saved)
# DBA, Database Developers & Database Architect
# DBA – installing and making sure that the databases are up and running

# OLTP (Online Transaction Processing) v OLAP (Online Analytical Processing)
## CRUD – C, U,D=80%, 20% R v 99% – reading

# Table: Students
# ROLLNO NAME GRADE EMAILID PHONE
# 1 Sachin 5 sa@sa.com 123
# 2 Laxman 7 lax@lax.com 231

# Table: Competitions
# COMPID NAME DOC ORG CONTACTNO


#Table: STUDENTCOMPETITIONS
# ID ROLLNO COMPID RANK
class Library:
book_count = 0 #class level variable

# __init__() is automatically called when you create the object
def __init__(self,title,author,price): #object level method
self.title = title #object level variable
self.author = author #object level variable
self.price = price #object level variable
self.copies = –1
Library.book_count +=1 #Library.book_count = Library.book_count + 1

def print_info(self):
print(” Printing Book Info”)
print(“———————-“)
print(“Title = “,self.title)
print(“Author = “,self.author)
print(“Price = “,self.price)

def set_copies(self,copies=10):
self.copies = copies

def get_copies(self):
print(f”Total copies available for the book {self.title} is {self.copies})
return self.copies

b1 = Library(“Strangeness”,“George”, 13.50)
b2 = Library(“Python”,“Swapnil”, 19.50)
b3 = Library(“Machine Learning”,“Advait”, 33.50)


print(b1.book_count)
print(b2.book_count)
print(b3.book_count)
print(Library.book_count)
print(b1.title)
print(b2.title)
print(b3.title)
b3.print_info()
b2.set_copies(7)
b2.get_copies()
if b1.get_copies() <0:
b1.set_copies(5)
b1.get_copies()
Class Calculation
1. use init to assign two variables
2. def add(self) , def sub(self), def mul(self), def div(self)

##Main Program
input a and b
c1 = Calculation(a,b)
create: def menu()
# Exceptions
# example 1: ValueError – when u convert non number to integer

”’
1. Syntax error:
print(“Hello) #SyntaxError: unterminated string literal (detected at line 7)

2. Logical Error: Sum of two numbers
a,b = 4,5
print(a*b)

3. Exceptions: Runtime error
1. int(‘n’) # ValueError: invalid literal for int() with base 10: ‘num’
ZeroDivisionError: division by zero

”’
#WAP to input two numbers and perform their division
try: #try block is used to check the exception
num = int(input(“Enter the numerator: “))
except ValueError: #if there is ValueError, code comes here
print(“You have given an invalid number, resetting it to zero”)
num = 0

except Exception: # if previous exception not valid then it comes here
print(“Sum error has occurred. Exiting the program”)
exit(0)
else: # if there is no error, then comes to else (not mandatory)
print(“You are doing good. No error so far!”)
finally: # error or no error, this is called. again its not mandatory
print(“You are doing good.”)

try:
dem = int(input(“Enter the denominator: “))
except ValueError: #if there is ValueError, code comes here
print(“You have given an invalid number, resetting it to one”)
dem = 1
try:
div = num/dem
except ZeroDivisionError:
print(“Denominator cant be zero!!! We are terminating the program”)
else:
print(“Division of given values is”,div)
# WAP to input and divide two numbers
try:
num = int(input(“Enter the numerator: “))
dem = int(input(“Enter the denominator: “))
divide = num/dem
except ValueError:
print(“Sorry, we cant move ahead because of the invalid number”)

except ZeroDivisionError:
print(“Sorry, we cant move ahead because we cant handle zero as denominator”)
else:
print(“Answer is”,divide)
finally:
print(“thank you for using our calculator. See you soon…”)
# WAP to input and divide two numbers

try:
num = int(input(“Enter the numerator: “))
dem = int(input(“Enter the denominator: “))
divide = num / dem

except ValueError:
print(“Invalid number”)
except Exception:
print(“Some error has occurred. We need to stop”)
else:
print(“Answer is”,divide)
finally:
print(“thank you for using our calculator. See you soon…”)

## Another approach
# WAP to input and divide two numbers
while True:
try:
num = int(input(“Enter the numerator: “))
except ValueError:
print(“Invalid number”)
else:
break

while True:
try:
dem = int(input(“Enter the denominator: “))
except ValueError:
print(“Invalid number”)
else:
if dem ==0:
print(“Denominator cant be zero, enter again!”)
else:
break

divide = num/dem
print(“Answer is”,divide)

## Another approach using our own class
# WAP to input and divide two numbers

#creating by own exception
class ZeroValueError(Exception):
def __init__(self,value):
self.val = value

while True:
try:
num = int(input(“Enter the numerator: “))
except ValueError:
print(“Invalid number”)
else:
break

while True:
try:
dem = int(input(“Enter the denominator: “))
if dem ==0:
raise ZeroValueError(dem)
except ValueError:
print(“Invalid number”)
except ZeroValueError as zde:
print(f”Denominator cant be {zde.val}, enter again!”)
else:
break

divide = num/dem
print(“Answer is”,divide)

#Another approach using Assert method
# WAP to input and divide two numbers

while True:
try:
num = int(input(“Enter the numerator: “))
except ValueError:
print(“Invalid number”)
else:
break

while True:
try:
dem = int(input(“Enter the denominator: “))
if dem ==0:
assert (dem!=0),“Denominator cant be zero, lets stop!”
except ValueError:
print(“Invalid number”)
except AssertionError:
print(“Dont give zero for denominator”)
else:
break

divide = num/dem
print(“Answer is”,divide)
# Files – txt, csv
# r (read mode): only reading, file must be there
# w (write mode): only writing, file needn’t be there (it will be created), previous content gets deleted
# a (append mode): only writing, added on the previous content
# relative path: will not have drive name, can start with / or \\
# absolute path: will start with drive name
filename = “MyPoem.txt”
filename2 = “c:/myfolder/Myfile.txt”
# if file isnt there for read mode:
# FileNotFoundError: [Errno 2] No such file or directory: ‘/MyPack1/MyPoem.txt’
fileobj = open(filename,“w”)

fileobj.close()
”’
Reading & Writing txt files. Modes in which you can open a txt files:
1. r – reading (you cant write to it)
2. w – writing (this will delete previous content and add the new content only)
3. a – append (old data will be ratained and new data is added below)
4. r+ – reading and writing
5. w+ – writing and reading
6. a+ – writing and reading

operations:
reading: read(), readline(), readlines()
writing: write(), writelines()

1. Open the file using a handle to the object
2. whatever you want to do – read/write/
3. Close the file

Absolute path: complete path, with the drive letter: D:\\Files\\file.txt
Relative path: path is mentioned with respect to the python file which has the code: /data/abc.txt

”’

file=“MyLearn.txt”
try:
fileobj = open(file,“r”)
except FileNotFoundError:
fileobj1 = open(file, “w”)
fileobj1.close()
fileobj = open(file, “r”)

content = fileobj.read(10)
print(content)
#seek() – instruction to go to a perticular position
#fileobj.seek(1) #goes to the beginning of the content
content1 = fileobj.readline()
print(“Content after readline:\n,content1)

# read whats for H?
fileobj.seek(0)
content2 = fileobj.readlines()
print(content2)
character = “B”
for sentence in content2:
if sentence[0]==character:
print(sentence)

fileobj.close()

fileobj = open(file,“a”)
inp_content=”’
L: Lion
M: Monkey
N: Needle
O: Opal
P: Peach
”’
fileobj.write(inp_content)
inp_content2 = [‘Q: Queen\n,‘R: Rain\n,‘S: Ship\n,‘T: Teapot’]
fileobj.writelines(inp_content2)
fileobj.close()

### Writing usage
file=“MyLearn.txt”
fileobj = open(file,“a”)
inp_content=”’
L: Lion
M: Monkey
N: Needle
O: Opal
P: Peach
”’
fileobj.write(inp_content)
inp_content2 = [‘Q: Queen\n,‘R: Rain\n,‘S: Ship\n,‘T: Teapot’]
fileobj.writelines(inp_content2)
fileobj.close()
”’
1. Read from the diary
2. Write to the diary

2.
11-JUNE-2023: Today we had singing practice at school

1.
Which date: 11-JUNE-2023
Output: Today we had singing practice at school

”’
import csv
file = “MyData.csv”
fileobj = open(file, mode=“a”, newline=“”)
csvwriter = csv.writer(fileobj, delimiter=“,”,quotechar=‘”‘,quoting=csv.QUOTE_MINIMAL)
while True:
content = []
name=input(“Enter your name:”)
content.append(name)
city=input(“Enter your city: “)
content.append(city)
score=input(“Enter your score:”)
content.append(score)
csvwriter.writerow(content)
ch=input(“Enter any value to continue adding:”)
if len(ch)==0:
break
fileobj.close()

”’ Reading the data from the CSV file”’
fileobj = open(file) # default mode is reading (r)
csvreader = csv.reader(fileobj,delimiter=“,”)
total = 0
for each_row in csvreader:
total+=int(each_row[2])
print(“Total = “,total)
#CSV files reader / writer
# name
# lastname, firstname
import csv
filename = “FruitProduction.csv”
fileobj = open(filename,“w”,newline=“”)
writerobj = csv.writer(fileobj, delimiter=“,”,quotechar=‘”‘,quoting=csv.QUOTE_MINIMAL)
first_row = [‘Year’,‘Apple’,‘Banana’,‘Mango’,‘Oranges’]
second_row = [‘2023’,65,34,29,56]
third_row = [‘2022’,45,29,23,45]
forth_row = [‘2021’,39,29,19,25]
writerobj.writerow(first_row)
writerobj.writerow(second_row)
writerobj.writerow(third_row)
writerobj.writerow(forth_row)
fileobj.close()

fileobj = open(filename) #default read mode
readerobj = csv.reader(fileobj,delimiter=‘,’)
for row in readerobj:
print(row)
fileobj.close()
fileobj = open(filename)
#1. Show to Apple production for last 3 years
readerobj = csv.reader(fileobj,delimiter=‘,’)
print(“Apple production were:”)
for row in readerobj:
print(row[0],“:”,row[1])

fileobj.close()

#Highest production of Mango
fileobj = open(filename)
#2. Highest Mango production
readerobj = csv.reader(fileobj,delimiter=‘,’)
mango_high,year_high = –1,-1

linecount=0
for row in readerobj:
if linecount==0:
linecount+=1
else:
if int(row[3]) > mango_high:
mango_high=int(row[3])
year_high = row[0]
print(“Highest Mango production was”,mango_high,“in the year”,year_high)
fileobj.close()

PostgreSQL Tutorial

# pymysql library connects to MYSQL
# Books
# Publishers

import sqlite3
connection = sqlite3.Connection(‘BOOKSDB.SQLITE’)
cursorobj = connection.cursor()

# SQL – Structured Query Language
# Dropping an already existing table:
#cursorobj.execute(“DROP TABLE Publishers”)

#create a new table:
table1 = ”’
Create Table Publishers(
PUBID INTEGER PRIMARY KEY,
PUBNAME VARCHAR,
PUBCITY VARCHAR
)
”’
#cursorobj.execute(table1) #creates the table
#create a new table:
table2 = ”’
Create Table BOOKS(
BID INTEGER PRIMARY KEY,
TITLE VARCHAR,
AUTHOR VARCHAR,
PUBID INTEGER,
CONSTRAINT fk_pidid_cons Foreign Key (PUBID) References Publishers(PUBID)
)
”’
#cursorobj.execute(table2) #creates the table

# INSERT Commands are used to add data to the tables
insert_data = [‘Insert into Publishers (PubID, PubName, PubCity) values (101, “ABC International”,”New York”)’,
‘Insert into Publishers values (102,”Indigo Publishers”,”New Delhi”)’,
‘Insert into Publishers (PubID, PubCity, PubName) values (105,”Hyderabad”,”Glocal Publishers”)’]

insert_data = [‘Insert into Books values (101,”Python Programming”,”Sachin”,102)’,
‘Insert into Books values (102,”Data Science Learning”,”Rohit”,102)’,
‘Insert into Books values (103,”SQL Programming”,”Virat”,105)’]
for statement in insert_data:
cursorobj.execute(statement)
connection.commit()
# pymysql library connects to MYSQL
# Books
# Publishers

import sqlite3
connection = sqlite3.Connection(‘BOOKSDB.SQLITE’)
cursorobj = connection.cursor()

# SQL – Structured Query Language
# Dropping an already existing table:
#cursorobj.execute(“DROP TABLE Publishers”)

#create a new table:
table1 = ”’
Create Table Publishers(
PUBID INTEGER PRIMARY KEY,
PUBNAME VARCHAR,
PUBCITY VARCHAR
)
”’
#cursorobj.execute(table1) #creates the table
#create a new table:
table2 = ”’
Create Table BOOKS(
BID INTEGER PRIMARY KEY,
TITLE VARCHAR,
AUTHOR VARCHAR,
PUBID INTEGER,
CONSTRAINT fk_pidid_cons Foreign Key (PUBID) References Publishers(PUBID)
)
”’
#cursorobj.execute(table2) #creates the table

# INSERT Commands are used to add data to the tables
insert_data = [‘Insert into Publishers (PubID, PubName, PubCity) values (101, “ABC International”,”New York”)’,
‘Insert into Publishers values (102,”Indigo Publishers”,”New Delhi”)’,
‘Insert into Publishers (PubID, PubCity, PubName) values (105,”Hyderabad”,”Glocal Publishers”)’]

insert_data = [‘Insert into Books values (101,”Python Programming”,”Sachin”,102)’,
‘Insert into Books values (102,”Data Science Learning”,”Rohit”,102)’,
‘Insert into Books values (103,”SQL Programming”,”Virat”,105)’]

”’
for statement in insert_data:
cursorobj.execute(statement)
connection.commit()
”’
# Read data from the database
q1 = “Select * from Publishers”
cursorobj.execute(q1)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
print(row)

q1 = “Select * from Books”
cursorobj.execute(q1)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
print(row)

#UPDATE
q3 =“Update Books Set Author =’Dhoni’ where BID=102 “
cursorobj.execute(q3)
connection.commit()

#DELETE
q3 =“Delete from Publishers where PUBID=101 “
cursorobj.execute(q3)
connection.commit()

q2 = “Select TITLE, PUBNAME, Author from Books t1, Publishers t2 where t1.PUBID=t2.PUBID”
cursorobj.execute(q2)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
#print(row)
print(f”{row[0]} which is written by {row[2]} is published by {row[1]})
”’
Install MYSQL from
https://dev.mysql.com/downloads/mysql/

Installation steps:
https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en/
or check this:
https://www.sqlshack.com/how-to-install-mysql-database-server-8-0-19-on-windows-10/

Components that we need:
1. Server – dont forget the admin (root) password
2. Client – server host, database, database username and password
3. Database
4. Workbench – UI tool to connect to the Server
”’


import pymysql
connection = pymysql.Connection(host=“localhost”,database=“advaitdb”,user=“root”,password=“learnSQL”)
cursorobj = connection.cursor()

# SQL – Structured Query Language
# Dropping an already existing table:
#cursorobj.execute(“DROP TABLE Publishers”)

#create a new table:
table1 = ”’
Create Table advaitdb.Publishers(
PUBID INT PRIMARY KEY,
PUBNAME VARCHAR(15),
PUBCITY VARCHAR(15)
);
”’
#cursorobj.execute(table1) #creates the table
#create a new table:
table2 = ”’
Create Table advaitdb.BOOKS(
BID INT PRIMARY KEY,
TITLE VARCHAR(15),
AUTHOR VARCHAR(15),
PUBID INT,
CONSTRAINT fk_pidid_cons Foreign Key (PUBID) References Publishers(PUBID)
)
”’
#cursorobj.execute(table2) #creates the table
# Alter is used to change the datatype
# Modify to change the current structure
alter_q =“ALTER TABLE publishers Modify Column PUBNAME varchar(40)”
#cursorobj.execute(alter_q)

alter_q =“ALTER TABLE Books Modify Column TITLE varchar(40)”
cursorobj.execute(alter_q)
# INSERT Commands are used to add data to the tables
insert_data = [‘Insert into Publishers (PubID, PubName, PubCity) values (101, “ABC International”,”New York”)’,
‘Insert into Publishers values (102,”Indigo Publishers”,”New Delhi”)’,
‘Insert into Publishers (PubID, PubCity, PubName) values (105,”Hyderabad”,”Glocal Publishers”)’]
”’
for statement in insert_data:
cursorobj.execute(statement)
connection.commit()
”’
insert_data = [‘Insert into Books values (101,”Python Programming”,”Sachin”,102)’,
‘Insert into Books values (102,”Data Science Learning”,”Rohit”,102)’,
‘Insert into Books values (103,”SQL Programming”,”Virat”,105)’]


for statement in insert_data:
cursorobj.execute(statement)
connection.commit()

# Read data from the database
q1 = “Select * from Publishers”
cursorobj.execute(q1)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
print(row)

q1 = “Select * from Books”
cursorobj.execute(q1)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
print(row)

#UPDATE
q3 =“Update Books Set Author =’Dhoni’ where BID=102 “
cursorobj.execute(q3)
connection.commit()

#DELETE
q3 =“Delete from Publishers where PUBID=101 “
cursorobj.execute(q3)
connection.commit()

q2 = “Select TITLE, PUBNAME, Author from Books t1, Publishers t2 where t1.PUBID=t2.PUBID”
cursorobj.execute(q2)
results = cursorobj.fetchall()
print(type(results)) #<class ‘list’>
for row in results:
#print(row)
print(f”{row[0]} which is written by {row[2]} is published by {row[1]})

Learn R Programming

 

var1 = 5

var1 = 50

print(var1)

#[1] 50

print(var1 + var4)

var = 55

var = 55

var4 = 55

#print(var1, var4)

#Error in print.default(var1, var4) : invalid printing digits 55

cat(var1, var4)  #50 55

print(‘var1 + var4’)

cat(‘var1 + var4=’,var1 + var4)

var1 + var4= 105

#class

print(class(var2))  #[1] “list”

#class

var2 <- 6

print(class(var2))   #[1] “numeric”

#class

var2 <- 6

print(class(var2))  #[1] “numeric”

var2 <- 6.0

print(class(var2))  #[1] “numeric”

var2 <- 6L  #”numeric”

print(class(var2))   #[1] “integer”

var2 <- “6L”  #”integer”

print(class(var2))   #[1] “character”

var2 = TRUE

print(class(var2))   ## “logical”

var1 = 10

var2 = 15

print(var1 %% var2)  #modulo – remainder

var1 = 100

print(var1 %% var2)  #modulo – remainder

var1 = 95

var2 = 15

print(var1 %% var2)  #modulo – remainder

var1 = 5

var2 = 15

print(var1 ^ var2)  #power:


var1<- 15

var2 <- 20

var3 <- 15

#Relational Operator / comparison operator – output is Logical

print(var1 > var2)  #is var1 greater than var2? – FALSE

print(var1 >= var3) 

print(var1 <= var3) 

print(var1 == var3) # double = is for asking is it equal?

print(var1 != var3)


#Logical operator- input and output both are logical

#I will do work 1 and work 2 today

#actual – I did only work 1 => No


#I will do work 1 or work 2 today

#actual – I did only work 1 => Yes

print(var1 == var3 | var1 != var3)  #

print(var1 == var3 & var1 != var3)


#CONDITIONAL STATEMENTS

var1 <- 0

# is it positive or not ?

if (var1 >0) {

  print(“Its positive”)

}


if (var1 >0) {

  print(“Its positive”)

} else {

  print(“Its not positive”)

}


if (var1 >0) {

  print(“Its positive”)

} else if (var1<0){

  print(“Its negative”)

} else {

  print(“Its zero”)

}



#Collections: Vectors, Lists, Matrices, Arrays, Factors & DataFrames

#Vectors: will store multiple values of same datatype

vec1 <- c(45,56,36)

print(vec1)


#List: multiple data types

list1 = list(45,56,”Hello”,c(2,4,6))

print(list1)


#Matrix

mat1 = matrix(c(2,2,4,4,6,6,8,8,10,10,11,11) ,nrow=3,ncol = 4,byrow = FALSE)

print(mat1)


#Arrays – more than 2-D

arr1 = array(c(2,2,4,4,6,6,8,8,10,10,11,11),dim=c(2,4,2,2))

print(arr1)



#factors: categorical values

gender = factor(c(“M”,”M”,”M”,’F’,”F”,”F”))

print(class(gender))

print(nlevels(gender))


#DataFrame

players_stats <- data.frame(

  ID= c(10,20,30),

  Name=c(“Sachin”,”Virat”,”Dhoni”)

)

print(players_stats)



#membership:  %in% : check if left side value is in right side or not

cities<- c(“Delhii”,”New York”,”London”)


print(“Delhi” %in% cities)


avg <- 98

## avg: 80: Grade A, 70-80: B, 60-70- C, 50-60 – D, 40-50: E , <40: Failed

if (avg >=80) {

  print(“Grade: A”)

  if (avg>=90){

    print(“You win special certificate!”)

    if (avg>=95) {

      print(“You win medal”)

    }

  }

} else if (avg>=70) {

  print(“Grade: B”)

} else if (avg>=60) {

  print(“Grade: C”)

} else if (avg >=50) {

  print(“Grade: D”)

} else if (avg>=40) {

  print(“Grade: E”)

} else {

  print(“Failed”)

}

 

result = 3

val1 <- switch(result,

               “Grade A”,”Grade B”,”Grade C”,”Grade D”,”Grade E”, “Grade F”)

cat(“Result – “,val1)

 

 

#Loops – to repeat:  

#repeat: keep repeating – break when a condition is met -EXIT Controlled

#while: will check for the condition and then repeat: ENTRY Controlled 

#for (exactly  how many times to run)

 

start = 1

repeat{

  print(start)

  if (start==10){

    break

  }

  start = start+1

}

 

start = 11

while (start <=20) {

  print(start)

  start = start + 1

}

 

#For loop

 

words <- LETTERS[1:5]

for (i in words) {

  print(i)

}

numbers <- seq(1,10,by=3)

for (i in numbers) {

  print(i)

}

 

num = 30

start = 2

isPrime=TRUE

repeat{

  

  if (num%%start==0){

    isPrime = FALSE

    break

  }

  if (start==num-1) {

    break

  }

  start=start+1

}

 

if (isPrime) {

  print(“Number is Prime”)

} else {

  print(“Number is not Prime”)

}

 

 

## Assignment 1: Do the above with WHILE and FOR

## Assignment 2: Extend the same logic (one of the 3) to generate prime numbers

## between 1000 and 1500



for (num in 10:20){

  #print(num)

  num1=53

  Isprime=TRUE

  for (a in 3:(num1-1)) {

    # cat(“testing value a”,a)

    if (num1%%a == 0) {

      Isprime=FALSE

      #print(a)

      #print(“inside Hello”)

      break

    }

  }

  if (Isprime==TRUE){

    print(num)

  }

}

########################


#Built-in function

print() #parameter


myfunc.generatePrime <- function(num) {

  isPrime=TRUE

  for(i in 2:(num-1)) {

    if (num %%i==0) {

      isPrime=FALSE

    }

  }

  if (isPrime){

    print(‘num is prime’) 

  } else {

    print(‘num is not Prime’)

  }

}


val <- mean(1:100)

print(val)


myfunc.generatePrime(30)


myfunc.checkPrime2 <- function(num) {

  isPrime=TRUE

  for(i in 2:(num-1)) {

    if (num %%i==0) {

      isPrime=FALSE

    }

  }

  return(isPrime)

}


output <- myfunc.checkPrime2(53)

if (output){

  print(‘num is prime’) 

} else {

  print(‘num is not Prime’)

}


for (num in 1000:1300) {

  output <- myfunc.checkPrime2(num)

  if (output){

    print(num) 

  }

}

######   #####################  ################

#built in functions

print(seq(10,90))

print(max(10:90))

print(mean(10:90))

 

#user defined functions

sum.func <- function(num1=1, num2=2,num3=4,num4=6) {

  cat(“Number 1 = “,num1)

  cat(“\n Number 2 = “,num2,”\n”)

  cat(“Number 3 = “,num3)

  cat(“\n Number 4 = “,num4,”\n”)

  result = num1 * num2

  print(result)

}

#calling the functions by parameters

sum.func(40,30)

#call by name

sum.func(num2=40,num4=30)

 

## Assignments: Logic built using loops- convert them to

## functions

 

# #####################

a <- “Whats your name”

b <- ‘What\’s your name?’

 

print(paste(a,b,sep = “:”))

 

print(substring(a,2,6))

 

print(tolower(a))

print(toupper(a))

 

vector1 = c(“Monday”, TRUE,5,”Thursday”)

print(vector1)

print(vector1[2])

print(vector1[-2])

print(vector1[-2])

 

print(vector1[c(2,4)])

 

list1 = list(“Monday”, TRUE,5,”Thursday”)

print(list1)

 

library(ggplot2)

dataset2 <- data.frame(city=c(“City A”,”City B”,”City C”),

                       revenue=c(200,220,190))

 

ggplot(dataset2, aes(x=city,y=revenue)) +

  geom_bar(stat=”identity”)

 

##############################

# VECTORS

vec1 <- c(2,4,”HELLO”, 5,6)

print(vec1)

 

#built-in 

vec2 <- 5:50

print(vec2)

 

vec2 <- 5.4:30.8

print(vec2)

 

#start, end and increment by

vec3 <- seq(5,30.2,by=0.9)

print(vec3)

 

vec1 <- c(2,4,”HELLO”, 5,6,9,11)

print(vec1[c(2,3,6)])

 

vec1 <- c(2,4,6,8,10)

vec2 <- c(1,2,1,2,0)

print(vec1 + vec2)

 

vec1 <- c(2,4,6,8,10,12)

vec2 <- c(1,2)

print(vec1 + vec2)

 

vec1 <- c(2,4,16,18,10,12)

vec3 <- sort(vec1)

print(vec3)

vec3 <- sort(vec1, decreasing = TRUE)

print(vec3)

 

## LIST

list1 <- list(55,”Hello”,c(2,4,6), 5.4)

print(list1)

print(list1[c(1,3)])

list2 <- list(33,99)

 

mergedlist <- c(list1,list2)

print(mergedlist)

 

 

###MATRICES

mat1 <- matrix(c(2,4,6,8,10,12),nrow = 3,byrow=FALSE)

print(mat1)

mat2 <- matrix(c(2,4,6,8,10,12),nrow = 3,byrow=TRUE)

print(mat2)

 

print(mat1 + mat2)

print(mat1 – mat2)

 

print(mat1 * mat2)

 

print(mat1 / mat2)

 

## ARRAY

arr1 <- array(c(2:20),dim = c(2,2,2))

print(arr1)

print(arr1[1,2,1])

print(arr1[,2,1])

# c(1,2,1)

 

##  Factors

regions<- factor(c(“N”,”S”,”S”,”W”,”N”,”E”,”E”,”E”))

 

print(is.factor(regions))

 

 

dataset1 <- data.frame(

  quarter = c(“Q1″,”Q2″,”Q3″,”Q4”),

  revenue = c(100,150,200,170),

  fruits = c(“Apple”,”Banana”,”Mango”,”Oranges”)

)

print(dataset1)

shorterrow <- dataset1[2:3,]

print(shorterrow)

print(dataset1[,c(2,3)])

 

setwd(“D:\\dataset”)

dataset <- read.csv(“1_Data_PreProcessing.csv”)

print(dataset)

 

dataset$Salesperson = ifelse(is.na(dataset$Salesperson),

                             ave(dataset$Salesperson,FUN=function(x) mean(x,na.rm=TRUE)),

                             dataset$Salesperson) 

dataset$Quotation = ifelse(is.na(dataset$Quotation),

                             ave(dataset$Quotation,FUN=function(x) mean(x,na.rm=TRUE)),

                             dataset$Quotation) 

#connecting to SQL Server

#ipaddress, username, password, dbname

 

#install and run library – RODBC

#sql_connection = odbcConnect(“SQLSERVERODBC”)

#sqlQuery(sql_connection,”Select * from table1″)

 

#handling the categorical value

dataset$Region = factor(dataset$Region)

 

#step 3: breaking into training and test set

library(caTools)

split = sample.split(dataset$Win, SplitRatio = 0.8)

training_set = subset(dataset,split==TRUE)

test_set = subset(dataset,split==FALSE)

 

#Step 4: Feature Scaling

# to bring dataset in similar range

### 1. divide the column with higher value, inthis case quotation by 1000

### 2. Min-Max Scaling – values ranges between 0 to 1

### 3. Z Score normalization – preferred

training_set[,2:3] = scale(training_set[,2:3])

test_set[,2:3] = scale(test_set[,2:3])

test_set

 

setwd(‘D:\\dataset’)

dataset = read.csv(“2_Marks_Data.csv”)

scatter.smooth(x=dataset$Hours,y=dataset$Marks,main=”Hours Studied v Marks Obtained”)

#split the dataset into training set and test set

library(caTools)

split = sample.split(dataset$Marks, SplitRatio=0.8)

training_set = subset(dataset, split=TRUE)

test_set = subset(dataset, split=FALSE)

 

#create regression object

regressor=lm(formula = Marks~Hours, data = training_set)

summary(regressor)

# y = 20.76 + 7.57x

#

 

# While solving machine learning problem – 

## 1. Is my data in a ready state to run the algorithm

## 2. Run the algorithm and check the values

####  2.1. Is this the best performance of this model (can I improve this model)

####  2.2: Is this the best model

## 3. Evaluate the performance of the algorithm

## RMSE and Rsquare (o to 1) – closer to 1 means best formance

 

## training performance v test performance – over fitting and under fitting

setwd(‘D:\\dataset’)

dataset = read.csv(“2_Marks_Data.csv”)

print(dataset)

scatter.smooth(x=dataset$Hours,y=dataset$Marks,main=”Hours Studied v Marks Obtained”)

#split the dataset into training set and test set

library(caTools)

split = sample.split(dataset$Marks, SplitRatio=0.75)

#training_set = subset(dataset, split=TRUE)

training_set = dataset[split,]

print(training_set)

test_set = dataset[!split,]

print(test_set)

#create regression object

regressor=lm(formula = Marks~Hours, data = training_set)

summary(regressor)

# y = 20.76 + 7.57x

#

 

# While solving machine learning problem – 

## 1. Is my data in a ready state to run the algorithm

## 2. Run the algorithm and check the values

####  2.1. Is this the best performance of this model (can I improve this model)

####  2.2: Is this the best model

## 3. Evaluate the performance of the algorithm

## RMSE and Rsquare (o to 1) – closer to 1 means best formance

 

## training performance v test performance – over fitting and under fitting

 

y_predict = predict(regressor, newdata = test_set)

#y_predict = predict(regressor, newdata = training_set)

comparison = cbind(test_set, y_predict)

print(comparison)

 

mse = mean((comparison$Marks – comparison$y_predict)^2)

print(mse)

library(MLmetrics)

mape.value = MAPE(comparison$y_predict, comparison$Marks)

print(mape.value)

 

 

y_predict = predict(regressor, newdata = training_set)

#y_predict = predict(regressor, newdata = training_set)

comparison = cbind(test_set, y_predict)

print(comparison)

 

mse = mean((comparison$Marks – comparison$y_predict)^2)

print(mse)

library(MLmetrics)

mape.value = MAPE(comparison$y_predict, comparison$Marks)

print(mape.value)

 

Learn Python – Evening Jan 2022 – II
########################
####
str1 = 'HELLO'
str2 = "I am fine"
str3 = '''Where are you going?
How long will you be here?
What are you going to do?'''
str4 = """I am here
I will be here for next 7 days
I am going to just relax and chill"""
print(type(str1),type(str2),type(str3),type(str4))
print(str1)
print(str2)
print(str3)
print(str4)

# What's you name?
str5 = "What's your name?"
print(str5)
#He asked,"Where are you?"
str6 = 'He asked,"Where are you?"'
print(str6)

#He asked,"What's your name?"
#escape sequence \
print('''He asked,"What's your name?"''')
print("He asked,\"What's your name?\"")

print('nnnnn\nnn\tnn')

print("\FOlder\\newfolder")
# \n is used to print newline in python
print("\\n is used to print newline in python")

# \\n will not print newline in python
print("\\\\n will not print newline in python")

str1 = "Hello You"
str2 = "There"
print(str1 + str2)
print(str1 *5)
for i in str1:
print("Hello")

#indexing
print(str1[2])
print("last element: ",str1[4])
print("last element: ",str1[-1])
print("second element: ",str1[-8])
print("ell: ",str1[1:4])
print("ell: ",str1[-8:-5])
print("First 3: ",str1[:3])
print("First 3: ",str1[:-6])
print("Last 3: ",str1[6:])
print("Last 3: ",str1[-3:])

#Methods - exactly same as your functions - only difference is they are linked to a class
import time
str1 = "HELLO"
print(str1.replace("L","X",1))

sub_str = "LL"
str2 = "HELLO HOW WELL ARE YOU LL"
cnt = str2.find(sub_str)
print("Count = ",cnt)

if cnt<0:
print("Sorry, no matching value hence removing")
else:
print("Value found, now replacing")
for i in range(5):
print(". ",end="")
time.sleep(0.5)
print("\n")
print(str2.replace(sub_str,"OOOO"))


out_res = str2.split("LL")
print("Output Result = ",out_res)

out_str = "LL".join(out_res)
print(out_str)

print(str2.title())
print(str2.lower())
print(str2.upper())

str3 = 'hello how well are you ll'
print(str3.islower())
print(str3.isupper())

num1 = input("Enter a number: ")
if num1.isdigit():
num1 = int(num1)
else:
print("Invaid input")

ename = input("Enter your first name: ")
if ename.isalpha():
print("Your name is being saved...")
else:
print("Invaid name")

#WAP to count of vowels in a sentence
para1 = "Work, family, and endless to-do lists can make it tough to find the time to catch up. But you'll never regret taking a break to chat with your friend, Frost reminds us. Everything else will still be there later."
sum=0
for l in para1:
if l=='a' or l=='A' or l=='e' or l=='E' or l=='i' or l=='I' or l=='o' or l=='O' or l=='u' or l=='3':
sum+=1
print("Total vowesl = ",sum)
sum=0
for l in para1.lower():
if l=='a' or l=='e' or l=='i' or l=='o' or l=='u':
sum+=1
print("Total vowesl = ",sum)

sum=0
for l in para1.lower():
if l in 'aeiou':
sum+=1
print("Total vowesl = ",sum)

########## LIST
#LIST
#collection of linear ordered items
list1 = [1,2,3,4,5]
print(type(list1))
print("Size = ",len(list1))

print(list1[0])
print(list1[-1])
print(list1[3])
print(list1[:3])
print(list1[-3:])
print(list1[1:4])

for i in list1:
print(i)

print([2,3,4]+[6,4,9])
print([2,3,4]*3)

str2 = "A B C D A B C A B A "
print(str2.count("D"))
print(list1.count(3))

l1 = [2,4,6,8]
print(l1.append(12))
print(l1)
l1[0]=10
print(l1)

l1.insert(2,15)
print(l1)

# Queue: FIFO
# Stack: LIFO

if 16 in l1:
l1.remove(16) #takes in value to remove
l1.remove(15)
print(l1)
l1.pop(1) #index
print(l1)

#################
while False:
print("Queue is: ",l1)
print("1. Add\n2. Remove\n3. Exit")
ch=input("Enter your choice: ")
if ch=="1":
val = input("Enter the value: ")
l1.append(val)
elif ch=="2":
l1.pop(0)
elif ch=="3":
break
else:
print("Try again!")

while False:
print("Stack is: ",l1)
print("1. Add\n2. Remove\n3. Exit")
ch=input("Enter your choice: ")
if ch=="1":
val = input("Enter the value: ")
l1.append(val)
elif ch=="2":
l1.pop(-1)
elif ch=="3":
break
else:
print("Try again!")

l2 = l1 #they become same
l3 = l1.copy()
print("1. List1 = ",l1)
print("1. List2 = ",l2)
print("1. List3 = ",l3)

l1.append(33)
l2.append(44)
l3.append(55)

print("2. List1 = ",l1)
print("2. List2 = ",l2)
print("2. List3 = ",l3)

l1.extend(l3)
print(l1)
print(l1.count(6))

sum=0
marks=[]
for i in range(3):
m = int(input("Enter marks in subject "+str(i+1)+": "))
marks.append(m)
sum+=m
print("Sum is ",sum, "and average is ",sum/3)
print("Marks obtained is ",marks)

#THREE STUDENTS AND THREE SUBJECTS:
allmarks=[]
for j in range(3):
sum=0
marks=[]
for i in range(3):
m = int(input("Enter marks in subject "+str(i+1)+": "))
marks.append(m)
sum+=m
print("Sum is ",sum, "and average is ",sum/3)
print("Marks obtained is ",marks)

allmarks.append(marks)

print("All the marks are: ",allmarks)

# All the marks are: [[88, 66, 77], [99, 44, 66], [44, 99, 88]]
# find the highest marks of each subject

#Tuple - linear order immutable collection
#strings are also immutable

tuple1 = (1,3,1,4,1,5,1,6)
print(type(tuple1))
print(len(tuple1))
print(tuple1.count(1))
print(tuple1.index(4))
print(tuple1[2])
for i in tuple1:
print(i)
t1 = list(tuple1)
t1.append(55)
t1=tuple(t1)
t2 = (2,4,6,8) #packing
#unpacking
a,b,c,d,e = t2
print(a,b,c,d)
#packing
import numpy as np
x = range(16)
x = np.reshape(x,(8,2))
print(x)
x2 = np.ones((3,3))
print(x2)
x3 = np.full((4,4),11)
print(x3)
x4 = [[1,2,1],[1,1,1],[2,2,2],[3,1,1]]
x4 = np.array(x4)
print(type(x4))
print(x4)

#indexing
print(x4[1:3,1:])
x5 = np.array([[1,2,1],[1,1,1],[2,2,2],[3,1,1]])
print(x4+x5)
print(np.add(x4,x5))
print(x4-x5)
print(np.subtract(x4,x5))
print(x4 * x5)
print(np.multiply(x4,x5))
print(x4 / x5)
print(np.divide(x4,x5))
print(x4 // x5)
print(np.sqrt(x4))
print(np.mean(x4))
print(“Shape of the matrix = “,np.shape(x4))
x6 = [[5],[6],[4]]
print(x4 @ x6) #matrix multiplication
print(np.matmul(x4,x6))



# x=5, y=4
# 3x-2y = 7
# 3x+5y = 35
# A * B = C => B = A inverse * C
A = np.array([[3,-2],[3,5]])
C = np.array([[7],[35]])
#find determinant and if its non zero only then perform inverse
det_A = np.linalg.det(A)
if det_A != 0:
Inv_A = np.linalg.inv(A)
Sol = Inv_A @ C
print(“Solution is: “,Sol)
else:
print(“Solution is not possible”)

# SCIPY
import scipy
#
#Indigo computers how many laptops and desktops to make
# memory chip: 1L+ 2D <=15000
# processing chip: 1L + 1D <=10000
# machine time: 4L + 3D <=25000
# maximize Profit: 750L + 1000D = ?
import numpy as np
from scipy.optimize import minimize, LinearConstraint, linprog
l,d = 1,1
obj = 750*l + 1000*d
#since we are going to minimize, the obj becomes
obj = –750*l –1000*d
obj_list = [-750, –1000]

lhs_constraint_ineq = [[1,2],
[1,1],
[4,3]]
rhs_value=[15000,
10000,
25000]
val_bounds = [(0, float(“inf”)),(0, float(“inf”))]
opt_sol = linprog(c=obj_list, A_ub=lhs_constraint_ineq, b_ub=rhs_value,method=“revised simplex”)
print(opt_sol)


import pandas as pd
data1 = pd.DataFrame([10,20,30,40,50])
print(data1)

data1 = pd.DataFrame([[10, “Sachin”],[20,“Laxman”],[30,“Dhoni”],[40,“Kohli”],[50,“Rohit”]], columns=
[“Roll No”,“Name”],
index=[“Player 1”,“Player 2”,“Player 3”,“Player 4”,“Player 4”])
print(data1)

dataset1 = pd.read_csv(“D:/datasets/ongc.csv”)
print(dataset1)
import pandas as pd
data = [[“Sachin”,“Cricket”,“Mumbai”,19000],[“Virat”,“Cricket”,“Delhi”,10000],
[“Dhoni”,“Cricket”,“Ranchi”,11000],[“Sunil”,“Cricket”,“Mumbai”,8000],
[“Ravi”,“Cricket”,“Mumbai”, 3000]]
data_df = pd.DataFrame(data, columns=[“Name”,“Sports”,“City”,“Runs”],
index=[“A”,“B”,“C”,“D”,“E”])
print(data_df)
print(pd.__version__) #2.0.0
print(data_df.loc[“B”]) # loc & iloc
print(data_df.loc[[“A”,“C”]])

print(data_df.iloc[0])
print(data_df.iloc[0,2]) #(row,col)
print(data_df.iloc[[0,2],2])
print(data_df.iloc[0:3,1:3])
print(data_df.iloc[3:,:2])

print(“Average of Runs scored: “, data_df[“Runs”].mean())
print(“Total Runs scored: “, data_df[“Runs”].sum())
# Axis = 0 is for Rows, Axis = 1 is for Columns
data_df = data_df.drop([“A”], axis=0)
data_df = data_df.drop([“City”], axis=1)
#
data_df = data_df.drop(data_df.index[1])
data_df = data_df[data_df.Name !=“Virat”]
print(“After Drop”)
print(data_df)
import pandas as pd
device_df = pd.read_csv(“D:/datasets/gitdataset/user_device.csv”) # 272 rows x 6 columns
usage_df = pd.read_csv(“D:/datasets/gitdataset/user_usage.csv”) # 240 rows x 4 columns
print(usage_df.head(6))

# merge
usage_device_df = pd.merge(usage_df, device_df,on=“use_id”) # inner
print(“INNER \n,usage_device_df)
usage_device_df = pd.merge(usage_df, device_df,on=“use_id”, how=“left”) # inner
print(“LEFT \n,usage_device_df)
usage_device_df = pd.merge(usage_df, device_df,on=“use_id”, how=“right”) # inner
print(“RIGHT \n,usage_device_df)

usage_device_df = pd.merge(usage_df, device_df,on=“use_id”, how=“outer”) # inner
print(“FULL \n,usage_device_df)

# 272 & 240 – 159 (159 + 113 + 81 = 353)
print(“Number of Rows in Combind tables: “,usage_device_df.shape[0])
print(“Number of Columns in Combind tables: “,usage_device_df.shape[1])

hotels_df = pd.read_csv(“D:/datasets/gitdataset/hotel_bookings.csv”)
print(hotels_df.shape)
print(hotels_df.dtypes)

”’
Data Analytics steps:
1. Collecting data
2. Data cleaning: missing data, outliers
”’
# heatmap to check missing values
import matplotlib.pyplot as plt
import seaborn as sns

cols_30 = hotels_df.columns[:30]
print(cols_30)
sns.heatmap(hotels_df[cols_30].isnull(), cmap=sns.color_palette([“#00FF00”, “#FF0000”]))
plt.show()
data = [[“January”,1500,1900],[“February”,1900,1800],[“March”,1500,1800],[“April”,1000,1500],[“May”, 2300,2500]]
import pandas as pd
data_df = pd.DataFrame(data, columns=[“Month”,“Runs Scored”,“Runs Given Away”])
print(data_df)
print(data_df[“Runs Scored”].mean())
print(data_df[“Runs Given Away”].sum())
print(data_df[data_df[‘Month’]==“March”])
print(data_df[data_df[‘Month’].isin([“January”,“April”,“May”])])
print(data_df.iloc[0])
print(data_df.loc[[0,2,4],[“Month”,“Runs Given Away”]])

#pd.read_csv(“https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/user_device.csv”)
device_df = pd.read_csv(“D:/datasets/gitdataset/user_device.csv”) #(272, 6)
print(device_df.shape)
usage_df = pd.read_csv(“D:/datasets/gitdataset/user_usage.csv”) #(240, 4)
print(usage_df.shape)
new_df = pd.merge(device_df, usage_df,on=“use_id”) #how=inner
print(new_df)

new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“left”) #how=inner
print(new_df)
new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“right”) #how=inner
print(new_df)
new_df = pd.merge(device_df, usage_df,on=“use_id”, how=“outer”) #how=inner
print(new_df)
# 159+81+113 = 353


link = “https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/baseball_game_logs.csv”

import pandas as pd
data_df = pd.read_csv(link)
print(data_df)
# Natural language processing
import pandas as pd
link = “https://raw.githubusercontent.com/swapnilsaurav/OnlineRetail/master/order_reviews.csv”
reviews_df = pd.read_csv(link)


”’
1. convert entire text to lower case
2. decomposition on the text (readable text)
3. convert accent (language specific words) into ASCII value (ignore the error)
4. Tokenization: breaking into words
5. Stop words removal (non helpful)
”’
#review_comment_message
import nltk
import unicodedata
reviews_df = reviews_df[reviews_df[‘review_comment_message’].notnull()].copy()
print(reviews_df[‘review_comment_message’].head())

# Function to translate into English
#pip install googletrans==4.0.0-rc1
”’
from googletrans import Translator
translator = Translator()
reviews_df[‘review_comment_english’] = reviews_df[‘review_comment_message’].apply(lambda x: translator.translate(x,src=”pt”, dest=’en’).text)

print(reviews_df[‘review_comment_english’])
”’
# function to normalize portuguese text
def normalize_text(text):
return unicodedata.normalize(‘NFKD’,text).encode(‘ascii’,errors=‘ignore’).decode(‘utf-8’)
def basic_nlp(text):
text = text.lower() # step 1 – lowercase
# steps 2 and 3
text = normalize_text(text)
# step 4: tokenize
words = set(normalize_text(word) for word in nltk.tokenize.word_tokenize(text))
# step 5: remove stop words (non meaningful words)
STOP_WORDS = nltk.corpus.stopwords.words(‘portuguese’)
words = tuple(w for w in words if w not in STOP_WORDS and w.isalpha())
return words

reviews_df[‘review_comment_words’] = reviews_df[‘review_comment_message’].apply(basic_nlp)
print(“===================”)
print(reviews_df[‘review_comment_words’].head())

# Unigram, bigram, trigram

Learning with P
print('hello')

print(5 +3 )
print('5+3=', 5+3)

var1 = 53
print(type(var1)) #<class 'int'> integer
var1 = '53' # str - string
print(type(var1))

var1 = 53.0 #float
print(type(var1))

var1 = 53j #complex
print(type(var1))

var1 = False #
print(type(var1))

count_of_pens = 23 #variable names can only have alphabets, numbers, _
#variable shouldnt begin with a number
cost_each_pen = 21.23
total_cost = cost_each_pen \
* count_of_pens
print('Cost of each pen is',cost_each_pen,"so for",count_of_pens,"pens, "
"total cost would be",total_cost)

#f-string format string
print(f"Cost of each pen is {cost_each_pen} so for {count_of_pens} pens, total cost would be {total_cost:.1f}")

###################
player= "Rohit"
country = "India"
position = "Captain"
print(f"The Player {player:<15} plays for the country {country:^15} and is {position:>15} of the team")
player= "Mbangawapo"
country = "Zimbabwe"
position = "Wicketkeeper"
print(f"The Player {player:<15} plays for the country {country:^15} and is {position:>15} of the team")

num1 = 5
num2 = 3
#Arithematic Operations
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2) #float output
print(num1 // num2) #integer division (double division)- integer (int)
print(num1 % num2) #remainder - modulo
print(num1 ** num2) #num1 to the power num2

#post office stamp problem for assignment
length = input("Enter length of the rectangle: ")
length = int(length)
print(type(length))
breadth = int(input("Enter breadth of the rectangle: "))
area = length * breadth
perimeter = 2*(length + breadth)
print(f"The rectangle with length {length} and bread {breadth} has an area of {area} and perimeter of {perimeter}")


#Comparison operators: < > <= >= == !=
#input here is variables, output is always bool value
val1=34
val2=34
print("Is val1 less than val2? ", val1 < val2)
print("Is val1 greater than val2? ", val1 > val2)
print("Is val1 less than or equal to val2? ", val1 <= val2)
print("Is val1 greater than or equal to val2? ", val1 >= val2)
print("Is val1 equal to val2? ", val1 == val2)
print("Is val1 not equal to val2? ", val1 != val2)

#Logical operators: and or not: Input is bool and output is also bool
print(val1 < val2 and val1 > val2 or val1 <= val2 and val1 >= val2 and val1 == val2 or val1 != val2)
#in AND - even if you have one false - o/p is False otherwise True
# in OR - even if you have one True - o/p is True otherwise False
print(not val1==val2)

#membership operator: in, not in
print( 5 in [5,10,15,20])
print("a" not in "ABCDE")

marks1 = int(input("Enter the marks in subject 1: "))
marks2 = int(input("Enter the marks in subject 2: "))
marks3 = int(input("Enter the marks in subject 3: "))
total = marks1 + marks2 + marks3
avg = total / 3

print(f"Total marks obtained is {total} and the average is {avg:.2f}")

#Conditional
num1 = -90
if num1 >0:
print("Number is positive")
print("This is second line of if")

if num1 >0:
print("Number is positive")
else:
print("Number is not positive")

if num1 >0:
print("Number is positive")
elif num1 <0:
print("Number is negative")
else:
print("Its Zero")

avg = 80
'''
avg >= 90: Grade A, 80-90: B, 70-80: C, 60-70: D, 50-60:E, 40-50: F and Grade Failed <40
'''
if avg>=90:
print("Grade: A")
elif avg>=80:
print("Grade: B")
elif avg>=70:
print("Grade: C")
elif avg>=60:
print("Grade: D")
elif avg>=50:
print("Grade: E")

elif avg>=40:
print("Grade: F")

else:
print("Grade: FAILED")

if avg>=40:
print("You have passed")

#print - You have passed for all those who got over 40%
avg=99.1
if avg>=40:
print("You have passed")
if avg >= 90:
print("Grade: A")
if avg >=95:
print("You win President's medal")
if avg>=99:
print("WOW")
elif avg >= 80:
print("Grade: B")
elif avg >= 70:
print("Grade: C")
elif avg >= 60:
print("Grade: D")
elif avg >= 50:
print("Grade: E")
else:
print("Grade: F")

else:
print("Grade: FAILED")

#to evaluate an algorithm - we look at Space complexity and Time complexity
# President medal for >95%

num1 = 78
if num1%2==0:
print("Even")
else:
print("Odd")

age=21
nationality = "USA"
if age>21 and nationality=="USA":
print("Vote")

####### LOOPS - repeatition
# for loop: exactly how manytimes to run the loop
# while loop: condition under which to repeat the loop

# range(a,b,c): a= initial value (including), b=end value (excluding), c= increment
#range(3,12,3): 3,6,9
#range(3,13,3): 3,6,9,12

for i in range(3,16,3):
print("HELLO")
print("i = ",i)
for i in range(5):
print("*",end=' ')
print()

'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=' ')
print()

'''
*
* *
* * *
* * * *
* * * * *
'''
for j in range(5):
for i in range(j+1):
print("*",end=' ')
print()

'''
* * * * *
* * * *
* * *
* *
*
'''
for j in range(5):
for i in range(5-j):
print("*",end=' ')
print()

'''
*
* *
* * *
* * * *
* * * * *
'''
for j in range(5):
for i in range(5-j-1):
print(" ",end='')
for k in range(j+1):
print("*",end=' ')
print()


n=5
m=1
for j in range(1,11):
for i in range(1,11):
print(f"{i:>2} * {j:>2} = {j*i:>3}",end=" ")
print()

#### WHILE Loops: no fixed times - based on some condition
i=1
while i<=10:
print(i)
i+=1

#print hello untill user wants
ch='y'
while ch=='y':
print("HELLO")
ch=input("Press y to continue, anyother key to stop: ")
import random
num = random.randint(1,100)
print("==> ",num)
l1="="
total_attempts,max,min=0,0,9999
n=250000
pc = n//100
for i in range(n):
attempt = 0
while True:
guess = int(input("Guess the number: "))
#guess = random.randint(1,100)
attempt +=1 # attempt = attempt + 1
if guess ==num:
print(f"Congratulations! You have guessed it correctly in {attempt} attempts.")
total_attempts +=attempt
if min > attempt:
min = attempt
if max < attempt:
max = attempt

if i%pc==0:
print(i//pc,"% Completed")

break
elif guess > num:
print("Sorry, Actual number is smaller")
else: #guess < num:
#pass
print("Sorry, Actual number is greater")

print("Average number of attempts it took: ",total_attempts/n)
print("Maximum attempt:",max," and minimum attempt:",min)

#########################
######### Attempt 2 ##
import random

#print("==> ",num)
l1="="
total_attempts,max,min=0,0,9999
n=250000
pc = n//100
num = random.randint(1, 100)
for i in range(n):

attempt = 0
start, end = 1, 100
while True:
#guess = int(input("Guess the number: "))
guess = random.randint(start,end)
if guess>100 or guess <1:
continue #takes you to the beginning of the loop
attempt +=1 # attempt = attempt + 1
if guess ==num:
#print(f"Congratulations! You have guessed it correctly in {attempt} attempts.")
total_attempts +=attempt
if min > attempt:
min = attempt
if max < attempt:
max = attempt

if i%pc==0:
print(i//pc,"% Completed")

break
elif guess > num:
#print("Sorry, Actual number is smaller")
end=guess-1
else: #guess < num:
#pass
#print("Sorry, Actual number is greater")
start =guess+1

print("Average number of attempts it took: ",total_attempts/n)
print("Maximum attempt:",max," and minimum attempt:",min)
#Strings
str1 = 'Hello'
str2 = "How are you?"
str3 = """I am fine
I am great
I am amazing"""
str4 = '''I am here'''

print(str3)

print("What's your name?")
print('What\'s your name?')
print(str1 + " "+str2)
print(str1 *5)

for i in str1:
print("Hello")
#subset of the string
str6 = "What's your name?"
print(str6[0])
print(str6[2])
print(len(str6))
print(str6[len(str6) - 1]) #last char
print(str6[len(str6) - 2]) #2nd last char
print(str6[- 1]) #last char
print(str6[- 2]) #2nd last char
print(str6[-len(str6)])

print(str6[:3])
print(str6[-3:])

### Methods
print(str6.index("W"))


str1 = 'How are YOU I AM fine'
#they are immutable - you cant edit them
#str1[0] = 'h' #TypeError: 'str' object does not support item assignment
str1 = 'h'+str1[1:]
print(str1)

#functions are independent - print(), len(), input(), int(), str()
#methods - they are functions written within a class
print(str1.isdigit())

val1 = str(5)#input("Enter a number: ")
if val1.isdigit():
val1 = int(val1)
else:
print("Invalid number! setting val1 to zero")
val1 = 0
print(val1)
str2="Hello123"
print(str2.isalnum())
print(str1.upper()) #isupper()
print(str1.lower())
print(str1.title())

print(str1)
print(str1.split("o")) #default split is done on blank space
l1 = str1.split()
str2 = "|| ||".join(l1)
print(str2)

str3 = "Ioooamooofineooohowoooareoooyouooo?"
str4 = " ".join(str3.split("ooo"))
print(str4)
occ = str3.find("ooo")
print("Occurences = ",occ)
occ = str3.count("ooo")
print("Occurences = ",occ)


start,end=0,len(str3)
for i in range(occ):
po = str3.index('ooo',start,end)
print(po,end=" , ")
start = po+1
print()

# LIST
l1 = []
print(type(l1))
print(len(l1))
l1 = [4,"Hello",8.0,True,[2,4,5],"Fine"]
print(type(l1))
print(len(l1))
print(len(l1[4]))
print(l1[4][1])
#list is mutable (unlike str)
l1[0]= 444
print(l1)

print(l1+l1)
print(l1 *3)
for i in l1[4]:
print(i)

#list methods
#Tuple - immutable version list

t1 = (2,2,4,6,8,10) #packing
a,b,c,d,e,f = t1
#print(a,b,c,d,e,f)
print(type(t1))
print(len(t1))
for i in t1:
print(i," - ",t1)

print(t1[-2:])
#t1[2] = 88
print(t1.index(8))
print(t1.count(2))

t1= list(t1)
t1.append(18)
t1=tuple(t1)

a=(5,88,1,77,99)
b=(5,88,1,77,99)
if a>b:
print(a)
elif b>a:
print(b)
else:
print("both are same")

# List - linear ordered collection
l1=[4,6,8,10,12,8,10,12,8,0,8]
l1.append(55) #add element at the end
print(l1)
l1.insert(3,90)
l1.insert(3,70)
print("2. ",l1)

#
element = 12
if element in l1:
l1.remove(12)
else:
print("Element doesnt exist")

if l1.count(element)<1:
print("Element doesnt exist")
print()
print("3. ",l1)
l1.pop(3)

print("4. ",l1)
print(l1.index(8))
s,e=0,len(l1)
for i in range(l1.count(8)):
inx = l1.index(8,s,e)
print(inx,end=", ")
s=inx+1
print()
print("5. ",l1)

#copy
l2 = l1 #deep copy - (giving another name)
l3 = l1.copy() #shallow copy (photocopy)
print("After copy")
print("L1 = ",l1)
print("L2 = ",l2)
print("L3 = ",l3)
l1.append(101)
l2.append(102)
l3.append(103)
print("After editing")
print("L1 = ",l1)
print("L2 = ",l2)
print("L3 = ",l3)

l1.reverse()
print("Reverse: ",l1)

l1.sort()
print("Sort: ",l1)
l1.sort(reverse=True)
print("Sort R: ",l1)

#stack - LIFO: add using append, remove: pop(-1)
#queue - FIFO: append, pop(0)

# 1,5,8,9,7

#add 5 numbers from the user
sum=0
nums=[]
for i in range(5):
num = int(input("Enter the number: "))
sum+=num
nums.append(num)
print("Sum is ",sum)
print("Printing values: ",nums)

#  [[a,b,c],[x,y,z],[p,q,r]]
master_list = []
for i in range(3):
temp=[]
for j in range(3):
m=int(input("Enter the marks: "))
temp.append(m)
master_list.append(temp)

print("Master list: \n",master_list)

'''
Assignment: Exten the above program to find highest marks for each subject and for
each students. Eg if the marks are: [[66, 77, 88], [98, 87, 76], [45, 65, 76]]
Highest for subject 1 = 98
2 = 87
3 = 88
Highest for Student 1 = 88
2 = 98
3 = 76
'''

# Dictionary - key:value
dict1 = {:,:, :,:}printtype
(dict1[])print
"Hello""Hola"

(dict1)
#deep copy
#shallow copy

(dict1.keys())print
(dict1.items())
i dict1.keys(): (i, dict1[i])
a,b dict1.items(): (a,b)
k dict1.items(): (k)
stats = {:[,,,],:[,,,],:[,,,]}for in
if "Virat"
print
dict3.pop()
print
#Sets
#data structures - collections: String, List, Tuple, Dictionary
#SETS - A B M O C - there is no order
# doesnt allow duplicate

set1 = {2,4,6,8}
print(set1)
#union intersection minus
set2 = {6,8,10,12}
#union
print(set1.union(set2))
print(set1 | set2)
#intersection
print(set1.intersection(set2))
print(set1 & set2)

#difference
print(set1.difference(set2))
print(set1 - set2)
print(set2.difference(set1))
print(set2 - set1)

#symmetric difference
#union of 2 differences
print(set1.symmetric_difference(set2))
print(set1 ^ set2)
print(set1, set2)

#update doesnt give new set, it changes the main set
set1.update(set2)

#union -> update
# {intersection_update, difference_update, symm_diff_update}
print(set1, set2)

set3 = {2,4,10,12}

# sets to list and to tuple
set1 = tuple(set1)
list(set1)
set()