Swapnil Saurav

Quest Learning DS December 2022

Day 1:

a=5
#data type is integer
print(a)
print(type(a))
a='''hello
how are you
I am fine'''
#type is string
print(a)
print(type(a))
a="""hello"""
#type is string
print(a)
print(type(a))

a=5.0
print(a)
print(type(a))

a = True #False
print(a)
print(type(a))

a=5j
print(a);print(type(a));print(a*a)

print("How are you?",end=" -> ")
print("I am doing good.")

quant = 40
price = 10
total_cost = quant * price
print("Product quantity is",quant,"and bought at",price,"will cost total of Rs",total_cost)
print(f"Product quantity is {quant} and bought at {price} will cost total of Rs {total_cost}")

length = 50
breadth = 20
area = length * breadth #calc
#output: A rectangle with length 50 and breadth 20 will have area of area_val and perimter of perimeter_vl

#Operators:
##Arithematic operators + - * / ** (power) // (integer division) % (reminder)
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** b)
print(a // b)
print(a % b)

##Comparison operator: == != > >= < <=
#input as numbers and output will be boolean value
a=10
b=3
print(a==b) #F
print(a!=b) #T
print(a > b)
print(a>=b)
print(a<=b)
print(a<b)

## Logical: and or not
a = 10
b = 3
print(a >b and b !=a) # T and T = T
print( True and True)
print( False and True)
print( False and False)
print( True and False)
print(not a!=b)
print( True or True)
print( False or True)
print( False or False)
print( True or False)

#bitwise: >> << & | ~
a=23
print(bin(a)) #bin - converts to binary( 0b) oct - octal 0c hex - hexadecimal 0x
print(hex(a))

print("23 >> 1: ",23 >> 1) #bitwise: right shift
print("23 >> 2: ",23 >> 2) #bitwise: right shift
print(23 << 2) #bitwise: left shift
print(int(0b1011))
# 10111. 1011

print(" & : ",23 & 12)
# 1 0 1 1 1
# 0 1 1 0 0
#&
#--------------
# 0 0 1 0 0
# 1 1 1 1 1

print(" | : ",23| 12)

a=-5

if a < 0:
print()
print()
print()
b = 6+4
print(b)
print("Thank you 1")

a = -5
if a<0:
print("This is a negative number")
else:
print("This is not a negative number")

a=0
if a<0:
print("Negative number")
elif a>0:
print("Positive number")
else:
print("Zero value")

Video Link Day 1

number = 6

if number<0:
print("Its negative")
elif number>0:
print("its positive")
if number%2==0:
print("Even")
if number%3==0:
print("Divisible by 3 and 2 both")
else:
print("Its divisible by 2 only")
else:
print("Odd")
if number%3==0:
print("Divisible by 3 only")
else:
print("Its not divisible by either 2 or 3")
else:
print("Its zero")

########## LOOP
# FOR Loop
#range(a,b,c): a = starting value (inclusive), b=ending value(exclusive), c=increment
#range(2,8,2): 2,4,6
#range(a,b): c is default 1
#range(3,7): 3,4,5,6
#range(3): a=0, c=1 => 0,1,2
for i in range(3):
print(i)

# While Loop
ch="n"
while ch=='y':
print("I am in While")
ch=input("Input your choice: ")

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):
print("*",end=" ")
print()

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

print("\n\n")
for j in range(5):
for k in range(4-j):
print(" ",end="")
for i in range(j+1):
print("*",end=" ")
print()
choice = "y"
while choice=='y' or choice=='Y':
print("Hello")
choice = input("Enter Y to continue: ")

while True:
print("Hello")
choice = input("Enter Y to continue: ")
print("Hello 2")
if choice == 'B' or choice == 'b':
continue #Take you to the beginning of loop
print("Hello 3")
if choice!='y' and choice!='Y':
break #break which will throw you out of current loop
print("Hello 4")

print("Hello 5")
val1 =input("Enter your name: ")  #reading input given by the user
print(val1)
print(type(val1))

marks1 = input("Enter your marks in subject 1: ")
marks1 = int(marks1)
marks2 = int(input("Enter your marks in subject 2: "))
marks3 = int(input("Enter your marks in subject 3: "))
sum = marks1 +marks2+marks3
print("Total marks obtained is ",sum)
avg = sum/3
print(f"{val1} has scored a total of {sum} marks with an average of {avg:.2f}")

#<class 'str'> str()
#<class 'int'> int()
#<class 'float'> float()
#<class 'complex'> complex()
#<class 'bool'> bool()

###############
choice = input("Do you want milk (Y/N): ")
if choice =='Y' or choice =='y':
print("Give milk")
print("So you want milk tea")

print("Done")
val1 = "Sachin Tendulkar"
marks1 = input("Enter your marks in subject 1: ")
marks1 = int(marks1)
marks2 = int(input("Enter your marks in subject 2: "))
marks3 = int(input("Enter your marks in subject 3: "))
sum = marks1 +marks2+marks3
print("Total marks obtained is ",sum)
avg = sum/3
print(f"{val1} has scored a total of {sum} marks with an average of {avg:.2f}")

if avg >=90:
print("Congratulations, you won President Medal")

#if avg >=40, Pass and its not then say Fail
if avg >=40:
print("Result: PASS")
else: #default condition , executed only when if is false
print("Result: FAIL")


'''
80 to 100: Grade A - IF
70 to 80: Grade B - ELIF
60 to 70: Grade C - ELIF
50 to 60: Grade D - ELIF
40 to 50: Grade E - ELIF
<40: Grade F - ELSE
'''
#avg = 90
if avg>=80:
print("Grade: A")
elif avg>=70:
print("Grade: B")
elif avg>=60:
print("Grade: C")
elif avg>=50:
print("Grade: D")
elif avg>=40:
print("Grade: E")
else:
print("Grade: F")

number = 11
if number %2==0:
print("Its an even number")
else:
print("Its an odd number")
number = int(input("Enter a number: "))
if number <0:
print("Its a negative number")
elif number >0:
print("Its a positive number")
if number %2==0:
print("Its an even number")
if number %3 ==0:
print("Its divisible by both 2 and 3")
else:
print("Its an odd number")
else:
print("Its Zero")


number = 5
if number %5==0 and number %3==0:
print("Number is divisible by both 5 and 3")
else:
print("Its neither divisible 5 nor 3")

if number %5==0:
if number%3 ==0:
print("Divisible by both 5 and 3")
else:
print("Divisible only by 5")
else:
if number%3 ==0:
print("Divisible by only 3")
else:
print("Its neither divisible 5 nor 3")


if number ==0:
print("Zero")
else:
print("Its either positive or negative")

# Loops : FOR - you know how many times (boil water for 2 min)
#range(a,b,c): a is the starting value, b is the ending value minus 1 (UPTO), c increment
#range(2,8,2): 2,4,6
#range(2,5): 2 values these are a and b, c is default =1 || 2,3,4
#range(3) : 1 value indicate b, default a=0,c=1 || 0,1,2

#WAP to generate first 10 natural numbers
for i in range(10):
if i==9:
print(i)
else:
print(i, end=', ')


#Loops: WHILE - you know until when (boil water till you see bubble)

counter = -11
while counter <=10:
print(counter)
counter+= 1 # a = a X 5 => a X= 5



# Sum of first 10 natural numbers
sum=0
for i in range(1,11):
sum+=i # sum = sum + i
print("Sum from For loop: ",sum)

# Sum of first 10 natural numbers
sum=0
counter = 1
while counter <=10:
sum+=counter
counter+=1
print("Sum from While loop: ",sum)
 
str1 = 'hello'
str2 = "hi"
str3 = '''Hello there'''
str4 = """Good evening"""
print(str4[-1])
print(str4[:4])
print(str4[1:4])
print(str4[-3:])
print(str1.count('l'))
print(str4.upper())
print(str1.upper().isupper())
num1 = input("Enter a number: ")

print(num1)
#List
list1 = [2,4,6,8.9,"Hello",True,[2,3,4]]
print(type(list1))
print(list1)
print(type(list1[-1]))
var = list1[-1]
print(list1[-1][0])
print(list1[-3:])
print(len(list1[-1]))

for i in list1:
print(i, end=" , ")
print()
l1 = [2,4,6,8]
l2 = [1,3,5,7]
print((l1+l2)*3)

l1.append(19)
print(l1)
l1.insert(2,"Hello")

l1.pop(0) #index / positive to remove
l1.remove(19) #value to remove
print(l1)
l1[1] = 18
print(l1)

l11 = l1
l21 = l1.copy()
print("1")
print("L1: ",l1)
print("L11: ",l11)
print("L21: ",l21)
l11.append(66)
l1.append(55)
l21.append(66)
print("2")
print("L1: ",l1)
print("L11: ",l11)
print("L21: ",l21)

l1.extend(l11) # l1 = l1+l2
print(l1)
#l1.sort()
l1.reverse()
print(l1)
print(l1.count(66))
print(l1.index(8))
t1 = tuple(l1)
t1 = list(t1)
t1 = (2,4,5)
n1,n2,n3 = t1

t1 = (3,)
print(type(t1))
t1 = (3)
print(type(t1))

dict1 = {55:"Sachin", "Name": "Cricket"}
word = "hello"
guess = "ll"
ind = 0
word1 = word.replace("l","L",1)
print(word1)
for i in range(word.count(guess)):
ind = word.find(guess,ind)
print(ind)
ind=ind+1

word3 = "How are you doing"
l1 = word3.split("o")
print(l1)
word4 = "o".join(l1)
print(word4)

#Strings
word = "hEllo".lower()
print(word)
display_text = "* "*len(word)
print(display_text)
while True:
guess = input("Guess the character: ")
guess = guess[0].lower()

if guess.isalpha():
if guess in word:
ind = 0
for i in range(word.count(guess)):
ind = word.find(guess, ind)
#now time to reveal
#0 - 0, 1-2, 2-4
display_text = display_text[:ind*2] + guess+display_text[ind*2+1:]
ind = ind + 1
print(display_text)

if "*" not in display_text:
print("Congratulations!")
break
else:
print("Given character is not in the original word")
else:
print("Invalid character")

#List
l1 = [2,4,6.5,"Hello",True,[2,4,6]]
l1.append(11)
l1.insert(1,"Good evening")
l1.pop(0) #removes element from the given position
l1.remove(6.5) #value

l2 = l1
l3 = l1.copy
print("Set 1: ")
print("l1 : ",l1)
print("l2 : ",l2)
print("l3 : ",l3)

print("Set 2: ")
print("l1 : ",l1)
print("l2 : ",l2)
print("l3 : ",l3)
print("######")
'''
22
12
2022

22nd December 2022
'''
month_txt = ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
dt_ending = ["st","nd","rd"]+["th"]*17 +["st","nd","rd"]+["th"]*7 +["st"]
date_user = int(input("Enter Date: "))
month_user = int(input("Enter month:"))
year_user = input("Enter the year: ")
display_txt = str(date_user) +dt_ending[date_user-1]+" " + month_txt[month_user-1]+" " +year_user

print(display_txt)

l1 = [5,10,15,20,25,30]
print(len(l1))


sample = [[1,2,3,4,5],
[2,4,6,8,10],
[3,6,9,12,15]]
#dictionary: unordered collection mutable
main_dict = {}
d1 = {"name":"sachin"}
d2 = {"city":"mumbai"}
main_dict.update(d1)
main_dict.update(d2)
key="sports"
val="cricket"
temp={key:val}
main_dict.update(temp)

main_dict2 = main_dict
main_dict3 = main_dict.copy()
print("Set 1")
print("Dict 1: ",main_dict)
print("Dict 2: ",main_dict2)
print("Dict 3: ",main_dict3)
key="marks"
val=[55,44,66,77,88]
temp={key:val}
main_dict.update(temp)
print(main_dict)

print("Set 1")
print("Dict 1: ",main_dict)
print("Dict 2: ",main_dict2)
print("Dict 3: ",main_dict3)

print("Set Mem Loc")
print("Dict 1: ",id(main_dict))
print("Dict 2: ",id(main_dict2))
print("Dict 3: ",id(main_dict3))

main_dict.pop('city')
print("Dict 1: ",main_dict)
main_dict.popitem()
print("Dict 1: ",main_dict)
#keys
for i in main_dict.keys():
print(i)
#values
for i in main_dict.values():
print(i)
#items
for i,j in main_dict.items():
print(i," : ",j)
# List functions

### MAP
list1 = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29]
#find cube of all these values

result = list(map(lambda x:x**3,list1))
print("Result = ",result)

### FILTER
result = filter(lambda x:x>=15,list1)
print("Filtered values: ",list(result))

### REDUCE
from functools import reduce
result = reduce(lambda x,y:x+y,list1)
print("Sum is ",result)

result = reduce(lambda x,y:x+y,[1,2,3,4,5,6,7])
print("Sum is ",result)

# 1,2,3,4,5,6,7 =
## 1. x=1, y=2 , x+y = 3
## 2. x=3, y=3, x+y=6
## 3. x=6, y=4, x+y = 10
## 4. x=10, y=5 = 15
## 5. x=15, y=6 = 21
## 6. x=21,y=7 = 28

#how to connect to the database from Python
#SQLITE3 - installed on local machine, nobody can connect from outside
import sqlite3

con_str = sqlite3.connect("classnotes.db")
cursor = con_str.cursor()
q1 = '''Create table Notes(
ID int primary key,
description text,
subject varchar(30))'''
#cursor.execute(q1)

q2 = '''Insert into Notes(ID, Description, Subject)
values(2,"This is a sample Maths notes to perform sone action",'MATHS')'''
#cursor.execute(q2)

q4 = '''UPDATE Notes set subject='Science' where ID=2 '''
cursor.execute(q4)
q4 = '''DELETE From Notes where ID=1 '''
cursor.execute(q4)

con_str.commit()
q3 = '''Select * from Notes'''
recordset = cursor.execute(q3)
#print(list(recordset))
for i in recordset:
for j in i:
print(j,end=" ")
print()

con_str.close()

##########
a=10
b=10
c =a/b
print("A/B = ",c) #ZeroDivisionError: division by zero
num1 = 0
num2 = 0
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))

except ValueError:
#print("We cant proceed further because input is not valid")
print("Invalid input, setting both the numbers to zero")

finally:
sum = num1 + num2
print("Sum is ", sum)
print("Thank you for using this program. See you soon")


#ValueError: invalid literal for int() with base 10: '8t'
Data Analytics – November 2022

Assignment

Develop

1. Library Management System – think of different tables it can have and also add columns to those tables

2. Add constraints to columns as applicable

3. Add data types to each column

4. Add atleast 5 sample data to each table

 

SQL Server 

 

DATATYPES:

.Approximate numeric data types (Float)

This data type is used to store floating-point and real values. It is mainly used in scientific calculations.

Date and Time data types

We use these data types to hold the temporal values such as date and time, including time offset in a column.

Character string data type

This data type allows us to define the character data type only, which can be fixed or variable in length.

Unicode character string data types

This data type allows us to define the full range of Unicode character sets encoded in the UTF-16 character set.

Binary data types

This data type allows storing image, audio, and video files of fixed and variable length into a database location. It stores information in 0 and 1 format.

 

Creating a table

— Creating a table

Create Table Library.dbo.Members(

MemberID INT IDENTITY PRIMARY KEY,

Full_name Varchar(40) NOT NULL,

Phone char(10),

emailid Varchar(20)

)

 

— Create table databasename.schemaname.tablename()

— Within the bracket we need to give the column names and the data types

— Add constraints if any: Primary Key

— We can use Identity to generate unique integer values: SQL SERVER

 
Deleting a table and creating it again

USE [Library]

GO

 

/****** Object:  Table [dbo].[BOOKS]    Script Date: 24-11-2022 07:04:04 ******/

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BOOKS]’) AND type in (N’U’))

DROP TABLE [dbo].[BOOKS]

GO

/****** Object:  Table [dbo].[BOOKS]    Script Date: 24-11-2022 07:03:22 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

CREATE TABLE [dbo].[BOOKS](

[BOOKID] [int] IDENTITY PRIMARY KEY,

[BTITLE] [nchar](10) NULL,

[AUTHOR] [nchar](10) NULL,

[COST] [real] NULL

GO

Codd’s Rules (defines RDBMS systems)

  • Rule 1 Information rule: information needs to be stored in a table format and each cell has to have one unique data => Table format
  • Rule 2 Guaranteed access: Each single data has to be accessible => each table has a primary key
  • Rule 3 Handling NULL values uniformly for all tables: data missing/not known/not applicable
  • Rule 4 Active online catalog: Data Dictionary (managed by system) should have all the information about metadata. => sys.objects in MSSS
  • Rule 5 comprehensive sub-language rule: database language to access data in a linear syntax format => SQL
  • Rule 6 Updating Rule (about Table): data needs to be updatable  => Update/Delete/Alter
  • Rule 7 Insert, Update, Delete available (Database)  => UNION,INTERSECTION etc
  • Rule 8 Physical data independence: can only be changed from within the database. No external factor can change the stored data. 
  • Rule 9 Logical data independence: Application should not be impacted by any change in the database
  • Rule 10 Integrity independence: database design can not be influenced by anyother team
  • Rule 11 Distribution independence: User need/should not know where the data is stored.
  • Rule 12 Non subversion: access to the lowest level => if you have access to a table, you should be able to access all the records/tuples in that table

Design

  • Table
  • Tuple
  • Record
  • Relation instance: group of columns that gives the relationship
  • Employee table: EMP_NAME & EMP_PHONE
  • Schema: Group of tables and other database objects
  • Relation key (KEY): set of columns that will uniquely identify each row
  • EMP_ID, NAME & DOB, Phonenumber & NAME
  • Referential Integrity constraint (FOREIGN KEY): link 2 tables, in current table its called FOREIGN KEY and in Other table, it has to be a Primary Key
 

E R Diagram

Example: (Member entity)

 

Handling Many to Many relationship:

 

Click here to Watch the Video

Home, Assignments and Projects

Homework 1:

Image Search for 3 ER diagrams from internet (preferably related to your domain of interest)

 

Re-draw it and just add 3-4 lines about that ER

 

Assignment 1:

E R diagram: Library Management System and We will later convert these into database

 

Project 1: Develop the conceptual model with an EntityRelationship Diagram (ERD)

1. What are the entities in our database (nouns – these will be the tables) – Draw these as rectangles

2. What are their attributes? (properties/characteristics of an entity that we want to collect and store in the DB) – think about what would uniquely identify a particular instance of the entity)

– Draw these as bubbles off the square

– Underline the attribute(s) that uniquely identifies instance

 

3. What are the relationships between entities? (what is the cardinality of that relationship? (1-1? 1-many? Etc.)

– Draw lines between entities – put a label on the line in a diamond

– Indicate by crow’s feet (or #’s) the cardinality at each end of the relationship

 

E R Diagram Refresher :

Rectangle — Entity

Ellipses — Attribute (underlined attributes are [part of] the primary key)

Double ellipses — multi-valued attribute

Dashed ellipses– derived attribute, e.g. age is derivable from birthdate and current date

Keys:

– Superkey:  an  attribute  or  set  of  attributes  that  uniquely  identifies  an entity–there  can  be  many  of  these

– Composite  key:  a  key  requiring  more  than  one  attribute

– Candidate  key:  a  superkey  such  that  no  proper  subset  of  its  attributes is  also  a  superkey  (minimal  superkey  – has  no  unnecessary attributes)

– Primary  key:  the  candidate  key  chosen  to  be  used  for  identifying entities  and  accessing  records.    Unless  otherwise  noted  “key”  means “primary  key”

– Alternate  key:  a  candidate  key  not  used  for  primary  key

– Secondary  key:  attribute  or  set  of  attributes  commonly  used  for accessing  records,  but  not  necessarily  unique

– Foreign  key:  term  used  in  relational  databases  (but  not  in  the  E-R model)  for  an  attribute  that  is  the  primary  key  of  another  table  and  is used  to  establish  a  relationship  with  that  table  where  it  appears  as  an attribute  also. So  a  foreign  key  value  occurs  in  the  table  and  again  in the  other  table.  This  conflicts  with  the  idea  that  a  value  is stored  only once;  the  idea  that  a  fact  is  stored  once  is  not  undermined.

Using Management Studio:

USE [Library]

GO

 

/****** Object:  Table [dbo].[Transactions]    Script Date: 29-11-2022 06:36:52 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

CREATE TABLE [dbo].[Transactions](

[TID] [smallint] IDENTITY(1,1) NOT NULL,

[MemberID] [int] NOT NULL,

[BookID] [int] NOT NULL,

[IssueDate] [date] NULL,

[ReturnDate] [date] NULL,

 CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED 

(

[TID] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

GO

 

ALTER TABLE [dbo].[Transactions]  WITH CHECK ADD  CONSTRAINT [FK_Transactions_Transactions] FOREIGN KEY([MemberID])

REFERENCES [dbo].[Members] ([MemberID])

GO

 

ALTER TABLE [dbo].[Transactions] CHECK CONSTRAINT [FK_Transactions_Transactions]

GO

 

ALTER TABLE [dbo].[Transactions]  WITH CHECK ADD  CONSTRAINT [FK_Transactions_Transactions1] FOREIGN KEY([BookID])

REFERENCES [dbo].[BOOKS] ([BOOKID])

GO

 

ALTER TABLE [dbo].[Transactions] CHECK CONSTRAINT [FK_Transactions_Transactions1]

GO

 

USING QUERY EDITOR:

 

Create Table BOOKDETAILS (

BDID SMALLINT PRIMARY KEY,

BOOKID INT FOREIGN KEY REFERENCES BOOKS(BOOKID),

CITY varchar(15),

Publisher varchar(15) 

)

Go

— Insert data into the tables

Insert into dbo.Members(Full_name,Phone,emailid) values(‘Sachin’,’23456′,’sachin@sachin.com’)

GO

Insert into dbo.Members(Full_name,Phone,emailid) values(‘Kapil’,’45456′,’kapil@sachin.com’)

GO

 

— Reading is done by Select query

Select MemberID, Full_name from dbo.Members

 

— Practice https://livesql.oracle.com/

 


 

— ALTER is used to change the structure of your table – add, drop, Alter (modify in some versions) table members

 

ALTER TABLE dbo.BOOKS

ADD ISBN char(13)

GO

ALTER TABLE dbo.BOOKS

ADD ISBN_10 char(10)

Go

 

— Drop column ISBN_10

ALTER TABLE dbo.BOOKS

DROP COLUMN ISBN_10

Go

 

— Change the datatype of a column

ALTER TABLE dbo.BOOKS ALTER COLUMN ISBN int

 

— ####################################

— Properties of a Foreign Key

— On DELETE OR UPDATE:

— 1. NO ACTION

— 2. CASCADE

— 3. SET TO NULL

— 4. DEFAULT

 

— DELETE – when value in main table is deleted, it performs above selected option in the secondary table

— UPDATE – when value in main table is updated, it performs above selected option in the secondary table

 

— BOOKS : 1 , 2, 3

 

— Delete : SET TO NULL

— UPDATE : CASCADE

 

ALTER TABLE dbo.BOOKS ALTER COLUMN BTITLE nchar(30)

GO

ALTER TABLE dbo.BOOKS ALTER COLUMN AUTHOR nchar(30)

GO

 

Insert into dbo.Books(BTITLE,AUTHOR) values (‘SQL Programming’,’Sachin’)

 

select * from dbo.BOOKS

go

select * from dbo.members

go

 

select * from dbo.Transactions

go

 

Insert into dbo.Transactions (MemberID,BookID,IssueDate) Values (1,2,GETDATE())

 

Insert into dbo.Transactions (MemberID,BookID,IssueDate) Values (2,2,GETDATE())

 

–Update the existing value in table

Update dbo.Transactions Set BookID = 3 where TID=2

 

 

Update dbo.Members Set MemberID = 100 where MemberID=1

 

Delete from dbo.Members where MemberID=1

DAY 16: using SELECT in SQL  (livesql.oracle.com)

 

select * from hr.employees;

 

Select EMPLOYEE_ID, LAST_NAME, FIRST_NAME, EMAIL, HIRE_DATE from hr.Employees;

 

 

Select EMPLOYEE_ID, LAST_NAME “LASTNAME”, FIRST_NAME, EMAIL, SALARY, HIRE_DATE from hr.Employees;

 

Select EMPLOYEE_ID, LAST_NAME AS LASTNAME, FIRST_NAME, EMAIL, SALARY, HIRE_DATE from hr.Employees;

 

 

Select EMPLOYEE_ID, LAST_NAME “LASTNAME”, FIRST_NAME, EMAIL, SALARY, SALARY*12 “ANNUAL SALARY”, HIRE_DATE from hr.Employees;

 

Select Distinct last_name , first_name from hr.Employees

 

Select Distinct last_name , first_name, COMMISSION_PCT from hr.Employees ORDER BY COMMISSION_PCT

 

Select Distinct last_name , first_name, COMMISSION_PCT from hr.Employees ORDER BY COMMISSION_PCT NULLS FIRST

 

Select first_name || ‘ ‘ || last_name “Employee_Name” from hr.Employees

 

Select first_name || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” from hr.Employees

 

Select FIRST_NAME || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” from hr.Employees Where Department_ID = 60 AND first_name = ‘Alexander’

 

Select first_name || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” , Department_ID from hr.Employees Where Department_ID = 60 OR Department_ID = 90

 

select * from hr.employees;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT >= .2;

 

— order by to sort

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT >= .2 order by COMMISSION_PCT  desc;

 

select first_name, last_name, salary, COMMISSION_PCT, HIRE_DATE from hr.employees where COMMISSION_PCT >= .2 order by HIRE_DATE 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null and rownum <=5;

 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null and rownum <=5 order by COMMISSION_PCT ;

 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null order by COMMISSION_PCT ASC , FIRST_NAME ASC

 

— You can also refer column using a number – 1 indicate first column which is first_name

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null order by COMMISSION_PCT ASC, 1;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where first_name like ‘%d%’ order by COMMISSION_PCT NULLS FIRST

 

— AND : first_name like ‘D%’ and salary > 5000   – MIN RECORD 0  MAX RECORD  10  – COUNT = 5  –  INTERSECTION

— OR  : first_name like ‘D%’ or salary > 5000  – MIN RECORD 20  MAX RECORD  30  – COUNT = 25 – UNION

 

— 10 records where names which starts with D , 20 records which has salary greater than 5000  / 5 rows which are common

 

select count(*) from hr.employees where first_name like ‘D%’ ;  –9

select count(*) from hr.employees where salary >=5000;  –58

select count(*) from hr.employees where salary >=5000 and first_name like ‘D%’  ; — 5

 

select first_name, last_name from hr.employees where salary >=5000

INTERSECT

select first_name, last_name from hr.employees where first_name like ‘D%’;

 

select count(*) from hr.employees where salary >=5000 or first_name like ‘D%’;

select first_name from hr.employees where salary >=5000

UNION

select first_name from hr.employees where first_name like ‘D%’;

 

— OPERATORS in SQL

—  Identity / negation   + –

— Multiplication Division    * /

— Addition, Subtraction, Concatenation    + –  ||

— Comparison operators:     =   !=   <   >   <=    >=  IS NULL   LIKE   BETWEEN   IN

— Logical Operators:   NOT   AND    OR

— Set operators:   UNION   INTERSECT  MINUS

 

select * from hr.employees where salary <0

 

select * from hr.employees  where -salary < 0   — negation

 

select FIRST_NAME, LAST_NAME, Salary*12 Annual_Salary from hr.employees   — Multiplication

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* COMMISSION_PCT Total_Salary , COMMISSION_PCT, Salary  from hr.employees

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where salary between 5000 and 10000 

 

— IT_PROG   AD_VP  (60,90)

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where DEPARTMENT_ID IN (90,60)

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where JOB_ID IN (‘IT_PROG’,’AD_VP’)

 

select * from hr.departments

 

select DEPARTMENT_ID from  hr.departments  where LOCATION_ID in (1700, 1800, 1500)

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name  from hr.employees where DEPARTMENT_ID IN (select DEPARTMENT_ID from  hr.departments  where LOCATION_ID in (1700, 1800, 1500))

 

 

select FIRST_NAME, LAST_NAME, LOCATION_ID , emp.DEPARTMENT_ID from hr.employees emp, hr.departments dept where COMMISSION_PCT is not null and emp.DEPARTMENT_ID = dept.DEPARTMENT_ID

 

— OPERATORS in SQL

 

—  Identity / negation   + –

 

— Multiplication Division    * /

 

— Addition, Subtraction, Concatenation    + –  ||

 

— Comparison operators:     =   !=   <   >   <=    >=  IS NULL   LIKE   BETWEEN   IN  ANY SOME ALL

 

— Logical Operators:   NOT   AND    OR

 

— Set operators:   UNION   INTERSECT  MINUS

 

Select * from hr.employees

 

Select * from hr.employees where salary = ANY (3000,6000)

 

Select * from hr.employees where salary = 3000 or salary =6000

 

Select * from hr.employees where salary = SOME (3000,6000)

 

Select * from hr.employees where salary >= ALL (3000,6000)

 

Select * from hr.employees where salary = 3000 and salary =6000

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

UNION

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

UNION ALL

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

INTERSECT

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

 

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

INTERSECT

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

 

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

MINUS

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

 

— (1,3,5,6) – (2,4,6,7)  =  (1,3,5)

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

MINUS

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

DEFINE salary_val = 3000

Select First_name, last_name from hr.employees where salary = &salary_val

UNDEFINE salary_val

 

— FUNCTIONS – String/text

Select lower(first_name), upper(last_name), initcap(email) from hr.employees

 

select concat(concat(first_name,’ ‘), last_name) from hr.employees — 2 strings

 

— Substring : SUBSTR    returns the position of a char:  INSTR

select first_name, substr(first_name,1,5), instr(upper(first_name),’A’) from hr.employees

 

— RPAD LPAD

 

select RPAD(first_name,12,’.’) || ‘ ‘ || LPAD(last_name,10,’x’)  from hr.employees

 

select RPAD(first_name,9,’ ‘) || ‘ ‘ || LPAD(last_name,9,’ ‘) || ‘ works as ‘ || LPAD(JOB_ID,8,’ ‘) MESSAGE from hr.employees

 

 

— — Number Functions

select * from dual


select sqrt(36) from dual


select distinct sqrt(salary) from hr.employees


select salary + COMMISSION_PCT TOTAL_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, round(salary + COMMISSION_PCT) ROUND_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, trunc(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, ceil(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, floor(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary * -COMMISSION_PCT TOTAL_SALARY, ABS(salary * -COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


Select MOD(19,5) from dual


— — DATE FUNCTIONS

select * from hr.employees


select sysdate from dual


select FIRST_NAME, LAST_NAME, HIRE_DATE, floor(sysdate-hire_date)  from hr.employees


select FIRST_NAME, LAST_NAME, HIRE_DATE,  floor(sysdate-hire_date)  DAYS_SERIVICE, MONTHS_BETWEEN(sysdate,hire_date) MONTHS_SERVICE  from hr.employees


select ADD_MONTHS(sysdate,5) from dual


select NEXT_DAY(sysdate,1)  from dual — date of the first weekday 1 for Sunday, 2 for Monday ….


select NEXT_DAY(sysdate,’FRIDAY’)  from dual — date of the first weekday


select last_day(sysdate)   from dual


select last_day(‘1-Feb-2023’)   from dual


select next_day(‘1-Feb-2023’,2)   from dual


select ADDDATE(day,1,sysdate)   from dual


— year, quarter, month, day


select sysdate + 1 from dual


select DateAdd(sysdate, “1”, 10) from dual



select to_char(sysdate+100, ‘Dy DD-Month-YYYY HH24:MI:SS’) as “Current Time” from dual;


select dayofweek(sysdate) from dual


select now() from dual


Digitalfirm Nov 2022

Day 1:

Installation:

Python:  https://learn.swapnil.pw/python/pythoninstallation

 Pycharm:  https://learn.swapnil.pw/python/pythonides

 R & RStudio:   https://swapnil.pw/uncategorized/installating-r-studio

https://www.mckinsey.com/featured-insights

 

print("terterterg feererg eryey erytey eytytyt",end='\n')
print(10+5);print("10+5+3+1");print(10+5+3+1)
print("10+5+3+1 =",10+5+3+1, "and 5 + 4 + 95 =", 5+4+95);

# \n is used to move the content to new line
print('Hello',end='. ')
print("How are you",end='. ')
print("Thank you",end='\n') #I am printing thank you here
'this is a sample content print("Thank you")'
'''
multiline
text

'''
print(''' this is a sample text''')
print("\n is use for newline") #printing text is 2 different lines
print("\\n is use for newline") # \\ will be read as \

########################################
num1 = 18+4+2+10
print(num1)
print(num1)

print(num1)
print(num1)

quantity = 13
cost = 19
total = quantity * cost
print(total)
#output: The cost of each pen $19 so the total cost of 17 pens will be $323
print("The cost of each pen $",cost,"so the total cost of",quantity,"pens will be $",total)
#using f string - use variables within strings - variable should be in {}
print(f"The cost of each pen ${cost} so the total cost of {quantity} pens will be ${total}")

# basic variables
#integer
#float
#string
#bool
#complex
#data types
a = 50 #int - numbers without decimal
print("a = 50 => ", type(a))
a = 50.0 #float - numbers decimal
print("a = 50.0 => ", type(a))
a = "50" #str - text
print("a = '50' => ", type(a))
a = True # or False - 2 values , bool
print("a = True => ", type(a))
a = 5j #j is square root of -1
print("a = 5j => ", type(a))
print(a*a)

#Operators
print("Arithematic operations")
a=5
b=8
print(a+b)
print(a-b)
print(a*b)
print(b/a) #float as output
print(a**b) #** power/exponential
print(a//b) #integer division
print(b//a) #integer division
print(a%b) # 5
print(b%a)

print("Conditional Operators")
#input as integer/float - output will be bool
a=8 #assignment, assigning the value 5 to a
b=8
print(a>b) #is a greater than b
print(a<b)
print(a>=b)
print(a<=b)
print(a==b) # == asking a question
print(a!=b) #is a not equal to b
#Logical operators: I/P: Bool and O/P: Bool
# P1: Sachin and Dravid will open the batting
# P2: Sachin or Dravid will open the batting
# A: Sachin and Sehwag opened the batting -
#AND - even one condition is FALSE - entire thing would be False
#OR - even one condition is TRUE - entire thing would be TRUE
a = 10
b = 20
print("a>b or b>a and b!=a: ",not(a>b or b>a and b!=a))
print("not b==a: ",not b==a)
# TRUE

#membership: in
l1 = [3,4,5,6,7]
print(l1)
print(type(l1))
print(5 not in l1)

#convert into different number systems
a= 10 #integer - decimal number system
print(bin(a))
b=0b10
print("b = ",int(b))
#hex for hexadecimal (0x5050) and oct for octal (0o) - number systems
print(oct(b))
print(hex(b))
###### example 1
marks1 = 89
marks2 = 90
marks3 = 56
marks4 = 67
marks5 = 78
sum = marks1 + marks2+marks3 + marks4 + marks5
avg = sum/5
print(f"Total marks obtained in 5 subjects is {sum} and average is {avg} %")

###### example 2
marks1 = input("Enter marks in Subject 1: ")
marks1 = int(marks1)
marks2 = int(input("Enter marks in Subject 2: "))
marks3 = 56
marks4 = 67
marks5 = 78
sum = marks1 + marks2+marks3 + marks4 + marks5
avg = sum/5
print(f"Total marks obtained in 5 subjects is {sum} and average is {avg} %")

# Conditional statements
if avg>=50:
print("You have passed")
print("In IF")
print("Hello")
print("hi")
else:
print("You have failed")

print("Thank you")
#
##Assignment 1: Input a number from the user and Check if the number is positive or not
##Assignment 2: Input number of sides from the user and check if its triangle or not
n=4  #s2 = 0 s1 =5
if n<3:
print("Invalid Shape")
elif n==3:
print("Its a triangle")
elif n==4:
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1==s2:
print("Its a square")
if s1==0:
print("Area is not possible")
else:
print("Area is: ",s1*s2)
else:
print("Its a rectangle")
if s1==0:
print("Area is not possible")
else:
if s2==0:
print("Area is not possible")
else:
print("Area is: ",s1*s2)

elif n==5:
print("Its a pentagon")
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1 == s2:
print("Its a square")
if s1 == 0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
else:
print("Its a rectangle")
if s1 == 0 or s2==0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
elif n==6:
print("Its a hexagon")
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1 == s2:
print("Its a square")
if s1 == 0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
else:
print("Its a rectangle")
if s1 == 0:
print("Area is not possible")
elif s2==0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
elif n==7:
print("Its a heptagon")
elif n==8:
print("Its an octagon")
else:
print("Its a complex shape")


#Assignment: Program to find sum and avg of 5 marks
# and assign grade on the basis on:
# avg > 90: A
#avg >75: B
#avg >60: C
#avg >50: D
#avg >40: E
#avg<40: F
#Loops- repeat given block of code

#For loop - exactly how many times to repeat
for i in range(1,10,2): #range(start - included,end-excluded,increment): 1,3,5,7,9
print(i,":Hello")

for i in range(3, 6): # range(start - included,end-excluded,increment=1): 3,4,5
print(i, ":Hello")

for i in range(3): # range(start=0,end-excluded,increment=1): 0,1,2
print(i, ":Hello")
sum=0
for i in range(5):
marks = int(input("Enter marks: "))
sum+=marks
avg = sum/5

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

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

'''
*
* *
* * *
* * * *
* * * * *
'''
#While
i=0
while i<5:
print("Hello")
i+=1

#adding 2 numbers till user says yes
ch='y'
while ch=='y':
a=30
b=50
print("Sum is 80")
ch=input("type y to continue, anyother key to stop: ")



#rewriting same program using While True
while True:
a = 30
b = 50
print("Sum is 80")
ch = input("type y to continue, anyother key to stop: ")
if ch!='y':
break

#lets write a program to print addition of 2 numbers only when they are even
#otherwise ignore, continue till user wants

while True:
n1 = int(input("Enter first number: "))
if n1%2==1:
continue #continue will take you the beginning of the loop
n2 = int(input("Enter second number: "))
if n2 % 2 == 1:
continue
sum = n1 + n2
print("Sum is ",sum)
ch=input("Hit enter to continue, anyother key to stop: ")
if len(ch)!=0:
break #break will throw you out of the loop

Assignments

1.     # Assignment 1: Modify the Total Avg marks calculation program to do it for 5 students
# Assignment 2: Modify your Voting program (eligible to vote or not) to a repeat it for multiple input until
# user wants to continue

  1. Write a Python program that computes the factorial of an integer.
  2. Program to find sum N natural numbers
  3. Write code to display and count the factors of a number
  4. Program to check if eligible to vote in India
  5. Enter marks of 3 subjects for 5 students and grade them. Check for data validity and use BREAK and CONTINUE where necessary
  6. Check the type of a Triangle: Isosceles, Equilateral, Scalene, Right Angle
  7. Input 3 numbers and re-arrange them in ascending order. Use BOOLEAN
#STRINGS
name1 = "Sachin"
#first character
print(name1[0]) #0 is for first character
print(name1[2]) #3rd character
size = len(name1)
print(name1[size-1]) #last character
print(name1[-1]) #last character
print(name1[1:4]) #2,3,4 th characters
print(name1[:3]) #no val on left of : means its zero
print(name1[3:6]) #last 3 characters
print(name1[size-3:size]) #last 3 characters
print(name1[-6:-3]) #first 3 characters
print(name1[-size:3-size]) #first 3 characters
print(name1[-3:]) #last 3 char - no val on right of :mean go till last

print("For loop")
for i in name1:
print(i)

for i in range(len(name1)):
print(f"the chracter at the index {i} is {name1[i]}")

for i in enumerate(name1):
print(i)

for i,j in enumerate(name1):
print(f"the chracter at the index {i} is {j}")

print("S" in name1)
name2 = "Tendulkar"
print(name1 + " " + name2)

print((name1 +" ")* 4)
#STRINGS
name1 = "Sachin"
#first character
print(name1[0]) #0 is for first character
print(name1[2]) #3rd character
size = len(name1)
print(name1[size-1]) #last character
print(name1[-1]) #last character
print(name1[1:4]) #2,3,4 th characters
print(name1[:3]) #no val on left of : means its zero
print(name1[3:6]) #last 3 characters
print(name1[size-3:size]) #last 3 characters
print(name1[-6:-3]) #first 3 characters
print(name1[-size:3-size]) #first 3 characters
print(name1[-3:]) #last 3 char - no val on right of :mean go till last

print("For loop")
for i in name1:
print(i)

for i in range(len(name1)):
print(f"the chracter at the index {i} is {name1[i]}")

for i in enumerate(name1):
print(i)

for i,j in enumerate(name1):
print(f"the chracter at the index {i} is {j}")

print("S" in name1)
name2 = "Tendulkar"
print(name1 + " " + name2)

print((name1 +" ")* 4)
# String methods
val1 = "Sachin 10Dulkar"
print(val1.isalnum())
print(val1.islower())
print(val1.istitle())
val2 = "12345"
print(val2.isdigit())
#lower upper title
print("Second set of functions")
val3 = "how ARE you doiNG todaY?"
print(val3.upper())
print(val3.lower())
print(val3.title())
#find
txt_to_search = "Are"
val4 = val3.lower()
print(val4.find(txt_to_search.lower()))
print(val3.replace("ARE","is"))
val3 = val3.lower().replace("are","is")
print(val3)

#split and join
val3 = "how ARE you are doiNG todaY?"
print(val3.split())
val4 = "HOW|ARE|YOU|DOING|TODAY"
print(val4.replace("|"," "))
val4_list = val4.split("|")
val6_str = " ".join(val4_list)
print(val6_str)
val7 = " how ARE you doiNG todaY? "
val7_strip = val7.strip()
print(val7_strip)
val_cnt = val3.lower().count("area")
print(val_cnt)
# LIST
str1 = "Hello"
print(str1[1])
# str1[1] = "Y" #this is not possible
# strings are called as immutable data types
list1 = [50, 4, 5.5, "Hello", True]
print(type(list1))
print(len(list1))
print(list1[3][2])
print(type(list1[3]))

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

l1 = [1, 2, 3, 4]
l2 = [10, 20, 30]
l3 = l1 + l2
print("Adding two list: ", l3)
print("Multiply: ", l2 * 3)
print(30 not in l2)

print(l2[2])
l2[2] = "Thank You" # lists are mutable
print(l2[2])

sum = 0
marks = []
for i in range(0):
m1 = int(input("Enter marks: "))
sum += m1
marks.append(m1)

print("Total marks", sum)

# append will add at the end
# insert - pos and value: value is added at the given pos
marks.insert(2, 11) # [11
marks.insert(2, 22) # [11,22]
marks.insert(2, 33) # [11,22,33]
marks.insert(2, 44) # [11,22,44,33]
marks.insert(2, 55) # [11,22,55,44,33]
marks.insert(2, 66) # [11,22,66,55,44,33]
marks.insert(2, 77) # [11,22,77,66,55,44,33]
# marks[7] = 100 - error since index 7 isnt there
print("Marks obtained are: ", marks)
# pop - removes from the given position
# remove - removes given value
val_remove = 77
if val_remove in marks:
marks.remove(val_remove)
else:
print("Value is not present in the list")
print("Marks obtained are: ", marks)
pos_remove = 2
if pos_remove < len(marks):
marks.pop(pos_remove)
else:
print("List doesnt have that index")

print("Marks obtained are: ", marks)
marks.clear()
print("Marks obtained are: ", marks)

Assignment


 

Assignments

1. Write a Python program to sum all the items in a list.

2. Write a Python program to multiplies all the items in a list.

3. Write a Python program to get the largest number from a list.

4. Write a Python program to get the smallest number from a list.

5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. 

Sample List : [‘abc’, ‘xyz’, ‘aba’, ‘1221’]

Expected Result : 2

6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. 

Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

7. Write a Python program to remove duplicates from a list.

8. Write a Python program to check a list is empty or not.

9. Write a Python program to clone or copy a list.

10. Write a Python program to find the list of words that are longer than n from a given list of words.

11. Write a Python function that takes two lists and returns True if they have at least one common member.

12. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.

Sample List : [‘Red’, ‘Green’, ‘White’, ‘Black’, ‘Pink’, ‘Yellow’]

Expected Output : [‘Green’, ‘White’, ‘Black’]

13. Write a Python program to generate a 3*4*6 3D array whose each element is *.

14. Write a Python program to print the numbers of a specified list after removing even numbers from it.

15. Write a Python program to shuffle and print a specified list.

16. Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).

17. Write a Python program to generate and print a list except for the first 5 elements, where the values are square of numbers between 1 and 30 (both included).

18. Write a Python program to generate all permutations of a list in Python.

19. Write a Python program to get the difference between the two lists.

20. Write a Python program access the index of a list. 

DAY 8

 

def myreverse(a):
print("A = ", a)
a.reverse()
return a[0]


list1 = [50, 4, 5.5, "Hello", True]
list2 = [90, 20, 50, 40, 30, 70]
list2.reverse()
# print(list2)
print("Myreverse: ", myreverse(list2))
print(list2.reverse())
list2.sort()
# print(list2)
list1.extend(list2)
print("New set: ", list1)
a = "5"
# print(int(a))
print("Learning COPY")
list2 = [90, 20, 50, 40, 30, 70]
list3 = list2 # shallow copy
list4 = list2.copy() # deep copy
print("list2: ", list2)
print("list3: ", list3)
print("list4: ", list4)
list2.append(10)
print("list2: ", list2)
print("list3: ", list3)
print("list4: ", list4)

print("Stack Implementation")
list_master = []
while True:
print("1. Add to the stack")
print("2. Remove from the stack")
print("3. Clear the stack")
print("4. Quit")
op = int(input("Enter your option"))
if op == 1:
val = int(input("Enter the element to add: "))
list_master.append(val)
print("After adding list: ", list_master)
elif op == 2:
if len(list_master) > 0:
list_master.pop(-1)
print("After adding list: ", list_master)
else:
print("List is empty!")
elif op == 3:
list_master.clear()
print("After adding list: ", list_master)
elif op == 4:
print("Thank you for using the program.")
break
else:
print("Invalid option, Try again!")

############### LIST #######################

# TUPLE
t2 = ()
t3=(55,)
t1 = (5, 4, 6, 8, 4)
print(type(t1))
t1 = list(t1)
print(t1.count(8))
# Dictionary
# list: linear ordered mutable collection
# tuple: linear ordered immutable collection
# dictionary: non-linear ordered mutable collection (unordered untill 3.7)
# dictionary is made up of key & value
dict1 = {} # empty dictionary
print(type(dict1))
dict1 = {"Name": "Sachin", "City": "Mumbai", "Runs": 12900, "IsPlaying": False}
print(dict1)
print(dict1["City"])
print(dict1.get("City"))
val = "India"
key = "Country"
t_dict = {key: val}
dict1.update(t_dict)
print("Dictionary after Update: \n", dict1)
print("Size of dictionary: ", len(dict1))

print("keys:", dict1.keys())
for i in dict1.keys():
print(i)
for i in dict1.values():
print(i)
for i in dict1.keys():
print(dict1[i])

for i, j in dict1.items():
print(i)

if "City" in dict1: # default it checks in keys
print("We have City")
if "Mumbai" in dict1.values():
print("We have City Mumbai")
else:
print("Mumbai is not there")

print("Dict1: ", dict1)
dict1.pop("City") # key as input
print("Dict1: ", dict1)
dict1.popitem() # key as input
print("Dict1: ", dict1)
print(type(dict1.values()))
dict1.pop(list(dict1.keys())[list(dict1.values()).index("Sachin")])
# print()
print("Dict1: ", dict1)
#Set - also mutable
set1 = {"New York"}
print(type(set1))
set1.add("Chicago")

#update
#union
s1 = {1,3,5,7,2,4}
s2 = {2,4,6,8}
print("Union: ",s1.union(s2))
print("Union: ",s1 | s2)
#s1.update(s2)
#print("Union Update: ",s1)

#difference
print("difference :",s1-s2)
print("difference :",s2-s1)
print("Difference: ",s1.difference(s2))
#s1.difference_update(s2)
#print("Difference update: ",s1)
print("Symmetric Difference: ", s1 ^ s2)


#intersection
print("intersection :",s1.intersection(s2))
print("intersection: ",s1 & s2)
print("intersection update: ",s1.intersection_update(s2))
print(s1)
s1.intersection_update(s2)
print("intersection update: ",s1)

print(set1)
l1 = [5,10,10,15,15,15,20,20,25]
l1 = list(set(l1))
print(l1)

### Functions



def myfunc1(name): #which takes ONE input argument and doesnt return anything
print("Hello ",name)
print("How are you?")
print("Where are you going?")

def myfunc2(name): #which takes ONE input argument and doesnt return anything
print("Hello ",name)
print("How are you?")
print("Where are you going?")
return "Thank You", "Bye"

def myfunc(): #this is an example which doesnt take any input argument and doesnt return
print("Hello")
print("How are you?")
print("Where are you going?")

myfunc()
print("second time: ")
myfunc1("Kapil") #1 required positional argument: 'name'
print(myfunc2("Sachin"))


#functions

#required positional arguments
## Function definition
def calculate(a,b):
print("Value of a is ",a)
print("Value of b is ",b)
sum = a+b
diff = a-b
mul = a*b
div = a/b
return sum,diff,mul,div

## Function definition - Default argument
def calculate1(a,b=50):
print("Value of a is ",a)
print("Value of b is ",b)
sum = a+b
diff = a-b
mul = a*b
div = a/b
return sum,diff,mul,div

result = calculate(30,20)
print("Addition of given 2 values is ", result[0])
result = calculate1(30,5)
print("Addition of given 2 values is ", result[0])
result = calculate1(30)
print("Addition of given 2 values is ", result[0])
#non positional
result = calculate1(b=30,a=5) #nonpositional => Keyword arguments
print("Addition of given 2 values is ", result[0])

#variable name arguments
def mycalculation(a,c,*b,**d): # * takes multiple values
print("A = ",a)
print("B = ", b)
print("C = ", c)
print("D = ", d)

mycalculation(5,6,7,8,9,10,11,name="Sachin", runs=5000)

def check_prime(a):
result1 = True
for i in range(2,a//2):
if a%i == 0:
result1 = False
break
return result1

result = check_prime(1100)
if result:
print("Its a prime number")
else:
print("Its not a prime number")

#generate prime numbers between 500 and 1000
prime_num = []
for i in range(500,1001):
if check_prime(i):
prime_num.append(i)
print("Prime numbers are: ",prime_num)
#Recursive function
def myfunc(number):
if number <1:
return 0
print(number)
myfunc(number-1)

def factorial(n):
if n<1:
return 1
return n * factorial(n-1)


if __name__ =="__main__":
myfunc(100)
# 5! = 5 * 4 * 3 * 2 * 1!
fact = factorial(5)
print("Factorial is ",fact)
class Person:
population = 0
def welcome(self,name):
self.name = name
print("Welcome to the world")
Person.population+=1

def display(self):
print("Welcome to ",self.name)
print("Total Population: ",Person.population)

p1 = Person()
p1.welcome("Sachin")
p3 = Person()
p3.welcome("Laxman")

p2 = Person()
p4 = Person()
p5 = Person()
p2.welcome("Rekha")
p4.welcome("Geeta")
p5.welcome("Rohit")
p3.display()
p4.display()
class Person():
def __method1(self):
print("Method 1")
def _method2(self):
print("Method 2")
def method3(self):
print("Method 3")
self.__method1()
class Student(Person):
def read(self):
print("I am studying")

p1 = Person()
#p1.__method1() - private members cant be called
p1.method3()
p1._method2()

s1 = Student()
s1.read()
s1.method3()

# public
#protected _ :practically its like public, but theoritically it cant be accessed outside the class
#private __ : members can not be used outside the class

19 DEC 2022

#Class
str1="555"
print(type(str1))
str2 = "Good day"
print(str1.upper())

class Apple:
loc = "World"
def getvalue(self,name):
self.name = name
def display(self):
print(f"I am {self.name}")
@classmethod
def setaddress(cls):
cls.loc = "Universe"
@classmethod
def address(cls):
print(f"Location: {cls.loc}")

a1=Apple()
a1.getvalue("Sachin")
a2=Apple()
a2.getvalue("Kapil")
a3=Apple()
a3.getvalue("Laxman")
a4=Apple()
print(type(a1))
a1.display()
a1.setaddress()
a2.address()

class MySum:
def getval(self):
self.num1 = int(input("Enter value 1: "))
self.num2 = int(input("Enter value 2: "))
def printsum(self):
self.sum = self.num1 + self.num2
print("Sum of the values: ",self.sum)

m1 = MySum()
m1.getval()
m1.printsum()
class Employee:
population = 0

def __init__(self,name,age, salary):
self.name = name
self.age = age
self.__salary = salary
Employee.population +=1

def edit_details(self,name,age,salary):
self.name = name
self.age = age
self.__salary = salary
def _getsalary(self):
return self.__salary

@classmethod
def display_pop(cls):
print("Total Count of Objects = ",cls.population)

p1 = Employee("Sachin",48,1500) # this is calling __init__()
p2 = Employee("Virat", 29,1400)
p3 = Employee("Rohit", 29,1300)
#print(p1.__salary)
p1.display_pop()
print(p1._getsalary())
#print(p2.getsalary())
#print(p3.getsalary())

'''
Encapsulation:
access modifiers:
3 types: Public (variablename), Private (__variablename) -only to class, Protected (_variablename)
'''
word = "hello"
guess = "ll"
ind = 0
word1 = word.replace("l","L",1)
print(word1)
for i in range(word.count(guess)):
ind = word.find(guess,ind)
print(ind)
ind=ind+1

word3 = "How are you doing"
l1 = word3.split("o")
print(l1)
word4 = "o".join(l1)
print(word4)

#Strings
word = "hEllo".lower()
print(word)
display_text = "* "*len(word)
print(display_text)
while True:
guess = input("Guess the character: ")
guess = guess[0].lower()

if guess.isalpha():
if guess in word:
ind = 0
for i in range(word.count(guess)):
ind = word.find(guess, ind)
#now time to reveal
#0 - 0, 1-2, 2-4
display_text = display_text[:ind*2] + guess+display_text[ind*2+1:]
ind = ind + 1
print(display_text)

if "*" not in display_text:
print("Congratulations!")
break
else:
print("Given character is not in the original word")
else:
print("Invalid character")

class Book:
book_count = 0
def __init__(self, author, title, book_id):
self.author = author
self.title = title
self.book_id = book_id
Book.book_count+=1

def getbook(self):
print(f"{self.title} is written by {self.author}")

@classmethod
def getBookCount(cls):
print("Total books available: ",cls.book_count)

book1 = Book('Swapnil Saurav','Learn and Practice Python', 9012)
book1.getbook()
book1.getBookCount()
#Inheritance
class School:
def __init__(self,schoolname):
self.schoolname = schoolname

def _displaydetails(self):
print("School name is ",self.schoolname)

class Student (School):
def __init__(self,stname, schoolname):
School.__init__(self,schoolname)
self.stname = stname

def displaydetails1(self):
print("Student name is ",self.stname)
def displaydetails1(self,name):
print("Student name is ",self.stname)

def displaydetails1(self,name,age):
print("Student name is ", self.stname)

class Teacher (School):
def __init__(self,tname):
self.tname = tname

def displaydetails(self):
print("Teacher name is ",self.tname)

sc1 =School("ABC International School")
st1 = Student("Sachin Tendulkar","XYZ International School")
t1 = Teacher("Kapil Dev")
sc1._displaydetails()
st1.displaydetails1()
t1.displaydetails()

'''
Public
Protected _var (single underscore)
Private __var (double underscore)
'''
#1. declare a class calc
#2. initialize functon to read 3 variables
#3. create another method to calculate: sum. multiply minus
#4. Display the result using another method
#5. Create another class to perform arithematic operators
## that you have learnt in Python: + - * / % ** //

class Calc:
def __init__(self,a,b,c):
self.n1 = a
self.n2 = b
self.n3 = c
self.add = "Addition not yet done"
self.mul = "Multiplication not yet done"
self.min = "Difference not yet done"

def calc(self):
self.add = self.n1 + self.n2
self.mul = self.n1 * self.n2
self.min = self.n1 - self.n2

def display(self):
print("Sum = ",self.add)
print("Multiplication = ",self.mul)
print("Difference = ",self.min)

class Arithmatic(Calc):
def __init__(self,a,b,c):
Calc.__init__(self,a,b,c)
self.n1 = a
self.n2 = b
self.n3 = c
self.div = "Division not yet done"
self.mod = "Modulus not yet done"
self.pow = "Power not yet done"
self.intdiv = "Integer Division not yet done"

def calc(self):
Calc.calc(self)
self.div = self.n1 / self.n2
self.mod = self.n1 % self.n2
self.pow = self.n1**self.n2
self.intdiv = self.n1 // self.n2

def display(self):
Calc.display(self)
print("Division = ",self.div)
print("Modulus = ",self.mod)
print("Power = ",self.pow)
print("Integer Division = ", self.intdiv)

c1 = Arithmatic(10,5,12)
c1.calc()
c1.display()

c2 = Calc(3,4,6)
c2.calc()
c2.display()

TYPES OF FUNCTION

 

def myfun1(a,b):
'''Example of Required Positional Argument'''
print(f"a is {a} and b is {b}")
sum = a + b
print("Sum: ",sum)
#return sum

def myfun2(a=16,b=6):
'''Example of Default Positional Argument'''
print(f"a is {a} and b is {b}")
sum = a + b
print("Sum: ",sum)
#return sum

def myfun3(a,*b,**c): #variable length arguments
print("a = ",a)
print("b = ", b) # * means tuple
print("c = ", c) # **- dictionary


myfun3(50,5,6,7,8,9,9,11,14,name="sachin",game ="Cricket")


#Keyword argument
n1,n2=14,26
print(myfun2(a=n2,b=n1))
result = myfun2(b=34)


n1,n2=14,26
print(myfun2(n1,n2))
result = myfun2(34)
#result*=2
print(result)

n1,n2=54,66
print(myfun1(n1,n2))
result = myfun1(34,76)
#result*=2
print(result)

#Types of functions based on input parameter:
## 1. Required positional arguments: YOu have to provide value and in same order (left to right)
## Default (positional) arguments
import os
print(os.name)
if os.name=="nt":
print("Its a Windows machine")
elif os.name=="posix":
print("its a Linux/Mac")
else:
print("Other OS")

print(os.getcwd())
#os.rmdir("Nov_2")
#os.rename("file1.txt", "file1dec.txt")
print("iterate in folder:")
from pathlib import Path
path_list = Path("C:\\Users\\Hp\\Poems\\")
for i in path_list.iterdir():
print(i)
os.mkdir("Test2")

fp= open(r"C:\Users\Hp\Poems\Poem1.txt","r") #r for read w for write a append
content = fp.read(200)
print(type(content))
print(content)
fp.seek(0)
content = fp.readline(500)
print(type(content))
print(content)

content = fp.readlines()
print(type(content))
print(content[4])
fp.close()
fp1 = open(r"C:\Users\Hp\Poems\testCopy\sample.txt","a")
if fp1.writable():
fp1.writelines(content)

fp1.close()
#Numpy
import numpy as np
x = range(16)
# range: 0 to upto 16 - 0...15
x = np.reshape(x,(4,4))
print(type(x))
print(x)
size = x.shape
print("Total rows = ",size[0])
print("Total columns = ",size[1])

#indexing
print(x[1,2])
print(x[3,1])
print(x[0,:])
print(x[:,0])
print(x[1:3,1:3])

#
x = np.zeros((3,3))
print(x)
x = np.ones((3,3))
print(x)
x = np.full((3,3),99)
print(x)

x = np.random.random((3,3))
print(x)

l1 = [[5,10,15],[9,10,11],[2,3,1]]
print(type(l1))
l1 = np.array(l1, dtype=np.int8)
print(l1)
print(type(l1))
l2 = np.array([[3,6,9],[7,14,21],[2,4,6]])
print(l2)

#addition
print(l1 + l2)
print(np.add(l2,l1))

print(l1 - l2)
print(np.subtract(l2,l1))

print(l1 / l2)
print(np.divide(l2,l1))

print("==========================")
print(l1,"\n",l2)
print(l1 @ l2)
print(np.matmul(l2,l1))

for i in l1.flat:
print(i)

x = np.identity(6)
print(x)
print("Printing l1:\n",l1)
print("Printing Transpose of l1:")
l1_t = np.transpose(l1)
print(l1_t)

l1_det = np.linalg.det(l1)
print("Determinant of L1 is ",l1_det)
l1_inv = np.linalg.inv(l1)
print("Inverse of L1 is ",l1_inv)

#Singular matrix have determinant zero so we cant find inverse of that matrix

# 2x-3y = 8
# 3x-4y = 12
# what is x & y?
# Numpy to solve linear algebra
# 2x +5y + 2z = -38
# 3x - 2y + 4z = 17
# -6x +y -7z = -12
import numpy as np
Coeff = [[2,5,2],[3,-2,4],[-6,1,-7]]
Coeff_mat = np.array(Coeff)
Coeff_det = np.linalg.det(Coeff_mat)
if Coeff_det ==0:
print("There are no possible solution for given equations")
else:
Const = [[-38],[17],[-12]]
Coeff_inv = np.linalg.inv(Coeff_mat)
sol = np.matmul(Coeff_inv,Const)
print("Solution is: \n",sol)
print(f"x={sol[0,0]}, y={sol[1,0]}, z={sol[2,0]}")
#SETS
set1 = {1,5,9,10,20}
print(type(set1))
set1.add(22)
print(set1)

set2 = set1 #deep copy - set2 and set1 will point to same location in memory
set3 = set1.copy() #shallow copy - create a duplicate copy
print("printing 1: ")
print("Set 1: ",set1)
print("Set 2: ",set2)
print("Set 3: ",set3)
set2.add(25)
set2.add(29)

print("printing 2: ")
print("Set 1: ",set1)
print("Set 2: ",set2)
print("Set 3: ",set3)
print("Set 1: ",id(set1))
print("Set 2: ",id(set2))
print("Set 3: ",id(set3))

#union, intersection, difference, symmetric difference
Set2 = {1, 20, 5, 22, 9, 10, 29, 25}
Set3 = {1, 20, 5, 22, 9, 10,31,35}
print(Set2.union(Set3))
print(Set2 | Set3)

print(Set2.intersection(Set3))
print(Set2 & Set3)

print(Set2.difference(Set3))
print(Set3 - Set2)

print(Set2.symmetric_difference(Set3))
print(Set2 ^ Set3)
print("Set 2: ",Set2)
print("Set 3: ",Set3)
print(Set2.symmetric_difference_update(Set3))
print("Set 2: ",Set2)
print("Set 3: ",Set3)

from datetime import datetime
currenttime = datetime.now()
print("Current time: ",currenttime)

n=10000
counter = 0
for i in range(n):
for j in range(n):
counter+=1
if counter*100 % (n*n)==0:
print(f"{counter*100//(n*n)}% Task Completed")

endtime = datetime.now()
print("Total time taken by the program is ",endtime-currenttime)

from datetime import datetime, timedelta
print("Current time: ",datetime.now())
print("Current date: ",datetime.now().strftime("%Y,%m-%d"))
print("Current year: ",datetime.now().year)
print("Current month: ",datetime.now().month)
print("Current day: ",datetime.now().day)
print("Current hour: ",datetime.now().hour)
print("Current minute: ",datetime.now().minute)
print("Current second: ",datetime.now().second)

import time
print("Current time: ",time.strftime("%Y,%m-%d"))
print("Total time: ",time.time())
print("Tomorrow's time: ",datetime.now()+timedelta(days=1))
from pytz import timezone
print("Current time in US Eastern is",datetime.now(timezone("US/Eastern")).strftime("%Y-%m-%d"))

# random numbers
import random
random.seed(100)
print("Random = ",random.random()) # randon no. between 0 & 1
print("Random = ",int(random.random()*1000))
print("Random Integer values: ",random.randint(500,9000))
choices = ["ONE","TWO","THREE","FOUR","FIVE","SIX"]
print("One value from the list: ",random.choice(choices))
random.shuffle(choices)
print("random shuffle: ",choices)

#MAP - works with List where you want to apply same calculation to all the numbers
distances = [1100,1900,4500,6500,3400,2900,5400]*500
dist_ft = 0 #3.1 *
from datetime import datetime

start=datetime.now()
dist_ft = list(map(lambda x:3.1*x,distances))
end=datetime.now()
print("Total time taken by MAP = ",end-start)

start=datetime.now()
dist_ft2 = []
for i in distances:
val = i*3.1
dist_ft2.append(val)
#print("Output using Loops = ",dist_ft2)
end=datetime.now()
print("Total time taken by LOOP = ",end-start)
Learn and Practice Javascript

DAY 1: 25 OCT 2022

 
<HTML>

<Head>
    <Title> Learning HTML AND JAVASCRIPT</Title>

    <Script>
        //displaying a welcome message

        /*
        3 ways to use numbers
        1. var
        2. let
        3. const
   
        */
        //var examples – older version of javascript
        var num3 = 50
        var num4 = 90
        var sum1 = num3 + num4

        //let is used in the newer version
        let name = Sachin //declaring and assigning value to a variable
        let num1 = 50
        let num2 = 60
        num1 = 40
        let sum = num1 + num2

        //Const
        const pi = 3.14
        //pi = 4

        /*
        Creating a welcome message for the website’s reader
        thank you
        go ahead
        */
        msg = Welcome to Javascript learning Session + name

        //usage of  ‘  ‘  and ”  “
        let str1 = Hello  //string datatype
        let str2 = How are you?;
        // let’s go
        str1 = let’s go;
        // he said,”Whats you name?”
        str2 = he said,”Whats you name?” ;

        //boolean: true and false
        num1 = 80
        num2 = 60
        num1 == num2  //false

        num1 < num2  // true
        if (num1 < num2) alert(Num1 is smaller than num2);

        alert(msg)

        //array
        let array1 = [JAN, Feb, Mar]

        //Object data type
        let obj1 = { fname: Sachin, lname: Tendulkar, runs: 25000, sports: Cricket }
        // datatype is object

        sum = 12 + 24 + 36 + hello

        //Datatype in Javascript is dynamic in nature
        let x  //variable is declared but not defined (defined = has to have a datatype)
        x = 99  // number datatype
        x = [JAN, Feb, Mar]  //will not throw error – dynamically typed data

        //numbers with scientific notation (e)
        let y = 99e6 //99000000
        let z = 9.9e7
        //alert(z)
        let t = 5.5e-3  //  0.0055
        alert(t)

        // typeof will give the datatype
        alert(typeof x)
        alert(typeof (y))
        let var4   //undefined
        alert(typeof (var4))

    </Script>

</Head>

<Body>

    Hello everyone, how are you doing?

</Body>

</HTML>

Day 2: 26 OCT 2022


<HTML>

<Head>
    <Title> Learning 2</Title>


    <Script>
        //declare a function
        function mysum(n1, n2, n3) {
            let total
            total = n1 + n2 + n3
            return total
        }
        //num1 = total – error: notdefined as its local variable
        let result = mysum(11, 22, 33)
        alert(Sum is + mysum(11, 22, 33))

        /*
            avg >=80 – Grade A
            avg >=60 (<80) – Grade B
            avg >=40 – Grade C
            avg <40 – Grade D
        */
        let avg = 95

        if (avg >= 80) {
            //what happens if the condition is true
            alert(Grade A)
        } else if (avg >= 60) {
            alert(Grade B)
        } else if (avg >= 40) {
            alert(Grade C)
        } else {
            alert(Grade D)
        }

        // SWITCH – also used for conditions
        //  Date()  – inbuilt function to get the date, getDay() will the day in integer value
        // 0 for Sunday, 1 for Monday …
        dayval = new Date().getDay()  //day in number
        switch (dayval) {
            case 2:
                alert(Today is Tuesday)
                break
            case 0:
                alert(Today is Sunday)
                break
            case 1:
                alert(Today is Monday)
                break

            case 3:
                alert(Today is Wednesday)
                break
            case 4:
                alert(Today is Thursday)
                break
            case 5:

            case 6:
                alert(It could be Friday or Saturday)
                break
            default:
                alert(I Dont Know the Day)
                break
        }

        /*
        Loops in Javascript: There are multiple types:
        1. for
        2. for /in – iterated through the properties of object
        3. for /out – iterated through the values of object

        4. while – is entry controlled loop
        5. do/while – is exit controlled loop
        */

        //for loop
        for (let i = 0; i < 5; i++) {
            alert(Loop is running : + i)
        }
    </Script>

</Head>

<body>

</body>

</HTML>

Day 3: For Loop

<html>

<head>
    <script>
        /*
        Loops in Javascript: There are multiple types:
        1. for
        2. for /in – iterated through the properties of object
        3. for /of – iterated through the values of object

        4. while – is entry controlled loop
        5. do/while – is exit controlled loop
        */

        //for loop
        let i = 1
        for (; i < 5; i++) {
            alert(Loop is running : + i)
        }

        i = 1
        for (; i < 1; i++) {
            alert(Loop is running : + i)
        }

        let obj1 = { fname: Sachin, lname: Tendulkar, runs: 25000, sports: Cricket }
        for (let j in obj1) {
            alert(j = + j + and value is + obj1[j])

        }
        let runs = [102, 2, 97, 0, 95]
        for (let j in runs) {
            alert(j = + j + and value is + runs[j])
        }
        /*
        of is not iteratable on Object
        for (let j of obj1) {
            alert(“j = ” + j)

        }
        */
        name = Sachin
        for (let j of name) {
            alert(j = + j)

        }

        //Creating a function to demonstrate forEach() of array
        /*
        it takes 3 arguments: item value, index and the array
        */
        runs = [102, 2, 97, 0, 95]
        let out_val = “”
        let ind_val = “”
        let array_val = “”

        runs.forEach(func_array)

        function func_array(val, index, array) {
            out_val += val + ,
            ind_val += index + ,
            array_val += array + ,
        }
        alert(Output of the function is: Value = + out_val + index = + ind_val + array = + array_val)
    </script>
</head>

<body>

</body>

</html>

DAY 4: WHILE

<html>

<head>
    <script>
        runs = [102, 2, 97, 0, 95]
        let out_val = 0
        let ind_val = 0
        let array_val = 0

        runs.forEach(func_array)

        function func_array(val, index, array) {
            out_val += val
            ind_val += index + ,
            if (index < 1) {
                array_val = array
            }

        }
        alert(Output of the function is: Sum of Value = + out_val + index = + ind_val + array = + array_val)
        // If is used when you know how many times to repeat
        //While works on conditions – while will repeat if the condition is True
        let a = 0
        while (a < 10) {
            alert(a)
            a += 2
        }
        //while is entry controlled loop
        a = true
        let num = 10
        while (a) {
            alert(num)
            num += 10
            if (num > 50) {
                break
            }
        }
        // do while – exit controlled
        num = 10
        do {
            alert(Second Run + num)
            num += 10
        }
        while (num < 0)

        //iterating through an array
        let players = [Sachin, Rohit, Rahul, Kapil, Kohli]
        let all_players = “”
        let counter = 0
        while (players[counter]) {
            all_players += players[counter] +
            counter += 1
        }
        alert(all_players)
        // a + = num   => a = a + num

        //Map Declaration
        runs_scored = new Map([
            [Sachin, 19000],
            [Kapil, 11000],
            [Sunil, 18000]
        ])

        //get() to fetch the data
        alert(Runs scored by Sunil is + runs_scored.get(Sunil))

        //set – add value to existing map
        runs_scored.set(Virat, 8900)
        alert(Runs scored by Virat is + runs_scored.get(Virat))
    </script>
</head>
<body>
</body>
</html>

DAY 5

<html>

<head>
    <script>
        //MAPS
        // new Map() – create a new map
        //set() – to add member
        //get() – get the value from the map

        players = new Map([
            [Sachin, 19000],
            [Rohit, 11000,],
            [Kapil, 9000],
            [Sunil, 18800]
        ])
        key_to_delete = Sachin
        alert(players.has(key_to_delete))
        if (players.has(key_to_delete)) {
            players.delete(key_to_delete)
        }
        players.set(Dhoni, 13000)
        alert(Size of the players map is + players.size)
        //if I want to iterate through : forEach
        let check = 0
        players.forEach(function (value, key) {
            if (key == Dhoni) {
                check = 1
            }
        })
        if (check == 0) {
            alert(Dhoni is not in the map)
        } else {
            alert(Dhoni is in the map)
        }

        // entries: get you all the entries
        //iterate through each key and value pair
        alert(players.entries :)
        for (let x of players.entries()) {
            alert(x)
        }
    </script>
</head>

<body>
</body>

</html>

DAY 6

<html>

<head>
    <title> My Website</title>
    <script>
        let a = 5
        debugger
        let b = 6
        //debugger
        c = a + b
        //debugger
        console.log(c)

        // arrow function
        let myfunction = (x, y, z) => 2 * x y + 0.38 * z

        let val = myfunction(5, 8, 100)
        //alert(val)
        console.log(val)

        class Laptop {
            //class level variables
            total = 0
            //class level methods

            //object level method
            constructor(person, make, os, year) {
                this.person = person
                this.make_co = make  //object level variables
                this.os = os
                this.purchase_year = year
            }

            //creating one more method
            age() {
                let date = new Date()  //creating object of Date class
                this.age_val = date.getFullYear() this.purchase_year
                //console.log(this.age_val)
            }
            //creating another method
            display() {
                console.log(this.person + has a laptop of + this.make_co + make which uses + this.os + and is + this.age_val + year old)
            }
        }
        //create object of class laptop
        let sachin_laptop = new Laptop(Sachin, HP, Windows, 2011)
        let kohli_laptop = new Laptop(Kohli, Dell, Linux, 2019)
        let dhonin_laptop = new Laptop(Dhoni, Dell, Mac, 2022)
        console.log(kohli_laptop.os)
        kohli_laptop.age()
        console.log(Kohli’s laptop age in yrs is + kohli_laptop.age_val)
        sachin_laptop.age()
        sachin_laptop.display()
    </script>
</head>

<body>
    <H1> My Webpage</H1>
</body>

</html>
<html>

<head>
    <script>
        const sub1 = 80
        const sub2 = 80
        const sub3 = 80
        const sub4 = 0
        const sub5 = 0
        let sum = sub1 + sub2 + sub3 + sub4 + sub5
        let avg = sum / 5
        console.log(“Average marks scored by the student is “ + avg)
        //avg > 90 A, B..
        if (avg >= 90) {
            console.log(“Grade is A”)
        } else if (avg >= 80) {
            console.log(“Grade is B”)
        } else if (avg >= 70) {
            console.log(“Grade is C”)
        } else if (avg >= 60) {
            console.log(“Grade is D”)
        } else if (avg >= 50) {
            console.log(“Grade is E”)
        } else {
            console.log(“Grade is F”)
        }

        //Example 2
        let weight = 85  //kg
        let height = 1.4 //meters
        let bmi = weight / height ** 2
        console.log(“BMI is “ + bmi)

        //function to check if input number is prime or not
        function checkPrime(num) {
            let isPrime = true

            for (let i = 2; i < num / 2; i++) {
                if (num % i == 0) {
                    isPrime = false
                    break
                }
            }
            return isPrime
        }
        let result = checkPrime(61)
        if (result) {
            console.log(“Its a prime number”)
        } else {
            console.log(“Its not a prime number”)
        }
        st = 4500
        en = 5000
        console.log(“Now generating prime numbers between “ + st + ” and “ + en)
        for (i = st; i <= en; i++) {
            result = checkPrime(i)
            if (result) {
                console.log(i)
            }

        }
    </script>
</head>

<body>

</body>

</html>
<html>

<head>
    <script>
        class TipCalc {
            constructor(bill_amount) {
                this.amount = bill_amount
            }

            calculator() {
                let tip = –1
                // Bill amount is between 50 and 300 – then its 15%, otherwise its 20%
                if (this.amount >= 50 && this.amount <= 300) {
                    tip = this.amount * 0.15

                } else {
                    tip = this.amount * 0.20
                }
                return tip
            }
        }
        amount = 49
        let mytip1 = new TipCalc(amount)
        tip_cal = mytip1.calculator()
        total = amount + tip_cal
        console.log(“The bill was $” + amount + ” the tip was $” + tip_cal + ” total value is $” + total + “.”)

    </script>
</head>

<body>

</body>

</html>
<html>

<head>
    <script>
        let a = 11  //a to be less than 10 or throw error
        try {
            if (a > 15) throw “High value for a”
            if (a < 8) throw “Low value for a”
            let b = “hello”
            let c = 0
            c = b / g
            console.log(“Result = “, c)

        }
        catch (err) {
            console.log(“Caught an error in try. Error message: “ + err)
            let mesg = err
            if (err == “High value for a”) {
                alert(“Please reduce the value of a and try again”)
            }
            if (err == “ReferenceError: g is not defined”) {
                alert(“You are using g without declaring g variable”)
            }
        }
        finally {
            console.log(“I dont care about the error”)
        }
    </script>
</head>

<body>

</body>

</html>
// Try and catch to handle run time errors
<html>

<head>
    <script>
        today_date = new Date() //this will have date object storing current date and time
        console.log(today_date)

        today_date = new Date(2022, 10)  //year, month (previous)
        console.log(today_date)


        today_date = new Date(“October 1, 2020 05:36:12”)
        console.log(today_date)

        today_date = new Date(“2022-11-29”)
        console.log(today_date)

        today_date = new Date(2021, 11, 15, 1)  // year, month, date, hour
        console.log(today_date.getFullYear())
        console.log(today_date.getMonth())
        months_txt = [“January”, “February”, “March”, “April”, “May”,
            “June”, “July”, “August”, “September”, “October”, “November”, “December”]
        console.log(months_txt[today_date.getMonth() – 1])
        //getMinutes() getSeconds()  getMilliseconds() getDate()
        console.log(today_date.getDate())

        //Set the dates
        //setDate()  setFullYear() …
        console.log(today_date.setFullYear(2050))
        console.log(today_date.getDate())
        text = ‘{“player”: [{“Name”: “Sachin”, “City”: “Mumbai”,’ +
            ‘”Sports”: “Cricket”}, {“Name”: “Kapil”,’ +
            ‘”City”: “Gurgaon”,”Sports”: “Cricket”}]}’;
        json_val = JSON.parse(text)
        console.log(json_val.player[1].Name + ” : “ +
            json_val.player[0].City)
        /*
   today_date = new Date()
   console.log(today_date)

   today_date = new Date()
   console.log(today_date)

   today_date = new Date()
   console.log(today_date)

   today_date = new Date()
   console.log(today_date)

   today_date = new Date()
   console.log(today_date)
   */
    </script>
</head>

<body>

</body>

</html>
<html>

<head>

</head>

<body>
    <h1> Welcome </h1>
    <p id=“test1”> </p>
    <h2> How are you?</h2>
    <p id=“test2”> </p>
    <p id=“test3”> Twinkle Twinkle Little Star </p>
    <form name=“Form1” action=“practice7.html” method=“post”>
        Name: <input type=“text” name=“name”>
    </form>
    <script>
        choice = 5

        document.getElementById(“test1”).innerHTML = “<H3>Sachin<H3>”
        document.getElementById(“test1”).innerHTML = “Date: “ + Date()
        //id_test3 = document.getElementById(“test3”)
        document.getElementsByTagName
        val_test3 = document.getElementsByTagName(“p”)
        //console.log(val_test3)
        document.write(“THIS IS HELLO FROM ME”)
    </script>
</body>

</html>
Learn Data Science

https://youtu.be/mr15WQQoTvI

19 OCTOBER 2022

Day 1 Video Session

 

print("hello")
print(5+4)
print('5+5')
print("10+frgjdsijgdskmdklfmdfmv4",5+6," = ",11)
# 4 parameters/arguments
#Comment
price = 50 #variable called price is assgined a value 50
quantity = 23
TotalCost = price * quantity
print(TotalCost)

 

#The total cost of XquantityX pens selling at XpriceX would be XtotalcostX
print(“The total cost of”,quantity,“pens selling at”,price,“would be”,TotalCost)
print(f”The total cost of {quantity} pens selling at {price} would be {TotalCost}”)

#going to use format string

 

Session 2: 20 OCT 2022

VIDEO Recording

var1 = 80
var2 = 60
sdfdwfdsg = "var3"
#Arithematic
s1 = var1 + var2
print(s1, var1 /var2,"Now minus", var1 - var2)
print(var1 - var2)
print(var1 * var2)
print(var1 / var2) #division
print(var1 // var2) #integer division

## Data types: nature of data that we can work
#integer : -inf to +inf without decimal
#float : decimal -5.0
#string: 'hello'
#bool (boolean): True / False
Val1 = True
#input() #take input from the user
print(type(Val1)) #give you the datatype of the variable
price = 50
quantity =23
totalcost = price * quantity
a=50
b=23
c=a*b

#arithematic operators:  + - * / //
var1 = 3
var2 = 5
print(var1 ** var2) #power()
print(var1 % var2) #reminder

#Relational operators: will always result in bool output (T/F)
print("var1 < var2: ",var1 < var2) #is var1 less than var2
print(var1 > var2) #is var1 greater than var2
print(var1 == var2)
print(var1 <= var2) #is var1 less than or equal to var2
print(var1 >= var2)
print(var1 != var2) #not equal to

#Logical operators: will have bool input and bool output
# and or not
# F and F = F and T = T and F = FALSE T and T = T
print(True and True)
print(True and False)

#or
# T or T = F or T = T or F = True F or F = False
print("True or True: ",True or True)
print(True or False)

print("Grade A" )
print("Grade B")
print("Grade C")
print("Grade D")
print("Grade E")
print()
avg = 40
if avg>=50:
print("i am inside if")
print()
sum=5+3
print(sum)

print("I am in main")

Session on 21 OCT 2022

subject1 = input("Enter the marks in subject 1: ")
print(type(subject1))
subject1 = int(subject1)
print(type(subject1))
subject2 = 99
subject3 = 100
avg_marks = (subject1+subject2+subject3)/3
print("Average marks scored is ",avg_marks)
if avg_marks >=80:
print("You got grade A")
if avg_marks >=90:
print("You also win President Medal")
elif avg_marks >=70:
print("You got grade B")
elif avg_marks >=60:
print("You got grade C")
elif avg_marks >=50:
print("You got grade D")
else:
print("You didnt get grade E")

print("Thank You")

#Loops - to repeat the steps more than once
#1. For : we use it when we know how many times to execute
#2. While : we dont know how many times but we know condition till when
for i in range(10): #range(10): starts from zero and goes upto 10 (not included 10)
print("Hello")

count = 0
while count<10:
print("Hello in While")
count=count+1
#for loop
for j in range(5):
for i in range(5):
print("*", end=" ")
print()

print()

# \n - newline
#print("A \n B \n C \n D \n E")
#print has invisible \n at the end

print("Hello\n")
print("Good Morning")

26 OCT 2022

#List methods
list1 = [2,4,6,8,10,8,19,8]
list1.append(3) #adds at the end of the list
print(list1)
list1.insert(2,14) #(pos,value)
print(list1)

#remove elements from a list
#pop() - removes element at the given position
list1.pop(1)
#remove() - remove given element
list1.remove(10)
print(list1)

#index()
print("Index: ",list1.index(8))

pos=[]
c=0
for i in list1:
if 8 ==i:
pos.append(c)
c+=1
print("Position of 8 in the list: ",pos)
list1.pop(pos[-1])

list2 = [10,20,30,40]
list3 = list1 + list2
print(list3)
list1.extend(list2) #list1 = list1 + list2
print(list1)
list1.reverse() #just reverse the elements
print(list1)
list1.sort() #increasing order
print(list1)
list1.sort(reverse=True) #decreasing order
print(list1)

#
list1 = [2, 14, 6, 8, 8, 19, 8, 3]
list1[1] = 4 #we can edit is called MUTABLE
print(list1)
list2 = list1 #deep copy: both points to same data
list3 = list1.copy() #shallow copy
print("1. List1: ",list1)
print("1. List2: ",list2)
print("1. List3: ",list3)
list2.append(22)
print("2. List1: ",list1)
print("2. List2: ",list2)
print("2. List3: ",list3)

27 OCT 2022


#linear ordered mutable collection - List
#linear ordered immutable collection - Tuple

t1 = (1,2,3,4,5)
print(type(t1))
print(t1[-1])
#[] brackets are used for indexing in all datatypes and also list
#() - for tuple and also for function
print(t1)
#t1[1] = 10 - TypeError: 'tuple' object does not support item assignment
print(t1.index(3))
print(t1.count(3))
n1,n2,n3 = (2,4,6) #unpacking
print(n2)

for i in t1:
print(i)

#comparing: always compares first element and if they are equal
# it goes to the next and so on
#(2,4) (2,4)
print(type(t1))
t1 = list(t1)
print(type(t1))
t1 = tuple(t1)

#Dictionary
#non-linear unordered mutable collection
d1 = {}
print(type(d1))
d1 = {"fname":"Sachin", "lname":"Tendulkar","Runs": 130000,"City":"Mumbai"}
d1["lname"] = "TENDULKAR"
print(d1["lname"])
#
d1.popitem()
print(d1)
d1.pop("fname") #removes the value with the given key
print(d1)

#keys
print(d1.keys())
for i in d1.keys():
if d1[i] == "TENDULKAR":
print("Remove this key: ",i)

print(d1.values())
for i in d1.items():
print(i[1])

d1 = {"fname":"Sachin", "lname":"Tendulkar","Runs": 130000,"City":"Mumbai"}
d2 = d1
d3 = d1.copy()
print("1. D1 = ",d1)
print("1. D2 = ",d2)
print("1. D3 = ",d3)
d1.update({"Country":"India"})
print("2. D1 = ",d1)
print("2. D2 = ",d2)
print("3. D3 = ",d3)

d3.clear()
print(d2)

#Sets
#linear un-ordered mutable collection - sets
set1 = {1,2,3,3,4,3,4,2,1}
print(type(set1))
print(set1)

s1 = {1,2,3,4,5}
s2 = {3,4,5,6,7}
print(s1|s2) # Union
print(s1 & s2) # Intersection
print(s1 - s2) #diff
print(s2 - s1) #diff
print(s1 ^ s2) #symm diff
print(s1.intersection(s2)) #without update will give a new set
print(s1.update(s2)) #update will update the s1 with new value
print(s1)

28 OCT 2022

#Functions
def mystatements():
print("How are you?")
print("Whats your name?")
print("Where are you going?")

print("Hello")
mystatements()
print("Second")
mystatements()

def myaddition():
n1 = int(input("Enter number 1 to add: "))
n2 = 50
sum = n1 + n2
print("Addition of two numbers is ",sum)

myaddition()
num1,num2,num3 = 15,20,25
def myaddition2(n1,n3,n2): #accepting arguments
#n1 = int(input("Enter number 1 to add: "))
n2 = 50
sum = n1 + n2
print("Addition of two numbers is ",sum)
myaddition2(num1,num2,num3) #num1 is the argument we are passing
## positional & required


##2. positional & default
def myaddition2(n1,n2,n3=0): #accepting arguments
#n1 = int(input("Enter number 1 to add: "))
n2 = 50
sum = n1 + n2
print("Addition of two numbers is ",sum)
myaddition2(num1,num2)

#3.keyword arguments (not positional)
def myaddition2(n1,n2,n3=0): #accepting arguments
#n1 = int(input("Enter number 1 to add: "))
n2 = 50
sum = n1 + n2
print("Addition of two numbers is ",sum)
myaddition2(n3=10,n2=num1,n1=num2)

SESSION 2


#4. Function with takes variable number of arguments
def myownfunction(num1, *numbers, **values):
print("Num 1 is ",num1)
print("Numbers : ",numbers)
print("Values: ", values)
sum=0
for i in numbers:
sum+=i
return sum

def myown2(num1, *numbers, **values):
print("Num 1 is ",num1)
print("Numbers : ",numbers)
print("Values: ", values)
sum=0
for i in numbers:
sum+=i

print("myownfunction: ",myownfunction(3,4,5))
print("MyOwn2: ",myown2(3,4,5))
out = myown2(3,4,5)
print("OUT = ",out)

output = myownfunction("Hello",2,4,6,8,10,12,14,16,18,20, name="Sachin",city="Mumbai",runs=25000)
print("Output is: ",output)

set1= {1,2,3}
set2 = {3,4,5}
print("Union",set1.union(set2)) #return
print("Union Update",set1.update(set2)) #doesnt have return
print("Set1: ",set1)

#
# Class and Objects
#collection of variables and functions (methods) - grouped together to define something
class Dog:
num_legs = 4
def __init__(self,name,make):
self.name = name
self.breed = make

def display(self):
print("Name is ",self.name)
print("Breed is ",self.breed)

mydog1 = Dog("Tiger","BBB") #object 1 of class Dog
mydog2 = Dog("Moti","AAA") #object 2 of class Dog
#mydog2.initialize()
#mydog1.initialize()
print(mydog1.num_legs)
print(mydog2.num_legs)
mydog1.display()
class FourSides:
def __init__(self,a):
self.side1 = a
print('FourSides Object is created')
def _display_4sides(self):
print("Display in 4 Sides")
def area(self):
print("Sorry, I am not complete")
def peri(self):
print("Sorry, I am not complete")

class Square(FourSides):
def __init__(self,a):
FourSides.__init__(self,a)
print('Square Object is created')
def area(self):
print("Area is ",self.side1**2)
class Rectangle(FourSides):
def __init__(self,a, b):
FourSides.__init__(self, a)
self.side2 = b
print('Rectangle Object is created')
def area(self):
print("Area is ",self.side1*self.side2)


sq = Square(10)
print(sq.side1)
rc = Rectangle(5,10)
print(rc.side1)
sq.area()
#string
var1 = "Hello"
var2 = 'Hello'
var1 = '''Hello'''
var1 = """Hello"""
var1 = """How are you
Where are you doing
When will you be back
Take care"""
print(type(var1))
print(var1)
print(var1[0:3])
print(var1[-4:])

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

if "e" in var2:
print("E is in the string")

var3 = "i am fine and am doing good"
find = var3.find("am",5,19)
if find!= -1:
var5 = var3.index("am",5,19)
print(var5)
print(" ".isspace())
print(var3.islower())
print("I Am DoinG Good".istitle())
R PROGRAMMING SEP 2022

DATA ANALYSIS WITH R

DAY 1: 10 SEP 2022

#Compiler

 

#interpreter

 

print(“XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”)

print(5 + 3)

print(“5 + 3”)

hello = 5

print(hello)

 

print(4) # comment

 

#Data types -what is the data

#Basic data type:  single value

#logical: TRUE / FALSE

var1 = TRUE  #FALSE

var1 <- TRUE

TRUE  -> var1

#

print(class(var1))

 

#Integer: positive or negative numbers without decimal part

var1 <- 3L

print(class(var1))

 

#numeric: can take decimal values

var1 <- 3.5

print(class(var1))

 

#CHARACTER

var1 <- “HEllo”

print(class(var1))

 

#complex: square root of -1

var1 = 5i   #complex numbers are represented iota

print(var1 * var1)

print(class(var1))

 

#Raw

print(charToRaw(“l”))

 

#### data structure

#vector : same type of values

hello=68

var1 = c(34,45,67,”hello”)

print(var1)

print(class(var1))

 

# lists

var1 <- list(3,5,”Hello”, TRUE, c(2,4,8,2,4,6,8,2,4,6,8))

print(var1)

cat(“Hello”, “there”)

#print(“Hello”, “there”)

 

#Matrices

mat1 = matrix(c(1,3,5,7,9,11,13,15,18), nrow=3,ncol=3, byrow = TRUE)

print(mat1)

 

mat1 = matrix(c(1,3,5,7,9,11,13,15,18), nrow=3,ncol=3, byrow = FALSE)

print(mat1)

 

var1 = array(c(1,3,5,7,9,11,13,15,18,9,11,13,15,18,21,22,25,28), dim=c(2,2,2,2))

print(var1)

 

# Factor

color = c(“Red”,”Green”,”Blue”,”Green”,”Blue”,”Green”,”Blue”,”Green”,”Blue”,”Red”)

color_f = factor(color)

print(color_f)

 

 

# Data Frames

employee <- data.frame(

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

  City = c(“Mumbai”,”Delhi”,”Chennai”),

  Avg = c(113,24,85)

)

print(employee)

 

DAY 2: 11 SEP 2022

#Arithmetic operators

v1 = c(1,3,5,7)

v2 = c(2,4,6,8)

print(v1 + v2)

print(v1 – v2)

print(v1 * v2)

print(v1 / v2)

 

# %% is for remainder

num = 15

rem = num %%2

print(rem)

 

# integer division or quotient:  %/%

qt = 15 %/% 4

print(qt)

 

#5 ^ 3 : cube power of

print( 5^ 3)

 

#Relational Operators: bigger smaller relation – oUput is logical

var1 = 55

var2 = 66

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

print(var1 < var2)

print(var1 >= var2)

print(var1 <= var2)

print(var1 == var2)

print(var1 != var2) 

 

 

#Logical operators: Input is logical and output is also logical

#prediction: Sachin and Laxman will open the batting

#actual: Sachin and Rahul opened the batting

 

#prediction: Sachin or Laxman will open the batting

#actual: Sachin and Rahul opened the batting

 

#  & for and ,  | for or

a=5

b=6

c=7

print(a > b | b < c)  # for OR – even 1 True will make it True

 

# T & T = T  F & F = F   T & F = F    F&T = F  (multiplication)

# T | T = T  F | F = F   T | F = T    F|T = T  (addition)

print(!TRUE)

 

#Assignment Operators:

a = 5

a <- 5

a <<- 5  #left assignment

#right assignment:

100 -> b

200 ->> b

c=6

 

b -> c

print(b)

print(c)

 

 

####################################################3

## CONDITIONS

 

#if avg >= 90 I want to print COngratulations

avg = 90

if (avg >=90) {

  print(“Congratulations”)

}

 

avg =40

if (avg>=50) {

  print(“You have passed”)

} else {

  print(“Sorry, You have failed”)

}

 

 

# if – else if  – else

 

#avg > 90: Grade A, avg>80: Grade B, avg>70: C, avg > 60: D, avg >50: E, <50: F

avg = 90

 

if (avg>=90) {

  print(“Grade A”)

  val = 1

} else if (avg >=80) {

  print(“Grade B”)

  val=2

} else if(avg>=70) {

  print(“Grade C”)

  val = 3

} else if (avg >= 60) {

  print(“Grade D”)

   val = 4

} else if (avg>=50) {

  print(“Grade E”)

   val =5

} else {

  print(“Grade F”)

   val = 6

}

 

## switch

#switch(expression, case1: case2)…

 result <- switch(

   val,

   “Hello”,

   “How are you?”,

   “Where are you?”,

   “Hows going?”

 )

 print(result)

 

 

 #loops – repeat block

 ## repeat: exit check

 ## while : entry check

 ## for : when we know how many times to repeat

 

TABLE OF CONTENTS

Unit 1: Getting Started with R.. 2

Getting Started. 2

R Objects and Data Types. 5

R Operators. 9

Decision Making in R. 12

LOOPS in R. 14

STRINGS in R. 15

Unit 2: FUNCTIONS in R.. 17

Built-in Function. 17

User-defined Function. 17

Unit 3: VECTORS, LISTS, ARRAYS & MATRICES. 19

VECTORS. 19

LISTS. 22

MATRICES. 25

ARRAYS. 27

Factors. 29

Data Frames. 34

Unit 4: Working with Files. 45

Working with Excel Files. 46

Unit 5: Working with MSAccess Database. 48

Unit 6: Working with Graphs. 51

Unit 7: Overview of R Packages. 64

Unit 8: Programming Examples. 68

Unit 1: Getting Started with R

R is a free software environment for statistical computing and graphics. It compiles and runs on a wide variety of UNIX platforms, Windows and MacOS. Why R? It’s free, open source, powerful and highly extensible. “You have a lot of prepackaged stuff that’s already available, so you’re standing on the shoulders of giants,” Google’s chief economist told The New York Times back in 2009.There can be little doubt that interest in the R statistics language, especially for data analysis, is soaring.

 

Downloading R

The primary R system is available from the Comprehensive R Archive Network, also known as CRAN. CRAN also hosts many add-on packages that can be used to extend the functionality of R. The “base” R system that you download from CRAN: Linux, Windows, Mac, Source Code

Website to download:  https://cran.r-project.org/mirrors.html

 

The R Foundation for Statistical Computing

The R Foundation is a not-for-profit organization working in the public interest. It was founded by the members of the R Development Core Team in order to:

·        Provide support for the R project and other innovations in statistical computing. We believe that R has become a mature and valuable tool and we would like to ensure its continued development and the development of future innovations in software for statistical and computational research.

·        Provide a reference point for individuals, institutions or commercial enterprises that want to support or interact with the R development community.

·        Hold and administer the copyright of R software and documentation.

 

R functionality is divided into a number of packages:

·        The “base” R system contains, among other things, the base package which is required to run R and contains the most fundamental functions.

·        The other packages contained in the “base” system include utils, stats, datasets, graphics, grDevices, grid, methods, tools, parallel, compiler, splines, tcltk, stats4.

·        There are also “Recommended” packages: boot, class, cluster, codetools, foreign, KernSmooth, lattice, mgcv, nlme, rpart, survival, MASS, spatial, nnet, Matrix.

When you download a fresh installation of R from CRAN, you get all of the above, which represents a substantial amount of functionality. However, there are many other packages available:

·        There are over 4000 packages on CRAN that have been developed by users and programmers around the world.

·        People often make packages available on their personal websites; there is no reliable way to keep track of how many packages are available in this fashion.

·        There are a number of packages being developed on repositories like GitHub and BitBucket but there is no reliable listing of all these packages.

 

 

More details can be found at the R foundation website: https://www.r-project.org/

 

Let’s create our first R Program

Launch R. In Windows you can launch R software using the option shown below under Program Files.

Figure 1: Launch R Programming Window

 

After launching R interpreter, you will get a prompt > where you can start typing your

Program. Let’s try our first program:

 

In the Hello World code below, vString is a variable which stores the String value “Hello World” and in the next line we print the value of the vString variable. Please note that R command are case sensitive. print is the valid command to print the value on the screen.

Figure 2: Hello World

 

# is the syntax used to print comments in the program

Figure 3: R Programming

 

R Basic Syntax

Download and Install R software

When R is run, this will launch R interpreter. You will get a prompt where you can start typing your programs as follows:

Here first statement defines a string variable myString, where we assign a string “Hello, World!” and then next statement print() is being used to print the value stored in variable myString.

 

R Script File

Usually, you will do your programming by writing your programs in script files and then you execute those scripts at your command prompt with the help of R interpreter called Rscript. So let’s start with writing following code in a text file called test.R as under:

Save the above code in a file test.R and execute it at Linux command prompt as given below. Even if you are using Windows or other system, syntax will remain same.

For windows, go to command prompt and browse to the directory where R.exe/Rscript.exe is installed.

Run-> Rscript filename.R     (filename.R is the name of the file which has R program along with the path name.)

 

We will use RStudio for rest of our course example. Download and install R Studio.

 

 

Generally, while doing programming in any programming language, you need to use various variables to store information. Variables are nothing but reserved memory locations to store values. This means that, when you create a variable you reserve some space in memory. In contrast to other programming languages like C and java in R, the variables are not declared as some data type. The variables are assigned with R-Objects and the data type of the R-object becomes the data type of the variable.

 

R has five basic or “atomic” classes of objects:

·        character

·        numeric (real numbers)

·        integer

·        complex

·        logical (True/False)

 

The frequently used ones are:

Vectors

Lists

Matrices

Arrays

Factors

Data Frames

 

The simplest of these objects is the vector object and there are six data types of these atomic vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic vectors.

Figure 4: Data Types in R

 

 

Creating Vectors

The c() function can be used to create vectors of objects by concatenating things together.  When you want to create vector with more than one element, you should use c() function which means to combine the elements into a vector. You can also use the vector() function to initialize vectors.

Figure 5: Vector example

 

Lists, Matrices, Arrays

A list is an R-object which can contain many different types of elements inside it like vectors, functions and even another list inside it.

 

A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the matrix function.

 

While matrices are confined to two dimensions, arrays can be of any number of dimensions. The array function takes a dim attribute which creates the required number of dimension. In the below example we create an array with two elements which are 3×3 matrices each.

 

Factors

Factors are used to represent categorical data and can be unordered or ordered. One can think of a factor as an integer vector where each integer has a label. Factors are important in statistical modeling and are treated specially by modelling functions like lm() and glm(). Using factors with labels is better than using integers because factors are self-describing. Having a variable that has values “Male” and “Female” is better than a variable that has values 1 and 2. Factor objects can be created with the factor() function.

Figure 6: List, Matrix and Array example

 

Figure 7: Factors example

 

Data Frames

Data frames are tabular data objects. Unlike a matrix in data frame each column can contain different modes of data. The first column can be numeric while the second column can be character and third column can be logical. It is a list of vectors of equal length. Data Frames are created using the data.frame() function.

Figure 8: Data frames example

 

Mixing Objects

There are occasions when different classes of R objects get mixed together. Sometimes this happens by accident but it can also happen on purpose. In implicit coercion, what R tries to do is find a way to represent all of the objects in the vector in a reasonable fashion. Sometimes this does exactly what you want and sometimes not. For example, combining a numeric object with a character object will create a character vector, because numbers can usually be easily represented as strings.

Figure 9: Mixing and Missing Objects examples

We have the following types of operators in R programming:

·        Arithmetic Operators

·        Relational Operators

·        Logical Operators

·        Assignment Operators

·        Miscellaneous Operators

 

Arithmetic Operators

 

Figure 10: Assignment Operators

 

Relational Operators

Operators

Meaning

> 

Checks if each element of the first vector is greater than the corresponding element of the second vector.

< 

Checks if each element of the first vector is less than the corresponding element of the second vector.

==

Checks if each element of the first vector is equal to the corresponding element of the second vector.

<=

Checks if each element of the first vector is less than or equal to the corresponding element of the second vector.

>=

Checks if each element of the first vector is greater than or equal to the corresponding element of the second vector.

!=

Checks if each element of the first vector is unequal to the corresponding element of the second vector.

 

Logical Operators

Operators

Meaning

&

It is called Element-wise Logical AND operator. It combines each element of the first vector with the corresponding element of the second vector and gives a output TRUE if both the elements are TRUE.

|

It is called Element-wise Logical OR operator. It combines each element of the first vector with the corresponding element of the second vector and gives a output TRUE if one the elements is TRUE.

!

It is called Logical NOT operator. Takes each element of the vector and gives the opposite logical value.

The logical operator && (logical AND) and || (logical OR) considers only the first element of the vectors and give a vector of single element as output.

 

Readers are encouraged to practice all the operators and see the output.

 

 

 

Assignment Operators

A variable in R can store an atomic vector, group of atomic vectors or a combination of many R objects. The variables can be assigned values using leftward, rightward and equal to operator. The values of the variables can be printed using print() or cat() function. The cat() function combines multiple items into a continuous print output.

In R, a variable itself is not declared of any data type, rather it gets the data type of the R -object assigned to it. So R is called a dynamically typed language, which means that we can change a variable’s data type of the same variable again and again when using it in a program.

Figure 11: Variable assignment

 

Figure 12: Listing and deleting variables

 

Miscellaneous Operators

Operators

Meaning

:

Colon operator. It creates the series of numbers in sequence for a vector.

%in%

This operator is used to identify if an element belongs to a vector.

%*%

This operator is used to multiply a matrix with its transpose.

 

 

R provides the following types of decision making statements:

Statement

Description

If statement

An if statement consists of a Boolean expression followed by one or more statements.

If else statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Switch statement

A switch statement allows a variable to be tested for equality against a list of values.

 

Figure 13: Example of If Statement

 

Figure 14: Example of If Else Statement

 

Multiple if else

An if statement can be followed by an optional else if…else statement, which is very

useful to test various conditions using single if…else if statement.

 

Syntax

 

When using if, else if, else statements there are few points to keep in mind.

·        An if can have zero or one else and it must come after any else if’s.

·        An if can have zero to many else if’s and they must come before the else.

·        Once an else if succeeds, none of the remaining else if’s or else’s will be tested.

 

SWITCH statement

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax

 

The following rules apply to a switch statement:

·        If the value of expression is not a character string it is coerced to integer.

·        You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

·        If the value of the integer is between 1 and nargs()-1 (The max number of arguments)then the corresponding element of case condition is evaluated and the

·        result returned.

·        If expression evaluates to a character string then that string is matched (exactly) to the names of the elements.

·        If there is more than one match, the first matching element is returned.

·        No Default argument is available.

·        In the case of no match, if there is a unnamed element of … its value is returned. (If there is more than one such argument an error is returned.)

 

 

Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming- a loop lets you write a very simple statement to produce a significantly greater result simply by repetition. R programming language provides the following kinds of loop to handle looping requirements:

Loop Type

Description

REPEAT loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

WHILE loop

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

FOR loop

It executes a block of statements repeatedly until the specified condition returns false.

 

Look Control Statements

Control Type

Description

BREAK statement

Terminates the loop statement and transfers execution to the statement immediately following the loop.

NEXT statement

The next statement simulates the behavior of R switch (skips the line of execution).

 

REPEAT – loop

The Repeat loop executes the same code again and again until a stop condition is met.

    Syntax:                                                                         Example:

 

 

 

 

 

WHILE – loop

The While loop executes the same code again and again until a stop condition is met.

    Syntax:                                                                         Example:

FOR – loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

    Syntax:                                                                         Example:

Any value written within a pair of single quote or double quotes in R is treated as a string. Internally R stores every string within double quotes, even when you create them with single quote.

 

Rules Applied in String Construction

·     The quotes at the beginning and end of a string should be both double quotes or both single quote. They can not be mixed.

·     Double quotes can be inserted into a string starting and ending with single quote.

·     Single quote can be inserted into a string starting and ending with double quotes.

·     Double quotes can not be inserted into a string starting and ending with double quotes.

·     Single quote can not be inserted into a string starting and ending with single quote.

 

 

 

 

Examples of Strings in R

Formatting numbers & strings – format() function

Numbers and strings can be formatted to a specific style using format()function.

Syntax – The basic syntax for format function is :

 

Following is the description of the parameters used:

·   x is the vector input.

·   digits is the total number of digits displayed.

·   nsmall is the minimum number of digits to the right of the decimal point.

·   scientific is set to TRUE to display scientific notation.

·   width indicates the minimum width to be displayed by padding blanks in the beginning.

·   justify is the display of the string to left, right or center.

 

Other functions

Functions

Functionality

nchar(x)

This function counts the number of characters including spaces in a string.

toupper(x) / tolower(x)

These functions change the case of characters of a string.

substring(x,first,last)

This function extracts parts of a String.

A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions.

The different parts of a function are:

·   Function Name: This is the actual name of the function. It is stored in R environment as an object with this name.

·   Arguments: An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values.

·   Function Body: The function body contains a collection of statements that defines what the function does.

·   Return Value: The return value of a function is the last expression in the function body to be evaluated.

 

R has many in-built functions which can be directly called in the program without defining them first. Simple examples of in-built functions are seq(), mean(), max(), sum(x)and paste(…) etc.

 

We can also create and use our own functions referred as user defined functions. An R function is created by using the keyword function. The basic syntax of an R function definition is as follows:

 

Example: Calling a function with argument values (by position and by name)

 

Example: Calling a function with default values

 

Lazy Evaluation of Function: Arguments to functions are evaluated lazily, which means so they are evaluated only when needed by the function body.

 

 

Vectors are the most basic R data objects and there are six types of atomic vectors. They are logical, integer, double, complex, character and raw. Even when you write just one value in R, it becomes a vector of length 1 and belongs to one of the above vector types.

# Atomic vector of type character.

print(“ABC”);

[1] “ABC”

# Atomic vector of type double.

print (1.2)

[1] 12.5

# Atomic vector of type integer.

print(10L)

[1] 10

# Atomic vector of type logical.

print(TRUE)

[1] TRUE

# Atomic vector of type complex.

print(4+8i)

[1] 4+8i

# Atomic vector of type raw.

print(charToRaw(‘hello’))

[1] 68 65 6c 6c 6f

 

Multiple Elements Vector

Using colon operator with numeric data

# Creating a sequence from 2 to 8.

v <- 2:8

print(v)

[1] 2 3 4 5 6 7 8

# Creating a sequence from 6.6 to 12.6.

v <- 6.6:12.6

print(v)

[1] 6.6 7.6 8.6 9.6 10.6 11.6 12.6

# If the final element specified does not belong to the sequence then it is discarded.

v <- 3.8:11.4

print(v)

[1] 3.8 4.8 5.8 6.8 7.8 8.8 9.8 10.8

 

Using sequence (Seq.) operator

Syntax and example of using Seq. operator:

# # Create vector with elements from 5 to 9 incrementing by 0.4.

print (seq(5, 9, by=0.4))

[1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0

 

Using the c () function

The non-character values are coerced to character type if one of the elements is a char.

Syntax and example of using c() function:

##  The logical and numeric values are converted to characters.

x <- c(‘apple’, ‘red’, 5, TRUE)

print(x)

[1] “apple” “red” “5” “TRUE”

Accessing Vector Elements

Elements of a Vector are accessed using indexing. The [ ] brackets are used for indexing. Indexing starts with position 1. Giving a negative value in the index drops that element from result. TRUE, FALSE or 0 and 1 can also be used for indexing.

Syntax and example:

# Accessing vector elements using position.

t <- c(“Sun”,”Mon”,”Tue”,”Wed”,”Thurs”,”Fri”,”Sat”)

u <- t[c(2,3,6)]

print(u)

[1] “Mon” “Tue” “Fri”

 

# Accessing vector elements using logical indexing.

v <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)]

print(v)

[1] “Sun” “Fri”

 

# Accessing vector elements using negative indexing.

x <- t[c(-2,-5)]

print(x)

[1] “Sun” “Tue” “Wed” “Fri” “Sat”

 

# Accessing vector elements using 0/1 indexing.

y <- t[c(0,0,0,0,0,0,1)]

print(y)

[1] “Sun”

 

Vector Manipulation

Vector Arithmetic- Two vectors of same length can be added, subtracted, multiplied or divided giving the result as a vector output.

Syntax and example:

# Create two vectors.

v1 <- c(3,8,4,5,0,11)

v2 <- c(4,11,0,8,1,2)

 

# Vector addition.

add.result <- v1+v2

print(add.result)

[1] 7 19 4 13 1 13

 

# Vector substraction.

sub.result <- v1-v2

print(sub.result)

[1] -1 -3 4 -3 -1 9

 

# Vector multiplication.

multi.result <- v1*v2

print(multi.result)

[1] 12 88 0 40 0 22

 

# Vector division.

divi.result <- v1/v2

print(divi.result)

[1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000

 

Vector Element Recycling

If we apply arithmetic operations to two vectors of unequal length, then the elements of the shorter vector are recycled to complete the operations.

Syntax and example:

v1 <- c(3,8,4,5,0,11)

v2 <- c(4,11)

# V2 becomes c(4,11,4,11,4,11)

add.result <- v1+v2

print(add.result)

[1] 7 19 8 16 4 22

 

sub.result <- v1-v2

print(sub.result)

[1] -1 -3 0 -6 -4 0

 

Vector Element Sorting

Elements in a vector can be sorted using the sort() function.

Syntax and example:

v <- c(3,8,4,5,0,11, -9, 304)

# Sort the elements of the vector.

sort.result <- sort(v)

print(sort.result)

[1] -9 0 3 4 5 8 11 304

 

# Sort the elements in the reverse order.

revsort.result <- sort(v, decreasing = TRUE)

print(revsort.result)

[1] 304 11 8 5 4 3 0 -9

 

 

# Sorting character vectors.

v <- c(“Red”,”Blue”,”yellow”,”violet”)

sort.result <- sort(v)

print(sort.result)

[1] “Blue” “Red” “violet” “yellow”

 

# Sorting character vectors in reverse order.

revsort.result <- sort(v, decreasing = TRUE)

print(revsort.result)

[1] “yellow” “violet” “Red” “Blue”

 

Lists are the R objects which contain elements of different types like – numbers, strings, vectors and another list inside it. A list can also contain a matrix or a function as its elements. List is created using list() function.

 

Syntax and example:

## Create a list containing strings, numbers, vectors and a logical values.

list_data <- list(“Red”, “Green”, c(21,32,11), TRUE, 51.23, 119.1)

print(list_data)

 

[[1]]

[1] “Red”

[[2]]

[1] “Green”

[[3]]

[1] 21 32 11

[[4]]

[1] TRUE

[[5]]

[1] 51.23

[[6]]

[1] 119.1

 

Naming List Elements

The list elements can be given names and they can be accessed using these names.

 

Manipulating List Elements

We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list. But we can update any element.

 

Merging Lists

You can merge many lists into one list by placing all the lists inside one list() function.

Converting Lists to Vector

A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this conversion, we use the unlist() function. It takes the list as input and produces a vector.

 

Matrices are the R objects in which the elements are arranged in a two-dimensional

format. They contain elements of the same atomic types. But we use matrices containing numeric elements to be used in mathematical calculations. A Matrix is created using the matrix() function.

 

Syntax

Parameters used:

·        data is the input vector which becomes the data elements of the matrix.

·        nrow is the number of rows to be created.

·        ncol is the number of columns to be created.

·        byrow is a logical clue. If TRUE then the input vector elements are arranged by row.

·        dimname is the names assigned to the rows and columns.

# Elements are arranged sequentially by row.

M <- matrix(c(3:14), nrow=4, byrow=TRUE)

print(M)

# Elements are arranged sequentially by column.

N <- matrix(c(3:14), nrow=4, byrow=FALSE)

print(N)

# Define the column and row names.

rownames = c(“row1”, “row2”, “row3”, “row4”)

colnames = c(“col1”, “col2”, “col3”)

 

# Accessing Elements of a Matrix

# Access the element at 3rd column and 1st row.

print(N[1,3])

# Access the element at 2nd column and 4th row.

print(N[4,2])

 

# Access only the 2nd row.

print(N[2,])

# Access only the 3rd column.

print(N[,3])

 

Matrix Computations

Various mathematical operations are performed on the matrices using the R operators. The result of the operation is also a matrix. The dimensions (number of rows and columns) should be same for the matrices involved in the operation.

# Create two 2×3 matrices.

matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow=2)

print(matrix1)

matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow=2)

print(matrix2)

# Add the matrices.

result <- matrix1 + matrix2

cat(“Result of addition”,”\n”)

print(result)

# Subtract the matrices

result <- matrix1 – matrix2

cat(“Result of subtraction”,”\n”)

print(result)

 

Matrix Multiplication & Division

# Create two 2×3 matrices.

matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow=2)

print(matrix1)

matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow=2)

print(matrix2)

# Multiply the matrices.

result <- matrix1 * matrix2

cat(“Result of multiplication”,”\n”)

print(result)

# Divide the matrices

result <- matrix1 / matrix2

cat(“Result of division”,”\n”)

print(result)

 

Arrays are the R data objects which can store data in more than two dimensions. For example – If we create an array of dimension (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3 columns. Arrays can store only data type. An array is created using the array() function. It takes vectors as input and uses the values in the dim parameter to create an array.

 

# Create two vectors of different lengths.

vector1 <- c(5,9,3)

vector2 <- c(10,11,12,13,14,15)

# Take these vectors as input to the array.

result <- array(c(vector1,vector2),dim=c(3,3,2))

print(result)

 

Naming Columns and Rows: We can give names to the rows, columns and matrices in the array by using the dimnames parameter.

# Create two vectors of different lengths.

vector1 <- c(5,9,3)

vector2 <- c(10,11,12,13,14,15)

column.names <- c(“COL1″,”COL2″,”COL3”)

row.names <- c(“ROW1″,”ROW2″,”ROW3”)

matrix.names <- c(“Matrix1″,”Matrix2”)

# Take these vectors as input to the array.

result <- array(c(vector1,vector2),dim=c(3,3,2),dimnames =

                  list(column.names,row.names,matrix.names))

print(result)

 

Accessing Array Elements

# Create two vectors of different lengths.

vector1 <- c(5,9,3)

vector2 <- c(10,11,12,13,14,15)

column.names <- c(“COL1″,”COL2″,”COL3”)

row.names <- c(“ROW1″,”ROW2″,”ROW3”)

matrix.names <- c(“Matrix1″,”Matrix2”)

# Take these vectors as input to the array.

result <- array(c(vector1,vector2),dim=c(3,3,2),dimnames =

                  list(column.names,row.names,matrix.names))

# Print the third row of the second matrix of the array.

print(result[3,,2])

# Print the element in the 1st row and 3rd column of the 1st matrix.

print(result[1,3,1])

# Print the 2nd Matrix.

print(result[,,2])

 

Manipulating Array Elements

As array is made up matrices in multiple dimensions, the operations on elements of array are carried out by accessing elements of the matrices.

# Create two vectors of different lengths.

vector1 <- c(5,9,3)

vector2 <- c(10,11,12,13,14,15)

# Take these vectors as input to the array.

array1 <- array(c(vector1,vector2),dim=c(3,3,2))

# Create two vectors of different lengths.

vector3 <- c(9,1,0)

vector4 <- c(6,0,11,3,14,1,2,6,9)

array2 <- array(c(vector1,vector2),dim=c(3,3,2))

# create matrices from these arrays.

matrix1 <- array1[,,2]

matrix2 <- array2[,,2]

# Add the matrices.

result <- matrix1+matrix2

print(result)

 

Calculations Across Array Elements: We can do calculations across the elements in an array using the apply() function.

 

Syntax

 

Parameters used:

·        x is an array.

·        margin is the name of the data set used.

·        fun is the function to be applied across the elements of the array.

 

 

We use the apply() function below to calculate the sum of the elements in the rows of an array across all the matrices.

# Create two vectors of different lengths.

vector1 <- c(5,9,3)

vector2 <- c(10,11,12,13,14,15)

# Take these vectors as input to the array.

new.array <- array(c(vector1,vector2),dim=c(3,3,2))

print(new.array)

# Use apply to calculate the sum of the rows across all the matrices.

result <- apply(new.array, c(1), sum)

print(result)

 

Array indexing. Subsections of an array

Individual elements of an array may be referenced by giving the name of the array followed by

the subscripts in square brackets, separated by commas.

More generally, subsections of an array may be specified by giving a sequence of index vectors

in place of subscripts; however if any index position is given an empty index vector, then the full

range of that subscript is taken.

Continuing the previous example, a[2,,] is a 42 array with dimension vector c(4,2) and

data vector containing the values

c(a[2,1,1], a[2,2,1], a[2,3,1], a[2,4,1],

a[2,1,2], a[2,2,2], a[2,3,2], a[2,4,2])

in that order. a[,,] stands for the entire array, which is the same as omitting the subscripts

entirely and using a alone.

For any array, say Z, the dimension vector may be referenced explicitly as dim(Z) (on either

side of an assignment).

Also, if an array name is given with just one subscript or index vector, then the corresponding

values of the data vector only are used; in this case the dimension vector is ignored. This is not

the case, however, if the single index is not a vector but itself an array, as we next discuss.

 

Factors are the data objects which are used to categorize the data and store it as levels. They can store both strings and integers. They are useful in the columns which have a limited number of unique values. Like “Male, “Female” and True, False etc. They are useful in data analysis for statistical modeling.

A factor is a vector object used to specify a discrete classification (grouping) of the components

of other vectors of the same length. R provides both ordered and unordered factors. While the

“real” application of factors is with model formulae (see Section 11.1.1 [Contrasts], page 53), we

here look at a specific example.

4.1 A specific example

Suppose, for example, we have a sample of 30 tax accountants from all the states and territories

of Australia1 and their individual state of origin is specified by a character vector of state

mnemonics as

> state <- c(“tas”, “sa”, “qld”, “nsw”, “nsw”, “nt”, “wa”, “wa”,

“qld”, “vic”, “nsw”, “vic”, “qld”, “qld”, “sa”, “tas”,

“sa”, “nt”, “wa”, “vic”, “qld”, “nsw”, “nsw”, “wa”,

“sa”, “act”, “nsw”, “vic”, “vic”, “act”)

Notice that in the case of a character vector, “sorted” means sorted in alphabetical order.

A factor is similarly created using the factor() function:

> statef <- factor(state)

The print() function handles factors slightly differently from other objects:

> statef

[1] tas sa qld nsw nsw nt wa wa qld vic nsw vic qld qld sa

[16] tas sa nt wa vic qld nsw nsw wa sa act nsw vic vic act

Levels: act nsw nt qld sa tas vic wa

To find out the levels of a factor the function levels() can be used.

> levels(statef)

[1] “act” “nsw” “nt” “qld” “sa” “tas” “vic” “wa”

4.2 The function tapply() and ragged arrays

To continue the previous example, suppose we have the incomes of the same tax accountants in

another vector (in suitably large units of money)

> incomes <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56,

61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,

59, 46, 58, 43)

To calculate the sample mean income for each state we can now use the special function

tapply():

> incmeans <- tapply(incomes, statef, mean)

giving a means vector with the components labelled by the levels

act nsw nt qld sa tas vic wa

44.500 57.333 55.500 53.600 55.000 60.500 56.000 52.250

The function tapply() is used to apply a function, here mean(), to each group of components

of the first argument, here incomes, defined by the levels of the second component, here statef2, as if they were separate vector structures. The result is a structure of the same length as the

levels attribute of the factor containing the results. The reader should consult the help document

for more details.

Suppose further we needed to calculate the standard errors of the state income means. To do

this we need to write an R function to calculate the standard error for any given vector. Since

there is an builtin function var() to calculate the sample variance, such a function is a very

simple one liner, specified by the assignment:

> stdError <- function(x) sqrt(var(x)/length(x))

(Writing functions will be considered later in Chapter 10 [Writing your own functions], page 42.

Note that R’s a builtin function sd() is something different.) After this assignment, the standard

errors are calculated by

> incster <- tapply(incomes, statef, stderr)

and the values calculated are then

> incster

act nsw nt qld sa tas vic wa

1.5 4.3102 4.5 4.1061 2.7386 0.5 5.244 2.6575

As an exercise you may care to find the usual 95% confidence limits for the state mean

incomes. To do this you could use tapply() once more with the length() function to find

the sample sizes, and the qt() function to find the percentage points of the appropriate t-

distributions. (You could also investigate R’s facilities for t-tests.)

The function tapply() can also be used to handle more complicated indexing of a vector

by multiple categories. For example, we might wish to split the tax accountants by both state

and sex. However in this simple instance (just one factor) what happens can be thought of as

follows. The values in the vector are collected into groups corresponding to the distinct entries

in the factor. The function is then applied to each of these groups individually. The value is a

vector of function results, labelled by the levels attribute of the factor.

The combination of a vector and a labelling factor is an example of what is sometimes called

a ragged array, since the subclass sizes are possibly irregular. When the subclass sizes are all

the same the indexing may be done implicitly and much more efficiently, as we see in the next

section.

4.3 Ordered factors

The levels of factors are stored in alphabetical order, or in the order they were specified to

factor if they were specified explicitly.

Sometimes the levels will have a natural ordering that we want to record and want our

statistical analysis to make use of. The ordered() function creates such ordered factors but

is otherwise identical to factor. For most purposes the only difference between ordered and

unordered factors is that the former are printed showing the ordering of the levels, but the

contrasts generated for them in fitting linear models are different.

 

Factors are created using the factor () function by taking a vector as input.

Factors are categorical variables that are super useful in summary statistics, plots, and regressions. They basically act like dummy variables that R codes for you.  So, let’s start off with some data:

and let’s check out what kinds of variables we have:

 

so we see that Race is a factor variable with three levels.  I can see all the levels this way:

So what his means that R groups statistics by these levels.  Internally, R stores the integer values 1, 2, and 3, and maps the character strings (in alphabetical order, unless I reorder) to these values, i.e. 1=Black, 2=Hispanic, and 3=White.  Now if I were to do a summary of this variable, it shows me the counts for each category, as below.  R won’t let me do a mean or any other statistic of a factor variable other than a count, so keep that in mind. But you can always change your factor to be numeric.

If I do a plot of age on race, I get a boxplot from the normal plot command since that is what makes sense for a categorical variable:

 

plot(mydata$Age~mydata$Race, xlab=”Race”, ylab=”Age”, main=”Boxplots of Age by Race”)

# Create a vector as input.

data <-

  c(“East”,”West”,”East”,”North”,”North”,”East”,”West”,”West”,”West”,”East”,”North”)

print(data)

print(is.factor(data))

# Apply the factor function.

factor_data <- factor(data)

print(factor_data)

print(is.factor(factor_data))

 

Factors in Data Frame

On creating any data frame with a column of text data, R treats the text column as categorical data and creates factors on it.

# Create the vectors for data frame.

height <- c(132,151,162,139,166,147,122)

weight <- c(48,49,66,53,67,52,40)

gender <- c(“male”,”male”,”female”,”female”,”male”,”female”,”male”)

# Create the data frame.

input_data <- data.frame(height,weight,gender)

print(input_data)

# Test if the gender column is a factor.

print(is.factor(input_data$gender))

# Print the gender column so see the levels.

print(input_data$gender)

 

Changing the Order of Levels: The order of the levels in a factor can be changed by applying the factor function again with new order of the levels.

data <-

  c(“East”,”West”,”East”,”North”,”North”,”East”,”West”,”West”,”West”,”East”,”North”)

# Create the factors

factor_data <- factor(data)

print(factor_data)

# Apply the factor function with required order of the level.

new_order_data <- factor(factor_data,levels = c(“East”,”West”,”North”))

print(new_order_data)

 

Generating Factor Levels: We can generate factor levels by using the gl() function. It takes two integers as input which indicates how many levels and how many times each level.

Syntax: gl(n, k, labels)

 

Following is the description of the parameters used:

·        n is a integer giving the number of levels.

·        k is a integer giving the number of replications.

·        labels is a vector of labels for the resulting factor levels.

v <- gl(3, 4, labels = c(“Tampa”, “Seattle”,”Boston”))

print(v)

 

 

A data frame is a table or a two-dimensional array-like structure in which each column contains values of one variable and each row contains one set of values from each column. Following are the characteristics of a data frame:

·        The column names should be non-empty.

·        The row names should be unique.

·        The data stored in a data frame can be of numeric, factor or character type.

·        Each column should contain same number of data items.

 

# Create the data frame.

emp.data <- data.frame(

  emp_id = c (1:5),

  emp_name = c(“Rick”,”Dan”,”Michelle”,”Ryan”,”Gary”),

  salary = c(623.3,515.2,611.0,729.0,843.25),

  start_date = as.Date(c(“2012-01-01″,”2013-09-23″,”2014-11-15”,”2014-05-

                         11″,”2015-03-27″)),

  stringsAsFactors=FALSE

  )

# Print the data frame.

print(emp.data)

 

Get the Structure of the Data Frame: The structure of the data frame can be seen by using str() function.

# Create the data frame.

emp.data <- data.frame(

emp_id = c (1:5),

emp_name = c(“Rick”,”Dan”,”Michelle”,”Ryan”,”Gary”),

salary = c(623.3,515.2,611.0,729.0,843.25),

start_date = as.Date(c(“2012-01-01″,”2013-09-23″,”2014-11-15”,”2014-05-

11″,”2015-03-27″)),

stringsAsFactors=FALSE

)

# Get the structure of the data frame.

str(emp.data)

 

Summary of Data in Data Frame

The statistical summary and nature of the data can be obtained by applying summary() function.

# Create the data frame.

emp.data <- data.frame(

emp_id = c (1:5),

emp_name = c(“Rick”,”Dan”,”Michelle”,”Ryan”,”Gary”),

salary = c(623.3,515.2,611.0,729.0,843.25),

start_date = as.Date(c(“2012-01-01″,”2013-09-23″,”2014-11-15”,”2014-05-

11″,”2015-03-27″)),

stringsAsFactors=FALSE

)

# Print the summary.

print(summary(emp.data))

 

Extract Data from Data Frame

Extract specific column from a data frame using column name.

# Create the data frame.

emp.data <- data.frame(

  emp_id = c (1:5),

  emp_name = c(“Rick”,”Dan”,”Michelle”,”Ryan”,”Gary”),

  salary = c(623.3,515.2,611.0,729.0,843.25),

  start_date = as.Date(c(“2012-01-01″,”2013-09-23″,”2014-11-15”,”2014-05-

                         11″,”2015-03-27″)),

  stringsAsFactors=FALSE

  )

# Extract Specific columns.

result <- data.frame(emp.data$emp_name,emp.data$salary)

print(result)

 

# Extract 3rd and 5th row with 2nd and 4th column.

result <- emp.data[c(3,5),c(2,4)]

print(result)

 

# Extract first two rows.

result <- emp.data[1:2,]

print(result)

 

# Expand Data Frame – A data frame can be expanded by adding columns and rows.

# Add the “dept” coulmn.

emp.data$dept <- c(“IT”,”Operations”,”IT”,”HR”,”Finance”)

v <- emp.data

print(v)

 

 

Add Row

To add more rows permanently to an existing data frame, we need to bring in the new rows in the same structure as the existing data frame and use the rbind() function. In the example below we create a data frame with new rows and merge it with the existing data frame to create the final data frame.

# Create the first data frame.

emp.data <- data.frame(

  emp_id = c (1:5),

  emp_name = c(“Rick”,”Dan”,”Michelle”,”Ryan”,”Gary”),

  salary = c(623.3,515.2,611.0,729.0,843.25),

  start_date = as.Date(c(“2012-01-01″,”2013-09-23″,”2014-11-15”,”2014-05-

                         11″,”2015-03-27″)),

  dept=c(“IT”,”Operations”,”IT”,”HR”,”Finance”),

  stringsAsFactors=FALSE

)

# Create the second data frame

emp.newdata <- data.frame(

  emp_id = c (6:8),

  emp_name = c(“Rasmi”,”Pranab”,”Tusar”),

  salary = c(578.0,722.5,632.8),

  start_date = as.Date(c(“2013-05-21″,”2013-07-30″,”2014-06-17”)),

  dept = c(“IT”,”Operations”,”Fianance”),

  stringsAsFactors=FALSE

)

# Bind the two data frames.

emp.finaldata <- rbind(emp.data,emp.newdata)

print(emp.finaldata)

 

Unit 4: Simple manipulations; numbers and vectors

Vectors and assignment

R operates on named data structures. The simplest such structure is the numeric vector, which is a single entity consisting of an ordered collection of numbers. To set up a vector named x, say, consisting of five numbers, namely 10.4, 5.6, 3.1, 6.4 and 21.7, use the R command

> x <- c(10.4, 5.6, 3.1, 6.4, 21.7)

 

This is an assignment statement using the function c() which in this context can take an arbitrary number of vector arguments and whose value is a vector got by concatenating its

arguments end to end. A number occurring by itself in an expression is taken as a vector of length one. Notice that the assignment operator (‘<-’), which consists of the two characters ‘<’ (“less than”) and ‘-’ (“minus”) occurring strictly side-by-side and it ‘points’ to the object receiving the value of the expression. In most contexts the ‘=’ operator can be used as an alternative. Assignment can also be made using the function assign(). An equivalent way of making the same assignment as above is with:

> assign(“x”, c(10.4, 5.6, 3.1, 6.4, 21.7))

The usual operator, <-, can be thought of as a syntactic short-cut to this.

Assignments can also be made in the other direction, using the obvious change in the assignment operator. So the same assignment could be made using

> c(10.4, 5.6, 3.1, 6.4, 21.7) -> x

If an expression is used as a complete command, the value is printed and lost 2. So now if we

were to use the command

> 1/x

the reciprocals of the five values would be printed at the terminal (and the value of x, of course, unchanged).

The further assignment

> y <- c(x, 0, x)

would create a vector y with 11 entries consisting of two copies of x with a zero in the middle

place.

 

Vector arithmetic

Vectors can be used in arithmetic expressions, in which case the operations are performed element by element. Vectors occurring in the same expression need not all be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression. Shorter vectors in the expression are recycled as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant is simply repeated. So with the above assignments the command

> v <- 2*x + y + 1

generates a new vector v of length 11 constructed by adding together, element by element, 2*x repeated 2.2 times, y repeated just once, and 1 repeated 11 times.

 

The elementary arithmetic operators are the usual +, -, *, / and ^ for raising to a power. In

addition all of the common arithmetic functions are available. log, exp, sin, cos, tan, sqrt,

and so on, all have their usual meaning. max and min select the largest and smallest elements of a vector respectively. range is a function whose value is a vector of length two, namely c(min(x), max(x)). length(x) is the number of elements in x, sum(x) gives the total of the elements in x, and prod(x) their product.

Two statistical functions are mean(x) which calculates the sample mean, which is the same

as sum(x)/length(x), and var(x) which gives sum((x-mean(x))^2)/(length(x)-1)

 

or sample variance. If the argument to var() is an n-by-p matrix the value is a p-by-p sample

covariance matrix got by regarding the rows as independent p-variate sample vectors.

sort(x) returns a vector of the same size as x with the elements arranged in increasing order;

however there are other more flexible sorting facilities available (see order() or sort.list()

which produce a permutation to do the sorting).

Note that max and min select the largest and smallest values in their arguments, even if they

are given several vectors. The parallel maximum and minimum functions pmax and pmin return a vector (of length equal to their longest argument) that contains in each element the largest (smallest) element in that position in any of the input vectors.

For most purposes the user will not be concerned if the “numbers” in a numeric vector

are integers, reals or even complex. Internally calculations are done as double precision real

numbers, or double precision complex numbers if the input data are complex.

 

To work with complex numbers, supply an explicit complex part. Thus

sqrt(-17)    :    will give NaN and a warning, but

sqrt(-17+0i)     :    will do the computations as complex numbers.

 

Generating regular sequences

R has a number of facilities for generating commonly used sequences of numbers. For example

1:30 is the vector c(1, 2, …, 29, 30). The colon operator has high priority within an expression,

so, for example 2*1:15 is the vector c(2, 4, …, 28, 30). Put n <- 10 and compare

the sequences 1:n-1 and 1:(n-1).

The construction 30:1 may be used to generate a sequence backwards.

The function seq() is a more general facility for generating sequences. It has five arguments,

only some of which may be specified in any one call. The first two arguments, if given, specify

the beginning and end of the sequence, and if these are the only two arguments given the result is the same as the colon operator. That is seq(2,10) is the same vector as 2:10.

Arguments to seq(), and to many other R functions, can also be given in named form, in

which case the order in which they appear is irrelevant. The first two arguments may be named from=value and to=value; thus seq(1,30), seq(from=1, to=30) and seq(to=30, from=1)

are all the same as 1:30. The next two arguments to seq() may be named by=value and

length=value, which specify a step size and a length for the sequence respectively. If neither

of these is given, the default by=1 is assumed.

For example

> seq(-5, 5, by=.2) -> s3

generates in s3 the vector c(-5.0, -4.8, -4.6, …, 4.6, 4.8, 5.0). Similarly

> s4 <- seq(length=51, from=-5, by=.2)

generates the same vector in s4.

The fifth argument may be named along=vector, which is normally used as the only argument

to create the sequence 1, 2, …, length(vector), or the empty sequence if the vector

is empty (as it can be).

A related function is rep() which can be used for replicating an object in various complicated

ways. The simplest form is

> s5 <- rep(x, times=5)

which will put five copies of x end-to-end in s5. Another useful version is

> s6 <- rep(x, each=5)

which repeats each element of x five times before moving on to the next.

 

Logical vectors

As well as numerical vectors, R allows manipulation of logical quantities. The elements of a

logical vector can have the values TRUE, FALSE, and NA (for “not available”). The

first two are often abbreviated as T and F, respectively. Note however that T and F are just

variables which are set to TRUE and FALSE by default, but are not reserved words and hence can be overwritten by the user. Hence, you should always use TRUE and FALSE.

Logical vectors are generated by conditions. For example

> temp <- x > 13

sets temp as a vector of the same length as x with values FALSE corresponding to elements of x where the condition is not met and TRUE where it is.

The logical operators are <, <=, >, >=, == for exact equality and != for inequality. In addition

if c1 and c2 are logical expressions, then c1 & c2 is their intersection (“and”), c1 | c2 is their

union (“or”), and !c1 is the negation of c1.

Logical vectors may be used in ordinary arithmetic, in which case they are coerced into

numeric vectors, FALSE becoming 0 and TRUE becoming 1. However there are situations where logical vectors and their coerced numeric counterparts are not equivalent, for example see the next subsection.

 

Missing values

In some cases the components of a vector may not be completely known. When an element

or value is “not available” or a “missing value” in the statistical sense, a place within a vector

may be reserved for it by assigning it the special value NA. In general, any operation on an NA

becomes an NA. The motivation for this rule is simply that if the specification of an operation

is incomplete, the result cannot be known and hence is not available.

The function is.na(x) gives a logical vector of the same size as x with value TRUE if and

only if the corresponding element in x is NA.

> z <- c(1:3,NA); ind <- is.na(z)

Notice that the logical expression x == NA is quite different from is.na(x) since NA is not

really a value but a marker for a quantity that is not available. Thus x == NA is a vector of the

same length as x all of whose values are NA as the logical expression itself is incomplete and

hence undecidable.

Note that there is a second kind of “missing” values which are produced by numerical computation, the so-called Not a Number, NaN, values. Examples are

> 0/0

or

> Inf – Inf

which both give NaN since the result cannot be defined sensibly.

In summary, is.na(xx) is TRUE both for NA and NaN values. To differentiate these,

is.nan(xx) is only TRUE for NaNs.

Missing values are sometimes printed as <NA> when character vectors are printed without

quotes.

2.6 Character vectors

Character quantities and character vectors are used frequently in R, for example as plot labels.

Where needed they are denoted by a sequence of characters delimited by the double quote

character, e.g., “x-values”, “New iteration results”.

Character strings are entered using either matching double (“) or single (’) quotes, but are

printed using double quotes (or sometimes without quotes). They use C-style escape sequences,

using \ as the escape character, so \\ is entered and printed as \\, and inside double quotes “

is entered as \”. Other useful escape sequences are \n, newline, \t, tab and \b, backspace—see

?Quotes for a full list.

Character vectors may be concatenated into a vector by the c() function; examples of their

use will emerge frequently.

The paste() function takes an arbitrary number of arguments and concatenates them one by

one into character strings. Any numbers given among the arguments are coerced into character

strings in the evident way, that is, in the same way they would be if they were printed. The

arguments are by default separated in the result by a single blank character, but this can be

changed by the named argument, sep=string, which changes it to string, possibly empty.

For example

> labs <- paste(c(“X”,”Y”), 1:10, sep=””)

makes labs into the character vector

c(“X1”, “Y2”, “X3”, “Y4”, “X5”, “Y6”, “X7”, “Y8”, “X9”, “Y10”)

Note particularly that recycling of short lists takes place here too; thus c(“X”, “Y”) is

repeated 5 times to match the sequence 1:10.3

2.7 Index vectors; selecting and modifying subsets of a data set

Subsets of the elements of a vector may be selected by appending to the name of the vector an

index vector in square brackets. More generally any expression that evaluates to a vector may

have subsets of its elements similarly selected by appending an index vector in square brackets

immediately after the expression.

Such index vectors can be any of four distinct types.

1. A logical vector. In this case the index vector is recycled to the same length as the vector

from which elements are to be selected. Values corresponding to TRUE in the index vector

are selected and those corresponding to FALSE are omitted. For example

> y <- x[!is.na(x)]

creates (or re-creates) an object y which will contain the non-missing values of x, in the

same order. Note that if x has missing values, y will be shorter than x. Also

> (x+1)[(!is.na(x)) & x>0] -> z

creates an object z and places in it the values of the vector x+1 for which the corresponding

value in x was both non-missing and positive.

 

2. A vector of positive integral quantities. In this case the values in the index vector must lie

in the set f1, 2, . . . , length(x)g. The corresponding elements of the vector are selected and

concatenated, in that order, in the result. The index vector can be of any length and the

result is of the same length as the index vector. For example x[6] is the sixth component

of x and

> x[1:10]

selects the first 10 elements of x (assuming length(x) is not less than 10). Also

> c(“x”,”y”)[rep(c(1,2,2,1), times=4)]

(an admittedly unlikely thing to do) produces a character vector of length 16 consisting of

“x”, “y”, “y”, “x” repeated four times.

3. A vector of negative integral quantities. Such an index vector specifies the values to be

excluded rather than included. Thus

> y <- x[-(1:5)]

gives y all but the first five elements of x.

4. A vector of character strings. This possibility only applies where an object has a names

attribute to identify its components. In this case a sub-vector of the names vector may be

used in the same way as the positive integral labels in item 2 further above.

> fruit <- c(5, 10, 1, 20)

> names(fruit) <- c(“orange”, “banana”, “apple”, “peach”)

> lunch <- fruit[c(“apple”,”orange”)]

The advantage is that alphanumeric names are often easier to remember than numeric

indices. This option is particularly useful in connection with data frames, as we shall see

later.

An indexed expression can also appear on the receiving end of an assignment, in which case

the assignment operation is performed only on those elements of the vector. The expression

must be of the form vector[index_vector] as having an arbitrary expression in place of the

vector name does not make much sense here.

For example

> x[is.na(x)] <- 0

replaces any missing values in x by zeros and

> y[y < 0] <- -y[y < 0]

has the same effect as

> y <- abs(y)

2.8 Other types of objects

Vectors are the most important type of object in R, but there are several others which we will

meet more formally in later sections.

matrices or more generally arrays are multi-dimensional generalizations of vectors. In fact,

they are vectors that can be indexed by two or more indices and will be printed in special

ways. See Chapter 5 [Arrays and matrices], page 18.

factors provide compact ways to handle categorical data. See Chapter 4 [Factors], page 16.

lists are a general form of vector in which the various elements need not be of the same

type, and are often themselves vectors or lists. Lists provide a convenient way to return the

results of a statistical computation. See Section 6.1 [Lists], page 26.

data frames are matrix-like structures, in which the columns can be of different types. Think

of data frames as ‘data matrices’ with one row per observational unit but with (possibly) both numerical and categorical variables. Many experiments are best described by data

frames: the treatments are categorical but the response is numeric. See Section 6.3 [Data

frames], page 27.

functions are themselves objects in R which can be stored in the project’s workspace. This

provides a simple and convenient way to extend R. See Chapter 10 [Writing your own

functions], page 42.

Objects, their modes and attributes

 

Changing the length of an object

An “empty” object may still have a mode. For example

> e <- numeric()

makes e an empty vector structure of mode numeric. Similarly character() is a empty character

vector, and so on. Once an object of any size has been created, new components may be added

to it simply by giving it an index value outside its previous range. Thus

> e[3] <- 17

now makes e a vector of length 3, (the first two components of which are at this point both NA).

This applies to any structure at all, provided the mode of the additional component(s) agrees

with the mode of the object in the first place.

This automatic adjustment of lengths of an object is used often, for example in the scan()

function for input. (see Section 7.2 [The scan() function], page 31.)

Conversely to truncate the size of an object requires only an assignment to do so. Hence if

alpha is an object of length 10, then

> alpha <- alpha[2 * 1:5]

makes it an object of length 5 consisting of just the former components with even index. (The

old indices are not retained, of course.) We can then retain just the first three values by

> length(alpha) <- 3

and vectors can be extended (by missing values) in the same way.

3.3 Getting and setting attributes

The function attributes(object) returns a list of all the non-intrinsic attributes currently

defined for that object. The function attr(object, name) can be used to select a specific

attribute. These functions are rarely used, except in rather special circumstances when some

new attribute is being created for some particular purpose, for example to associate a creation

date or an operator with an R object. The concept, however, is very important.

Some care should be exercised when assigning or deleting attributes since they are an integral

part of the object system used in R.

When it is used on the left hand side of an assignment it can be used either to associate a

new attribute with object or to change an existing one. For example

> attr(z, “dim”) <- c(10,10)

allows R to treat z as if it were a 10-by-10 matrix.

3.4 The class of an object

All objects in R have a class, reported by the function class. For simple vectors this is just the

mode, for example “numeric”, “logical”, “character” or “list”, but “matrix”, “array”,

“factor” and “data.frame” are other possible values.

A special attribute known as the class of the object is used to allow for an object-oriented

style4 of programming in R. For example if an object has class “data.frame”, it will be printed

in a certain way, the plot() function will display it graphically in a certain way, and other

so-called generic functions such as summary() will react to it as an argument in a way sensitive

to its class.

To remove temporarily the effects of class, use the function unclass(). For example if winter

has the class “data.frame” then

> winter

 

will print it in data frame form, which is rather like a matrix, whereas

> unclass(winter)

will print it as an ordinary list. Only in rather special situations do you need to use this facility,

but one is when you are learning to come to terms with the idea of class and generic functions.

Generic functions and classes will be discussed further in Section 10.9 [Object orientation],

page 48, but only briefly.

 

 

 

 

Importing and manipulating your data are important steps in the data science workflow. R allows for the import of different data formats using specific packages that can make your job easier:

·        readr for importing flat files

·        The readxl package for getting excel files into R

·        The haven package lets you import SAS, STATA and SPSS data files into R.

·        Databases: connect via packages like RMySQL and RpostgreSQL, and access and manipulate via DBI

·        rvest for webscraping

 

Once your data is available in your working environment you are ready to start manipulating it using these packages:

·        The tidyr package for tidying your data.

·        The stringr package for string manipulation.

·        For data frame like objects learn the ins and outs of the dplyr package

·        Need to perform heavy data wrangling tasks? Check out the data.table package

·        Performing time series analysis? Try out packages like like zoo, xts and quantmod.

 

Let’s practice

 

# Get and print current working directory.

print(getwd())

 

#Reading a CSV File

data <- read.csv(“input.csv”)

print(data)

 

# Analyzing the CSV File

data <- read.csv(“input.csv”)

print(is.data.frame(data))

print(ncol(data))

print(nrow(data))

 

#Get the maximum salary:

# Create a data frame.

data <- read.csv(“input.csv”)

# Get the max salary from data frame.

sal <- max(data$salary)

print(sal)

 

# Get the max salary from data frame.

sal <- max(data$salary)

# Get the person detail having max salary.

retval <- subset(data, salary == max(salary))

print(retval)

 

#Get the persons in IT department whose salary is greater than 600

info <- subset(data, salary > 600 & dept == “IT”)

print(info)

 

#Get the people who joined on or after 2014

retval <- subset(data, as.Date(start_date) > as.Date(“2014-01-01”))

print(retval)

 

Writing into a CSV File

R can create csv file form existing data frame. The write.csv() function is used to create the csv file. This file gets created in the working directory

 

# Create a data frame.

data <- read.csv(“input.csv”)

retval <- subset(data, as.Date(start_date) > as.Date(“2014-01-01”))

# Write filtered data into a new file.

write.csv(retval,”output.csv”)

newdata <- read.csv(“output.csv”)

print(newdata)

 

retval <- subset(data, as.Date(start_date) > as.Date(“2014-01-01”))

# Write filtered data into a new file.

write.csv(retval,”output.csv”, row.names=FALSE)

newdata <- read.csv(“output.csv”)

print(newdata)

 

 

# Verify the package is installed.

any(grepl(“xlsx”,installed.packages()))

# Load the library into R workspace.

library(“xlsx”)

 

Input as XLSX file

Open Microsoft excel. Copy and paste the following data in the work sheet named as sheet1.

Also copy and paste the following data to another worksheet and rename this worksheet to “city”.

 

Save the Excel file as “input.xlsx”. You should save it in the current working directory of the R workspace.

 

Reading the Excel File

The input.xlsx is read by using the read.xlsx() function as shown below. The result is stored as a data frame in the R environment.

# Read the first worksheet in the file input.xlsx.

data <- read.xlsx(“input.xlsx”, sheetIndex = 1)

print(data)

 

Note: These examples are for 32 bit Windows

 

First, load the RODBC package (you’ll also have to install it if you don’t have it already).

 

# Load RODBC package

 library(RODBC)

 

Next, connect to the Access database. This code creates an object called “channel” that tells R where the Access database is.

 

If you paste the path from windows be sure to change every backslash to a forward slash.

Do not include the file extension (.accdb or .mdb) on the end of the name of the database.

 

# Connect to Access db

 channel <- odbcConnectAccess(“C:/Documents/Name_Of_My_Access_Database”)

 

Finally, run a SQL query to return the data.

# Get data

data <- sqlQuery( channel , paste (“select *

 from Name_of_table_in_my_database”))

 

Return All Data from One Table

Example shows how to connect to database in R and queries the database DATABASE and returns all of the data (this is specified using the * in SQL) from the table DATATABLE. The table is preceded by the database schema SCHEMA and separated by a period. Each of the words in all caps needs within the query needs to be replaced so that the query applies to your database.

# Load RODBC package

library(RODBC)

 

# Create a connection to the database called “channel”

# If you are using operating system authentication (the computer already knows who you

# are because you are logged into it) you can leave out the uid=”USERNAME”, part.

channel <- odbcConnect(“DATABASE”, uid=”USERNAME”, pwd=”PASSWORD”, believeNRows=FALSE)

 

# Check that connection is working (Optional)

odbcGetInfo(channel)

 

# Find out what tables are available (Optional)

Tables <- sqlTables(channel, schema=”SCHEMA”)

 

# Query the database and put the results into the data frame “dataframe”

 dataframe <- sqlQuery(channel, “

 SELECT *

 FROM

 SCHEMA.DATATABLE”)

 

Return Only Specific Fields

Example shows how to connect to database in R and query the database DATABASE and pull only the specified fields from the table DATATABLE. Note that loading the RODBC package and creating a connection does not have to be repeated if they were done in the first example.

 

# Load RODBC package

library(RODBC)

 

# Create a connection to the database called “channel”

channel <- odbcConnect(“DATABASE”, uid=”USERNAME”, pwd=”PASSWORD”, believeNRows=FALSE)

 

# Find out what fields are available in the table (Optional)

# as.data.frame coerces the data into a data frame for easy viewing

Columns <- as.data.frame(colnames(sqlFetch(channel, “SCHEMA.DATATABLE”)))

 

# Query the database and put the results into the data frame “dataframe”

 dataframe <- sqlQuery(channel, “

 SELECT SCHOOL,

 STUDENT_NAME

 FROM

 SCHEMA.DATATABLE”)

 

Joining Two Tables and Returning Only Specific Fields and Records

 

# Load RODBC package

library(RODBC)

 

# Create a connection to the database called “channel”

channel <- odbcConnect(“DATABASE”, uid=”USERNAME”, pwd=”PASSWORD”, believeNRows=FALSE)

 

# Query the database and put the results into the data frame “dataframe”

 dataframe <- sqlQuery(channel, “

 SELECT

 DT.SCHOOL_YEAR,

 DTTWO.DISTRICT_NAME AS DISTRICT,

 DTTWO.SCHOOL_NAME AS SCHOOL,

 DT.GRADE_LEVEL AS GRADE,

 DT.ACTL_ATT_DAYS AS ACTUAL_DAYS,

 DT.POSS_ATT_DAYS AS POSSIBLE_DAYS

 FROM

 (SCHEMA.DATATABLE DT INNER JOIN SCHEMA.DATATABLE_TWO DTTWO

 ON (DT.SCHOOL_YEAR = DTTWO.SCHOOL_YEAR AND

 DT.SCHOOL_NUMBER = DTTWO.SCHOOL_CODE))

 WHERE

 DT.SCHOOL_YEAR = ‘2011-12’ AND

 DTTWO.SCHOOL_NAME = ‘Pine Tree Elementary School'”)

 

Using a Parameter from R to Return Only Specific Records

 

# Load RODBC package

library(RODBC)

 

# Create a connection to the database called “channel”

channel <- odbcConnect(“DATABASE”, uid=”USERNAME”, pwd=”PASSWORD”, believeNRows=FALSE)

 

# Parameter

YEARS <- c(“2012”, “2013”, “2014”)

 

# Query the database and put the results into the data frame “dataframe”

dataframe <- sqlQuery(channel, paste(“SELECT

 YEAR,

 SCHOOL_YEAR,

 DISTRICT_CODE,

 GRADE_LEVEL

 FROM SCHEMA.DATATABLE

 WHERE SCHEMA.DATATABLE.SCHOOL_YEAR IN (‘”, paste(YEARS, collapse = “‘, ‘”), “‘)

 “, sep=””))

 

 

 

 

The basis of any analysis is to understand, evaluate and interpret complex results. Thus, it is very imperative for an analyst to have a very comprehensive understanding of the data under scrutiny and relationship among various variables. The simplest yet very power powerful approach to gain a better understanding of the data is graphical techniques. For example, if you are looking at a excel spreadsheet for daily revenue data for a firm in a year, it is obviously not possible to understand if there is a particular trend or seasonality. But, by just plotting the data using a line chart, you can easily see seasonality, trend, and average behavior in one short. Let’s take an example of a scatterplot. A simple scatter plot not only shows the correlation between two variables but also shows linearity, non-linearity, homogeneity in the data. More importantly, data visualization also helps in presenting results to higher management group in a very simple manner. In this section we will explore various data visualization technique using R.

 

For most of the plots in the next sub sections, we have used a dataset consisting of following metrics for Year 2010-2017 for a website.

·        Date     

·        Visits     

·        Page views

·        Unique Visitors

·        Bounce rate

 

Basic Visualization Techniques

1.      Histogram: Histogram is used to plot continuous variable. It breaks the data into bins (or breaks) and shows frequency distribution of these bins. Histograms are appropriate to understand underlying distribution.

R Code:

h <- hist(Data$Visits, # Vector of data to be plotted

          main = “Total Visits of a Web Site Per Year”, # Title of the plot

          xlab = ” Visits”, # Title of the x – axis

          # xlim = c(15, 40),# limit on the x axis

          col = “palevioletred1”, # Color of the bar to be filled

          border = “brown”, # color of the border around the bin

          freq = T) # representation of frequencies

text (h$mids, h$counts, labels=h$counts, adj = c(0.5, -0.5)) # Give number on each bar

Figure:

In a histogram, the area of the bar indicates the frequency of occurrences for each value. From the figure, it found that the visits in the range of 1000000-1200000 occurring three times, the spread is more between 1000000-12000000. From the figure we can say the, there are no outliers in the data.  The Histogram shows the data follows an irregular clustered distribution.

2.      Bar/Line chart:

Line: Line Charts are chosen to examine a trend spread over a period. Additionally, line plot is used to compare relative changes in quantities across some variable (like time). Line charts are typically used to analyze trend in a data. It can also be used to understand outliers and to check normality assumptions.

R Code:

p <- plot_ly (Data, # Data frame

             x = ~Date, # x- axis data

             y = ~Visits) %>% # y- axis data

      add_lines() %>% # Add traces to a plotly visualization

      filter(Visits == min(Visits)) # filtering minimum among all values

      plotly_data (p) # obtaining data associated with a plotly graph

      add_markers (p) # Add traces to a plotly visualization

      layout (p, annotations = list(x = ~Year, y = ~Visits, text = “Valley”)) %>%

      layout (title = “Total Visits of a Web Site per year”, xaxis = list (title = “Date”,        showgrid = F), yaxis = list (title = “Visits”), showlegend = F)

 

 

Figure:

 

The above line chart shows the visitors for a website yearly from 2010 to 2016.  It gives fairly good idea that the visitors of the website have grown continuously up to 2015 over a particular time frame. In the year 2015, the total visitors for a website are high and decreased in the year 2016 around 15%. The visitor’s data of a website follows a left skewed normal distribution. I
Bar: Bar Plots are used to compare cumulative totals across several groups.

R Code:

plot_ly (Data, # Data frame

        type=”bar”, # Type of chart

        x = ~Date, # x- axis data

        y = ~Visits, # y- axis data

        visible = TRUE, # Visualbility of plot

        showlegend = TRUE) %>% # Legend status

  layout (title = “Total Visits of a Web Site Per Year”, # Title of the chart

         xaxis = list (title = “Year”, showgrid = TRUE, color = “red”), # list of x-axis properties

         yaxis = list (title = “Visits”, showgrid = TRUE, color = “green”)) # list of y-axis properties

Figure:

 

The bar chart indicates the number of visitors for a website between the years 2010-2016. It can be seen that the number of visitors is increasing linearly up to 2015; however, it decreases in the year 2016.

3.      Box plot: Box Plot used for visualizing the spread of the data and deriving inferences accordingly and also determine outliers.

R Code:

boxplot (Data [, 2:4], # Specifying data

        las = 1, #for Naming Vertical (las = 2) or Horizontal (las = 10)

        col = c (“sienna”,”green”), # Color of the box

        main = “Total Visits and Pageviews of a Web Site Per Year”) # Title of the plot

Figure:

The chart gives information about the spread of the data for Visitors, Page.views, and Unique visitors. The quartile range for visitors, page views, and unique visitors are around 300000, 1100000 and 150000respectively. That means there is tightly bound for unique visitors. For Visitors, unique visitors the median lies very close to the upper quartile.

4.      Scatter plot: Scatter plot used to visualize data easily and for simple data inspection.

R Code:

plot_ly (Data, # Data frame

        type =”scatter”, # Type of chart

        x = ~Date, # x- axis data

        y = ~Visits, # y- axis data

        visible = TRUE, # Visualbility of plot

        showlegend = TRUE) %>% # Legend status

  layout (title = “Total Visits of a Web Site Per Year”,

         xaxis = list (title = “Date”, showgrid = TRUE, color = “red”),

         yaxis = list (title = “Visits”, showgrid = TRUE, color = “green”))

Figure:

The graph above shows the relationship between visitors, page views, unique visitors and bounce rate during 2010 to 2016. It is observed that, higher number of visitors to a website leads to lower bounce rate. However visitors, page views and unique visitors interrelated to each other.

 

Advanced Visualization Techniques

 

1.      Heat map- Heat maps used to do empirical data analysis with two dimensions as the axis and the third dimension shown by intensity of color.

R Code:

heatmap (as.matrix (Data[, 18:21]), las=2)

 

R Code:

heatmap.2 (as.matrix (Data), # numeric matrix of the values

          dendrogram =”row”) # row dendrogram plotted and row reordering done

Figure:

 

The heat map gives the hierarchical clustering of visitors, unique visitors, page views and bounce rate. Initially, visitors and unique visitors together form a cluster because of their much similarity in their values. Then, bounce rate is clustered with the existing one, and finally, they clustered with page views.

2.      Mosaic plot- A mosaic plot can be used for plotting categorical data very effectively with the area of the data showing the relative proportions.

R Code:

mosaicplot (~ Visits + Page.views, # formula

           data = Data, # Data frame

           main = “Total Visits and Page views of a website per Year”, # Title of the plot

           color = TRUE, # Color shading

           dir = “h”, # Vector of split directions

           las = 2) # the style of axis labels

Figure:

In the mosaic plot, the data is split into different bars and shown the relationship between visitors, page views, unique visitors, and bounce rate. The mosaic plot is divided first into horizontal bars whose widths are proportional to the probabilities associated with the year. Then each bar is split vertically into bars that are proportional to the conditional probabilities of visitors, page views, unique visitors, and bounce rate. The colors represent the level of the residual/probability for that cell/combination of levels. 

3.      Map visualization-

a.     World map

R Code:

newmap <- getMap (resolution = “high”) # Accessing map stored in the package with high resolution

plot (newmap, # Map source

     xlim = c (10, 50), # co-ordinates in x – direction

     ylim = c (0, 81), # co-ordinates in y – direction

     asp = 1) # Aspect ratio

Figure:

b.     Plotting a location based on longitudes and latitudes

R Code:

m <- leaflet () %>%

               addTiles () %>% # Add default Open Street Map tiles

addMarkers (lng=87.3091, lat=22.3145, popup=”The Indian institute of Technology Kharagpur”) # longitude and latitude of IIT Kharagpur

m # Print the map

Figure:

 

4.      3D graphs- 

a.     Scatter plot

R Code:

scatterplot3d(x = Data$Date, # the x coordinates of points

              y = Data$Visits, # the y coordinates of points

              z = Data$Page.views, # the z coordinates of points

              residuals=TRUE, # Residuals

              bg=”black”, # Background color

              axis.scales=TRUE,

              grid=TRUE, # grid should be drawn on the plot or not

              ellipsoid=T,

              main = “Total Visits of a Web Site Per Year”, # Title of plot

              xlab = “Year”, # Title of x-axis

              ylab = “Page.Views”, # Title of y-axis

              zlab = “Visits”) # Title of z-axis

 

 

 

Figure:

b.     Surface plot

R Code:

plot_ly (Data, # Data frame

        x = ~Date, # The x coordinates of points

        y = ~Visits, # The x coordinates of points

        z = volcano, # The x coordinates of points

        type = “surface”) # Surface plot

layout (title = “Total Visits of a Web Site Per Year”, # Title of the plot

       xaxis = list (title = “Year”, showgrid = TRUE, color = “red”), # x-axis title and other properties

       yaxis = list (title = “Visits”, showgrid = TRUE, color = “green”)) # x-axis title and other properties

Figure:

c.      Spinning scatter plot

R Code:

scatter3d (as.numeric (Data$Year), # The x coordinates of points

          Data$Visits, # The y coordinates of points

          Data$Page.views) # The z coordinates of points

 

Figure:

 

 

5.      Correlogram – Correlogram used to visualize the data in correlation matrices.

R Code:

corrgram (Data, #Data frame

         order=NULL, # Variables are not re-ordered

         panel=panel.shade, # To plot content of each panel

         text.panel=panel.txt,

         main=”Correlogram between website Visits and Page views”) # Title of the plot

 

Figure:

From the figure, we observed that there is a positive correlation between visitors, page views, and unique visitors. However, Bounce rate has a negative correlation with other three values.

 

 

 

 

To install a package, in the console, type: install.packages(“RGoogleAnalytics”) and hit enter.

install.packages(“RGoogleAnalytics”)

 

magrittr

 

A Forward-Pipe Operator for R: Provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. The magrittr is a package developed to give two main benefits: 1) to decrease development time, and 2) to improve readability and maintainability of code.

 

Below codes are based on the mtcars dataset provided in R.

Compare the codes with and without %>%.

library(magrittr)

car_data <-

  mtcars %>%

  subset(hp > 100) %>%

  print

 

car_data <-

  mtcars

print (car_data)

 

%>% changes the semantics of the code and makes it more intuitive to both read and write.

rvest

rvest is a package that makes it easy to scrape (or harvest) data from html web pages, inspired by libraries like beautiful soup. It is designed to work with magrittr so that you can express complex operations as elegant pipelines composed of simple, easily understood pieces. Install it with:

 

Test the rvest library: code to get the rating of the Titanic movie from IMDB.com (http://www.imdb.com/title/tt0120338/). selectorgadget (refer online tutorial to learn about this plugin) to figure out which css selector matches the data we want. strong span is the CSS selector for to extract the rating.

library(rvest)

movie_link <- html(“http://www.imdb.com/title/tt0120338/”)

movie_link %>%

     html_node(“strong span”) %>%

     html_text() %>%

     as.numeric()

 

Rcurl

A wrapper for ‘libcurl’ <http://curl.haxx.se/libcurl/> Provides functions to allow one to compose general HTTP requests and provides convenient functions to fetch URIs, get & post forms, etc. and process the results returned by the Web server. This provides a great deal of control over the HTTP/FTP/… connection and the form of the request while providing a higher-level interface than is available just using R socket connections. Additionally, the underlying implementation is robust and extensive, supporting FTP/FTPS/TFTP (uploads and downloads), SSL/HTTPS, telnet, dict, ldap, and also supports cookies, redirects, authentication, etc.

 

library(RCurl)

# Amazon search: The Best American Short Stories of the Century

URL  <- “https://www.amazon.com/Best-American-Short-Stories-2016/dp/0544582896/ref=sr_1_1?ie=UTF8&qid=1493919877&sr=8-1&keywords=The+Best+American+Short+Stories”

html <- getURLContent(URL)

print(html)

 

gridExtra

Provides a number of user-level functions to work with “grid” graphics, notably to arrange multiple grid-based plots on a page, and draw tables.

 

Below is a sample example where we have mixed a few grobs and plots

 

library(gridExtra)

library(grid)

library(ggplot2)

library(lattice)

p <- qplot(1,1)

p2 <- xyplot(1~1)

r <- rectGrob(gp=gpar(fill=”grey90″))

t <- textGrob(“text”)

grid.arrange(t, p, p2, r, ncol=2)

 

Other R Libraries ReQuired in Data Visualization

 

These libraries are used in the examples shown under Data Visualization section

·        library (plotly): Plotly’s R graphing library makes interactive, publication-quality graphs online. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, and 3D (WebGL based) charts.

·        library (ggplot2): A system for ‘declaratively’ creating graphics, based on “The Grammar of Graphics”. You provide the data, tell ‘ggplot2’ how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.

·        library (RColorBrewer): Provides color schemes for maps (and other graphics) designed by Cynthia Brewer.

·        library (gplots): Various R programming tools for plotting data, including: – calculating and plotting locally smoothed summary function as (‘bandplot’, ‘wapply’), – and more. Refer the documentation.

·        library (vcd): Visualization techniques, data sets, summary and inference procedures aimed particularly at categorical data. Special emphasis is given to highly extensible grid graphics.

·        require (stats): This package contains functions for statistical calculations and random number generation.

·        library (maps): Package to display maps. Projection code and larger maps are in separate packages (‘mapproj’ and ‘mapdata’).

·        library (leaflet): Leaflet is one of the most popular open-source JavaScript libraries for interactive maps. This R package makes it easy to integrate and control Leaflet maps in R.

·        library (maptools): Tools for Reading and Handling Spatial Objects

·        library (rworldmap): Enables mapping of country level and gridded user datasets.

·        library (Rcmdr): A platform-independent basic-statistics GUI (graphical user interface) for R, based on the tcltk package.

·        library (rgl) – 3D Visualization Using OpenGL: Provides medium to high level functions for 3D interactive graphics, including functions modelled on base graphics (plot3d(), etc.) as well as functions for constructing representations of geometric objects (cube3d(), etc.). Output may be on screen using OpenGL, or to various standard 3D file formats including WebGL, PLY, OBJ, STL as well as 2D image formats, including PNG, Postscript, SVG, PGF.

·        library (scatterplot3d): Plots 3D Scatter Plot

·        library (corrgram): Calculates correlation of variables and displays the results graphically. Included panel functions can display points, shading, ellipses, and correlation values with confidence intervals.

·        library(markdown): ‘Markdown’ is a plain-text formatting syntax that can be converted to ‘XHTML’ or other formats.

·        library(shiny): Makes it incredibly easy to build interactive web applications with R. Automatic “reactive” binding between inputs and outputs and extensive prebuilt widgets make it possible to build beautiful, responsive, and powerful applications with minimal effort.

·        library (htmltools): Tools for HTML generation and output.

 

 

 

 

 

 

 

 

#R Program to Add Two Vectors

> x <- c(3,6,8)

[1] 3 6 8

> y <- c(2,9,0)

[1] 2 9 0

 

> x + y

[1]  5 15  8

 

> x + 1    # 1 is recycled to (1,1,1)

[1] 4 7 9

 

> x + c(1,4)    # (1,4) is recycled to (1,4,1) but warning issued

[1]  4 10  9

Warning message:

In x + c(1, 4) :

 longer object length is not a multiple of shorter object length

 

 

#Find Sum, Mean and Product of Vector in R Programming

> sum(2,7,5)

[1] 14

 

> x

[1]  2 NA  3  1  4

 

> sum(x)    # if any element is NA or NaN, result is NA or NaN

[1] NA

 

> sum(x, na.rm=TRUE)    # this way we can ignore NA and NaN values

[1] 10

 

> mean(x, na.rm=TRUE)

[1] 2.5

 

> prod(x, na.rm=TRUE)

[1] 24

 

 

#R Program to Take Input From User

my.name <- readline(prompt=”Enter name: “)

my.age <- readline(prompt=”Enter age: “)

 

# convert character into integer

my.age <- as.integer(my.age)

 

print(paste(“Hi,”, my.name, “next year you will be”, my.age+1, “years old.”))

 

 

#R Program to Generate Random Number from Standard Distributions

> runif(1)    # generates 1 random number

[1] 0.3984754

 

> runif(3)    # generates 3 random number

[1] 0.8090284 0.1797232 0.6803607

 

> runif(3, min=5, max=10)    # define the range between 5 and 10

[1] 7.099781 8.355461 5.173133

 

 

#R Program to Sample from a Population

> x

[1]  1  3  5  7  9 11 13 15 17

 

> # sample 2 items from x

> sample(x, 2)

[1] 13  9

 

 

#R Program to Find Minimum and Maximum

> x

[1]  5  8  3  9  2  7  4  6 10

 

> # find the minimum

> min(x)

[1] 2

 

> # find the maximum

> max(x)

[1] 10

 

> # find the range

> range(x)

[1]  2 10

 

 

#Find factors of a number

print(paste(“The factors of”,x,”are:”))

for(i in 1:x) {

  if((x %% i) == 0) {

    print(i)

  }

 

}

 

 

# Program to check if

# the input number is

# prime or not

 

# take input from the user

num = as.integer(readline(prompt=“Enter a number: “))

 

flag = 0

# prime numbers are greater than 1

if(num > 1) {

    # check for factors

    flag = 1

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

        if ((num %% i) == 0) {

            flag = 0

            break

        }

    }

}

if(num == 2)    flag = 1

if(flag == 1) {

    print(paste(num,“is a prime number”))

} else {

    print(paste(num,“is not a prime number”))

}

 

 

 

# Program to check if
# the input number is odd or even.
# A number is even if division
# by 2 give a remainder of 0.
# If remainder is 1, it is odd.
 
num = as.integer(readline(prompt="Enter a number: "))
if((num %% 2) == 0) {
    print(paste(num,"is Even"))
} else {
    print(paste(num,"is Odd"))
}

 

 

 

# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
 
num = as.double(readline(prompt="Enter a number: "))
if(num > 0) {
    print("Positive number")
} else {
    if(num == 0) {
        print("Zero")
    } else {
        print("Negative number")
    }
}

 

 

 

# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
 
# check is the number is negative, positive or zero
if(num < 0) {
    print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
    print("The factorial of 0 is 1")
} else {
    for(i in 1:num) {
        factorial = factorial * i
    }
    print(paste("The factorial of", num ,"is",factorial))
}

 

 

 

# Program to find the multiplication
# table (from 1 to 10)
# of a number input by the user
 
# take input from the user
num = as.integer(readline(prompt = "Enter a number: "))
 
# use for loop to iterate 10 times
for(i in 1:10) {
    print(paste(num,'x', i, '=', num*i))
}

 

 

# take input from the user
nterms = as.integer(readline(prompt="How many terms? "))
 
# first two terms
n1 = 0
n2 = 1
count = 2
 
# check if the number of terms is valid
if(nterms <= 0) {
    print("Plese enter a positive integer")
} else {
    if(nterms == 1) {
        print("Fibonacci sequence:")
        print(n1)
    } else {
        print("Fibonacci sequence:")
        print(n1)
        print(n2)
        while(count < nterms) {
            nth = n1 + n2
            print(nth)
            # update values
            n1 = n2
            n2 = nth
            count = count + 1
        }
    }
}

 

 

# Program make a simple calculator
# that can add, subtract, multiply
# and divide using functions
 
add <- function(x, y) {
    return(x + y)
}
 
subtract <- function(x, y) {
    return(x - y)
}
 
multiply <- function(x, y) {
    return(x * y)
}
 
divide <- function(x, y) {
    return(x / y)
}
 
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
 
choice = as.integer(readline(prompt="Enter choice[1/2/3/4]: "))
 
num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))
 
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(num1, num2), subtract(num1, num2), multiply(num1, num2), divide(num1, num2))
 
print(paste(num1, operator, num2, "=", result))
check <- function(x) {
   if (x > 0) {
       result <- "Positive"
   }
   else if (x < 0) {
       result <- "Negative"
   }
   else {
       result <- "Zero"
   }
   return(result)
}

 

 

# take input from the user
num = as.integer(readline(prompt = "Enter a number: "))
 
if(num < 0) {
    print("Enter a positive number")
} else {
    sum = 0
    # use while loop to iterate until zero
    while(num > 0) {
        sum = sum + num
        num = num - 1
    }
    print(paste("The sum is", sum))
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 https://learn.swapnil.pw/

Free Python Training by BRC Warriors (Aug-Sep 2022)

FREE PYTHON TRAINING BY BRC WARRIORS - AUG TO SEP 2022

DAY 0 – ORIENTATION  (AUGUST  12, 2022)

Download The Python Installer From Here (We Will Install Python 3.9.9):

https://www.python.org/downloads/release/python-399/

You can follow the instructions to install from here:
http://learn.swapnil.pw/python/pythoninstallation/

 

Download & Install IDE for Python Programming

Follow The Steps From Here: https://learn.swapnil.pw/python/pythonides/

DAY 1:  PYTHON  BASICS  (AUGUST 15, 2022)


print(3+4+5) #Python will evaluate
print('3+4+5') #Python will print as it is
print('Hello how are you?')
#this is a sample comment
#comments are put in hash
print("Good evening")
#there are two types of translators in programming
#language - COMPILER & INTERPRETER
#Constant v Variable
x = 5
x = 7
x = 9.5
# x is a variable which can change its value
# x is the variable name
# you can add number to variable name
x1 = 10 #valid variable name
#1x = 10 # it is wrong
# you can give _ to variable name
# _ is the only special character that can be
# given to variable name
first_num = 50
print(first_num)
print('first_num')
print("First number value is ",first_num)


#What are different data types in Python
#in python, number is of 2 types:
# int = integer: non decimal values: -inf to +inf
## 5,10,-99999,-78, 0, 56
# float = float: values with decimal
## e.g. -5.5, 0.0, 5.0 , 5.99999999

val1 = 5
val2 = 5.0
#print the data type using type()
print(type(val1))
print(type(val2))
#complex : square root of -1
# square root of -25 ?
# square root (25*-1) = 5i
# iota (i) in python is written as j
val3 = 5j
print(type(val3))
val4 = "Hello" #text data in python is
#called str (string)
print(type(val4))

# 5th data type is bool (boolean)
#boolean takes 2 values: True & False
val5 = True
print(type(val5))

#Basic data types: int, float, complex, bool,str
#WAP to calculate area and perimeter of a rectangle
length = 10
breadth = 12
area = length * breadth
print("Rectanle with sides",length,"and", breadth,
"has area of",area)
perimeter = 2 * (length + breadth)
print("Rectanle with sides",length,"and", breadth,
"has perimeter of",perimeter)

# 1. calculate and display area and perimeter of a
## square
# 2. calculate and display area and circumference of a
## circle

DAY 2:  PYTHON  OPERATORS(AUGUST 16, 2022)

 

#Program done on 16th

pi = 3.14
r = 5
area = pi*r**2 # ** for power
circumference = 2 * pi * r

print("A circle with radius",r,"has a circumference"
" of",circumference," and area of",area)

#Above I am moving only the content to different line
#with just one print function
#using format string -
print(f"A circle with radius {r} has a circumference "
f"of {circumference:0.1f} and area of {area}")

print(5**2)
print("Hi there \nHow are you?") #\n stands for newline
print("Hello",end=" ") # end will make \n visible
print("Good Evening")

val1 = 59
val2 = 25
print(val1 + val2) #addition
print(val1 - val2) #subtraction
print(val1 * val2) #multiplication
print(val1 / val2) #division
print(val1 ** val2) # power
print(val1 // val2) # integer division
print(val1 % val2) #modulo - remainder

## These were arithematic operations
#Comparison Operators
## input are integer values and output is a boolean value (T/F)
val1 = 12
val2 = 12

##comparison operators are: > < >= <= == !=
print(val1 > val2)
print(val1 >= val2)
print(val1 < val2)
print(val1 <= val2)
print(val1 == val2)

# a = 5 : assign value 5 to a // a will be 5
# a==5 : asking question, is a equal to 5 ? answer would T/F
print(val1 != val2) # not equal to- is val1 not equal to val2 ?

# Logical operators
## checks the relationship between 2 boolean values
## operators are: and or not
## and : if one value is False entire value will be false. Its true only when all the values
### are True
val1 = 15
val2 = 19
print(val1 !=val2 and val1 > val2) #True and False = FALSE

# OR - even if one nalue is True entire result will be True
print(val1 !=val2 or val1 > val2) # TRUE or FALSE - True
print(not True)
print(not False)
val1 = 30
print(val1 % 3)

#INPUT
a= input("Enter a value: ") #interactive input - you dont have to give fixed value
a = int(a) #int() str() float() complex() bool()
print("Input value is ",a)
print("Data type of input value is ", type(a))

DAY 3:  PYTHON  OPERATORS(AUGUST 17, 2022)

#
avg = 40
#you have passed
if avg >=40: #if the condition is true only print command will be executed
print("You have passed")
print("I am in if")
print("I am also in if")
else:
#pass #pass statement is used when you have nothing to write
print("Sorry you have not passed!")

print("I am outside if")

num = 25
#wap to check if num is divisible by 5 or not
#divisibility: if you divide the num by 5 and the remainder is zero
if num%5==0:
print(f"{num} is divisible by 5")
else:
print(f"{num} is not divisible by 5")

#wap to check if a number is positive or negative
num = -10
if num >0:
print(f"{num} is positive number")
elif num==0:
print("0 is neither a positive or negative number")
else:
print(f"{num} is negative number")

#WAP to print sum and average of 5 subjects and assign grade to the student based on:
## avg >=80: A, avg>= 70: B, avg>=60: C, avg >=50: D, avg>=40: E, avg <40- F

marks1 = input("Enter marks in subject 1: ")
marks1 = int(marks1)
marks2 = int(input("Enter marks in subject 2: "))
marks3 = int(input("Enter marks in subject 3: "))
marks4 = int(input("Enter marks in subject 4: "))
marks5 = int(input("Enter marks in subject 5: "))
total = marks1 + marks2 + marks3 + marks4 + marks5
avg = total /5
print(f"Student has scored a total of {total} marks and average of {avg}")
#if you score more than 90% - you win school medal, if >=95%
# we win President medal
if avg >=80:
print("You have got Grade A")
if avg >=90:
if avg>=95:
print("You win President Medal")
else:
print("You win School Medal")
elif avg >=70:
print("You have scored Grade B")
elif avg >= 60:
print("You have scored Grade C")
elif avg >= 50:
print("You have scored Grade D")
elif avg >= 40:
print("You have scored Grade E")
else:
print("Sorry, You have scored Grade F")

print("Thank you for running my program")

#wap to arrange given 3 numbers in increasing order
#enter numbers as: 45, 75, 35 => 35 45 75
a,b,c = 85, 75,95
l1,l2,l3 = a,a,a
if a < b: #when a is less than b
if a<c: # a is less than b and a is less than cv [
l1 = a
if b<c:
l2,l3=b,c
else: #c is less than b
l2,l3 = c,b
else: #a is less than b and greater than c [e.g. 3 5 2]
l1,l2,l3=c,a,b

else: #when b is less than a
if b <c:
l1 =b
if a <c:
l2,l3=a,c
else:
l2,l3 = c,a
else: # c <b
l1,l2,l3 = c,b,a

print(f"{l1} <= {l2} <={l3}")

DAY 4:  PYTHON  TRAINING – IF Condition & FOR Loop(AUGUST 18, 2022)

#yesterday we did arranging 3 words in increasing order
#retry the same program but this time we will do in decreasing order
num1,num2,num3 = 80,10,40
b1,b2,b3 = num1,num1,num1
#logic to find highest, second highest and lowest values
if num1 >= num2:
if num1 >= num3:
b1 = num1
if num2 > num3:
b2,b3 = num2, num3
else:
b2,b3 = num3,num2
else: #num1 > num2 and num3 >num1
b1 = num3
b2,b3 = num1, num2
else: #num2 > num1
if num2 > num3:
b1 = num2
if num3 > num1:
b2,b3=num3,num1
else:
b2, b3 = num1, num3
else:
b1 = num3
b2, b3 = num2, num1

#after the logic- b1 will have the higest value, b2: second highest and b3: lowest value
print(f"{b1} >= {b2} >= {b3}")

############ LOOPS #######
## FOR Loop - how many times you need to execute
print("Hello 5 times using FOR")
for counter in range(0,5,1):# generate values from 0 (including) upto 5 (excluding) with increment of 1
print("Hello : ",counter)
# range(3,8): when range has only 3 values then default increment is 1 (first val is starting and second is ending)
for i in range(3,8):
print("Hello: ",i) #generated values: 3, 4, 5, 6,7
print("3rd For loop: ")
for i in range(3,8,2):
print("Hello: ",i) #generated values: 3, 5, 7
print("For range with one value: ")
for i in range(3): #if one value then its ending value, default start = 0 ; increment =1
print("Hello: ",i) #generated values: 0,1,2
print("For loop is done)")
##############
# * * * * *
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()

## While Loop - checks for a condition, it will execute till the condition is true

Day 5:  19 AUGUST 2022

 

#for loop when we know how many times to run the loop
# while is based on condition
i = 1
while i <=5:
print(i)
i+=1
user = "y"
while user=="y":
print("How are you?")
user = input("Do you want to continue?")

while True:
print("Select Your Option:")
print("1. Perform Addition")
print("2. Perform Subtract")
print("3. Perform Multiplication")
print("4. Perform Division")
print("5. Quit")
ch=int(input("Enter your choice? "))
if ch==1:
n1 = int(input("Enter a number: "))
n2 = int(input("Enter second number: "))
sum= n1 + n2
print("Addition is ",sum)
elif ch==2:
pass
elif ch==3:
pass
elif ch==4:
pass
elif ch==5:
print("We are exiting... thank you!")
break #this command will throw us out of the loop
else:
print("Sorry, you have entered an invalid option! Try Again...")

# for - same as for loop in Python
# While - same as while in python
# do.. while (exit controlled loop)
#Generate Prime Numbers:
start = 5000
end = 10000
while start <= end:
#check if a number is prime or not
num = start
#how to check? - if a number is divisible by 1 and itself only
isPrime = True
for i in range(2,num//2+1):
if num%i ==0:
isPrime = False
break
if isPrime:
print(num,end=", ")

start+=1 #now increment the start value to next
print()

"""
*
* *
* *
* *
* *
* * * * * *
"""
n = 8
for i in range(n):
if i==0 or i==n-1:
for j in range(i+1):
print("*",end=" ")
else:
print("*",end= "")
for k in range(i):
print(" ",end=" ")
print("*",end="")
print()

#Fibonacci series
# 1,1,2,3,5,8,13.....
n_terms = int(input("How many terms you want? "))
if n_terms == 1:
print("1 ")
elif n_terms > 1:
print(" 1", end=", ")
prev1,prev2 = 0,1
for i in range(1,n_terms):
current = prev1 + prev2
print(current, end=", ")
prev1, prev2 = prev2, current
else:
print("Invalid input")

 

DAY 6 :  22 AUGUST 2022


# 22 aug 2022
#Practice on IF conditions as well as Loops
num = int(input(“Enter the number: “))
mul = int(input(“Enter the multiple: “))
print(f{num} X {mul} = {num*mul})
num = int(input(“Enter the number: “))
for i in range(10):
    print(f{num} X {i+1} = {num*(i+1)})
”’
1 * 1 = 1    2 * 1 = 2   3 * 1 = 3 …   10 * 1
1 * 2 = 2
..
1 * 10 = 10
”’
for j in range(10):
    for i in range(10):
        print(f{i+1:<2} X {j+1:<2} = {(j+1)*(i+1): <3}, end=”  “)
    print()
#wap to give options to perform sum, difference, multiplication or division
#continue till user wants
while True:
    print(“Please select from below options: “)
    print(“1. Addition \n2. Subtraction \n3. Multiplication \n4. Division \n5. Quit”)
    ch=int(input(“Enter your option: “))
    if ch==1:
        num1 = int(input(“Enter first number: “))
        num2 = int(input(“Enter second number: “))
        print(f“Addition of {num1} and {num2} is {num1+num2})
    elif ch==2:
        num1 = int(input(“Enter first number: “))
        num2 = int(input(“Enter second number: “))
        print(f“Difference of {num1} and {num2} is {num1-num2})
    elif ch==3:
        num1 = int(input(“Enter first number: “))
        num2 = int(input(“Enter second number: “))
        print(f“Multiplication of {num1} and {num2} is {num1*num2})
    elif ch==4:
        num1 = int(input(“Enter first number: “))
        num2 = int(input(“Enter second number: “))
        print(f“Division of {num1} by {num2} is {num1/num2})
    elif ch==5:
        break
    else:
        print(“Invalid option! Please try again..”)
        continue
#wap to give options to perform sum, difference, multiplication or division
#continue till user wants
while True:
    print(“Please select from below options: “)
    print(“1. Addition \n2. Subtraction \n3. Multiplication \n4. Division \n5. Quit”)
    ch=int(input(“Enter your option: “))
    if ch==1:
        num1 = int(input(“Enter first number: “))
        num2 = int(input(“Enter second number: “))
        print(f“Addition of {num1} and {num2} is {num1+num2})
    elif ch==2:
        num1 = int(input(“Enter first number: “))
        num2 = int(input(“Enter second number: “))
        print(f“Difference of {num1} and {num2} is {num1-num2})
    elif ch==3:
        num1 = int(input(“Enter first number: “))
        num2 = int(input(“Enter second number: “))
        print(f“Multiplication of {num1} and {num2} is {num1*num2})
    elif ch==4:
        num1 = int(input(“Enter first number: “))
        num2 = int(input(“Enter second number: “))
        print(f“Division of {num1} by {num2} is {num1/num2})
    elif ch==5:
        break
    else:
        print(“Invalid option! Please try again..”)
        continue

#Lets develop a guessing game
#Let computer think of a number and let computer guess that number
import random  # it has functions that deal with random numbers
comp_num = random.randint(1,100)
counter = 0
low,high = 1,100
while True:
    guess_num = random.randint(low,high)
    counter+=1
    if guess_num ==comp_num:
        print(f“Congratulations! You have guessed the number correctly in {counter} attempts!”)
        break
    else:
        print(“Sorry! You did not get it correct”)
        if guess_num > comp_num:
            print(“HINT: Your number is higher than the actual number…”)
            high=guess_num-1
        else:
           print(“HINT: Your number is lower than the actual number…”)
            low = guess_num+1
# one line if condition
num = 10
if num>0:
    print(“Positive”)
else:
    print(“not Positive”)
#where you have condition which does one line of instruction, we can modify this as:
# we can re-write line no. 3 to 6 as:
output = “Positive” if num>0 else  “not Positive”
print(output)

#one line loop example:
output = [i for i in range(1,11)]   
#[] is creating a list we will discuss later this week
print(output)

https://play.google.com/store/apps/details?id=com.hachiweb.story_mantra&hl=en_IN&gl=US

 

Download Python book and many other technical books and videos for free from Story Mantra Android Mobile App. Login and then click on Technical category to access the material

https://play.google.com/store/apps/details?id=com.hachiweb.story_mantra&hl=en_IN&gl=US

DAY 7: AUGUST 23, 2022



#String
## its a text that Python uses
greet1 = 'hello'
greet2 = "evening"
print(type(greet2))
print(greet1 + " "+ greet2)
print(greet1 *5)
print("Hello " + str(8))
print(str(7) + str(8))

'''
comment
'''

greet3 = '''How are you today?
I am fine'''
print(greet3)
greet4 = """I am fine
I am going home
Where are you going?"""
print(greet4)

greet1 ="Good Evening"
for i in greet1:
print(i,end="")
print()
print(f"Number of characters in {greet1} are {len(greet1)} ")

for i in range(len(greet1)):
print(i, end=" ")
print()

#slicing / indexing in String
#concept is same for future discussions like List, Tuple, Dictionary,...
greet1 = "Hello Bye"
#counting starts from ZERO
print(greet1[0]) #position 1 = Index 0
print(greet1[0]+greet1[4]+greet1[7])
#counting or indexing starts from zero from left to right
# len(greet1) = 9
print(len(greet1))
#first memeber of the string: greet1[0]
size = len(greet1)
#last member of the string: greet1[size-1]
print(greet1[size-1]) #last character
'''
H E L L O
0 1 2 3 4 => Left to Right is +ve indexing starting from zero
-5 -4 -3 -2 -1 => Right to Left is -ve indexing, starts from -1

'''

greet1 = "Hello Bye"
#print last character, 3rd character and 5th last character
print(greet1[-1] + greet1[-3]+greet1[-5])

#indexing sequence of characters
greet1 = "Hello Bye"
print(greet1[0:3]) #first 3 characters
print(greet1[2:5]) #llo
print(greet1[-7:-4]) #llo using -ve indexing
size = len(greet1)
print(greet1[-size:-size+4]) #first 3 characters
print(greet1[:-size+4]) #if left side is blanks, then its starting from 0
print(greet1[6:9]) #last 3 characters using +ve indexing
print(greet1[-3:]) #last 3 characters using -ve indexing
print(greet1[:]) #print from first to last

# Inbuilt Methods in String
#functions part of a class is called methods
#here class name is String
greet1 = "Hellobe Hello7Hello*y"
print(greet1.isalpha()) #True/False
print(greet1.isalnum())
print(greet1.isupper()) #check if its upper case
print(greet1.islower()) #check if its lower case
print(greet1.istitle()) #title case means - first character of every word
# words can be separated by any non-alphabet

# Str are called immutable (u cant edit)
str1 = "hello"
#str1[0] = "H" #error because we cant edit the value
str1 = "H"+str1[1:] #this is fine because we are creating new string variable
print(str1)

DAY 8:  24 AUGUST 2022 –  String Methods – II and List – I

# String
# isupper, islower,istitle

num1 = input(“Enter length of the rectangle: “)
num2 = input(“Enter breadth of the rectangle: “)
if num1.isdigit() and num2.isdigit():
    num1 = int(num1) 
    num2 = int(num2)
    area = num1 * num2
    perimeter = 2 * (num1 + num2)
    print(f“Area and Perimeter are {area} and {perimeter} respectively”)
else:
    print(f“One or more input values are invalid!”)

# String methods
#lower(), upper(), title()
greet1 = “Hello EveryONE”
print(“Title Case: “,greet1.title())
print(“Upper Case: “,greet1.upper())
print(“Lower Case: “,greet1.lower())

#WAP to input nationality and age to decide whether that person can vote or not
age = int(input(“Enter your age: “)) 
nationality = input(“Enter Your Nationality: “)
if age >=18 and nationality.lower() ==“india”:
    print(“You are eligible to vote in India”)
else:
    print(“Sorry, you do not meet the criteria to vote in India”)

statement1 = “Hello How Are You Doing Today?”
words1 = statement1.split()  # output is a List, which we will discuss later
print(words1)
text1 = “Hello;How;are;you;doing;today;?”
words2 = text1.split(“;”#by default it will split on blank space but we can tell how to split
print(words2)
txt2 = ” “.join([‘Hello’‘How’‘are’‘you’‘doing’‘today’‘?’])
print(txt2)

#replace
txt3 = “What are you doing today?”
txt3 = txt3.lower().replace(“what”,“How”)
print(txt3)
#find
txt4 = “How are you doing today whats your name”
#WAP to find is the text has “doing”
result = txt4.find(“doing”)
if result ==-1:
    print(“Sorry, the text doesnt contain doing in it”)
else:
    print(“Text has doing at position “,result)

text= “HELLO EVERYONE”
reverse_txt  = “”
for i in text:
    reverse_txt= i + reverse_txt
print(reverse_txt)


# Working with List datatype
#declare a list
list1 = [5True,“Hello”, [2,4,6]]
print(“Size of the list: “,len(list1))
list2= [5.5False]
print(list1 + list2)
print(list2 * 4)
print(“Hello” in list1)

print(“Values in the list using For Loop:”)
for i in list1:
    print(i)

print(“#Indexing / Slicing same as string”)
print(list1[-2:])
first_mem = list1[0]
print(type(first_mem))
last_mem = list1[-1]
print(type(last_mem))

#WAP to input marks of 5 subjects and print sum and averag
# First type that we have done:
sub1 = int(input(“Enter marks in sub1: “))
sub2 = int(input(“Enter marks in sub2: “))
sub3 = int(input(“Enter marks in sub3: “))
sub4 = int(input(“Enter marks in sub4: “))
sub5 = int(input(“Enter marks in sub5: “))
total = sub1 + sub2 + sub3 + sub4 + sub5 
##problem here is that we have to write 5 different input()
#to avoid repeating same thing we used loops
#Type 2: use loop
total = 0
for i in range(5):
    m = int(input(“Enter the marks in subject “+str(i+1)+“: “))
    total+=m
print(“Total after step 2: “,total)

#method 2 avoid us from writing samething again and again – used loop instead
#problem here is: we lost the individual marks

total = 0
marks = []
for i in range(10):
    m = int(input(“Enter the marks in subject “+str(i+1)+“: “))
    marks.append(m)
    total+=m
print(f“Marks obtained in each subject is {marks} and the total marks is {total})

st1 = [65789054699087697576]
st2 = [65789094699087697576]
st3 = [65789054695087697576]
st4 = [65789054699287697576]
highest_marks = []

for i in range(10):
    if st1[i] > st2[i] and st1[i] > st3[i] and st1[i] > st4[i]:
        highest_marks.append(st1[i])
    elif st2[i] > st1[i] and st2[i] > st3[i] and st2[i] > st4[i]:
        highest_marks.append(st2[i])
    elif st3[i] > st2[i] and st3[i] > st1[i] and st3[i] > st4[i]:
        highest_marks.append(st3[i])
    #if st4[i] > st2[i] and st4[i] > st3[i] and st4[i] > st1[i]:
    else:
        highest_marks.append(st4[i])
print(“highest marks in each subject is: “,highest_marks)

#insert()
st1.insert(0,100)
print(st1)
#append will add at the back
#insert takes the position number – you can add at any position

 

DAY 9 – 25 AUGUST 2022:  LIST – 2 and TUPLE INTRO


list1 = [3,5.4,False,“Hello”,[2,3,4]]
#append – by default adds at the end
#insert – takes position also to add

list1[1] = 100
print(list1)

#List is Mutable ; String is Immutable
list2 = list1  #list2 will have same values as list1
list3 = list1.copy()   #list3 will be duplicate copy of list1
#when we say equal to : list2 is not created different set of values
## they all point to same data in the memory
## one data and two names are created
# when we do copy – it is like photocopy, duplicate copy is
## created and they are separate- list1 and list3 have no connection after this
print(“Printing after 1 Iteration”)
print(list1,“\n”,list2,“\n”,list3)
#as expected all 3 have same list of values
list1.append(999)
list2.append(“mango”)
list3.append(“india”)
print(“Printing after 2 Iteration”)
print(list1,“\n”,list2,“\n”,list3)
# there are 2 methods to remove as well:  remove() – value and pop() – position
list1.pop(0)
list3.remove(False)
if False in list3:
    list3.remove(False)
else:
    print(“False is no longer in the list”)
print(“List 2: “,list2)
print(“List 3: “,list3)
pos = 100
if len(list1)>pos:
    list1.pop(pos)
else:
    print(f{pos} index is not in the list”)

list1 = [5,10,100,70,90,90,90,40]
list1.reverse()  #reverse() method doesnt return anything (none)
print(list1)
list1.sort()  #sort is done in the increasing order
print(“List after sorted: “,list1)

# how to sort in decreasing order?
list1.sort(reverse = True)
#list1.reverse()
print(” “,list1)
count_of_90 = list1.count(90)
print(f“There are {count_of_90} values with 90″)
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
list3 = list1 + list2
print(list3)
#extend()
list1.extend(list2)
print(list1)

#WAP where we input date, month and year in numbers
# and display as – date(st/nd/rd/th) Month_in_text Year
# eg. date = 25  month = 8 year = 2022
# output would be 25th August 2022
month_txt = [‘January’‘February’,‘March’,‘April’,‘May’,
             ‘June’‘July’,‘August’,‘Setember’,‘October’,
             ‘November’‘December’]
date_th = [‘st’,‘nd’,‘rd’] + 17*[‘th’] + [‘st’,‘nd’,‘rd’] +7*[‘th’] +[‘st’]
date = int(input(“Enter the Date: “))
month = int(input(“Enter the Month: “))
year = input(“Enter the Year: “)
result = str(date)+date_th[date-1]+” “ + month_txt[month-1]+” “ + year
print(result)

#Assignment: input marks of 5 subjects for 5 students and display
#the highest marks in each subject and also for overall and name the student

#Tuple
#Tuple is immutable version of List
#It is also linear collection, can store multiple values
#but we cant edit (just like String)
#Lists are mutable & Tuple and String are Immutable
t1 = ()
print(len(t1))
print(type(t1))
t1 = list(t1)
print(type(t1))
t1.append(5)
t1 = tuple(t1)
print(t1)

# t1 = (5) – this is invalid
t1 = (5,) #- this is valid- this is true only if tuple has ONLY 1 member
t1 = (5,10,15)

#In reading operations Tuple is preferred over List as it is much faster
# So lists are converted into Tuple for reading op like FOR/WHILE
#Lists are preferred for Writing Operations because Tuple is Immutable

Click here to watch data 9 video

DAY 10: AUGUST 26, 2022

#26 AUG 2022
#Tuple
t1 = (“Sachin”,“Kohli”,“Rohit”)
name1, name2, name3 = t1  #unpacking
#since the size of t1 is 3, we should use exactly 3 variables to unpack
print(t1)
print(name1, name2,name3)
for i in t1:
    print(i)

t1 = list(t1)
print(type(t1))
t1.append(“Rishabh”)
t1 = tuple(t1)
print(t1.index(“Kohli”))

#Dictionary
student_marks = {‘2018CSE046’: [86,39,98,76,69], True:“Evening”,3:3}
print(student_marks[‘2018CSE046’])
print(student_marks[True]) 
#List and Dictionary are mutable / Str and Tuple – they immutable
student_marks[True] = “Good Evening”
print(student_marks[True])

#WAP to input rollnumber and the marks in 3 subjects for 3 students
all_students = {}
student = {102: [67,87,73]}
all_students.update(student) #this is how you add a dict to another
print(all_students)
#solution to the above question
all_students = {}
for i in range(3):  #students
    print(“Input details for Student”+str(i+1)+“: “)
    roll = int(input(“Enter Roll No: “))
    marks_list = []  # to read next set of marks
    for j in range(3):
        mark=input(“Enter the marks in subject”+str(j+1)+“: “)
        marks_list.append(mark)
    temp_dict = {roll: marks_list}
    all_students.update(temp_dict)

print(“All the student records are: “)
print(all_students)

all_students={101: [’76’’78’’83’], 90: [’54’’67’’90’], 95: [’95’’55’’55’]}
print(all_students.keys())
print(all_students.values())

for i,j in all_students.items():
    print(f“Key is {i} and value is {j}

#remove particular key – pop()
#student with roll no 95 to be removed
all_students.pop(95)
print(all_students)

#difference between = and extend
# extend is used to add 2 dictionaries
# = is to assign (l3 = l1 + l2 => this doesnt exist in Dictionary)

#difference between = and copy
dict2 = all_students
dict3 = all_students.copy()

#new member to dict1:
all_students.update({100: [56,68,75]})
print(“dict2: “,dict2)
#when you try add duplicate key, old value is replaced with new value
#So your dictionary cant have duplicate values
print(“dict3: “,dict3)
# = is doing deep copy (same as List) – it will point to same memory location
# copy is called shallow copy (same as List) – it will create a duplicate copy

womens_team= {“Mithali”232“Anjum”130“Jhulan”202}
mens_team = {“Kohli”190“Rohit”185“Rishabh”50}
indian =[]
for i in womens_team.values():
    indian.append(i)
for i in mens_team.values():
    indian.append(i)
print(indian)

womens_team= {“Mithali”“India”“Lisa”:“Aus”“Anjum”“India”,“Karen”:“Aus”“Jhulan”“India”}
mens_team = {“Kohli”“India”“Joe Root”:“Eng”“Rohit”“India”,“Babar”:“Pak”“Rishabh”“India”}
indian =[]
for i,j in womens_team.items():
    if j.lower() == “india”:
        indian.append(i)
for i,j in mens_team.items():
    if j.lower() == “india”:
        indian.append(i)
print(“Indian players that appears in the lists are: \n”,indian)

#SET – which is same as Set theory in Mathematics
#sets are also declared using {} just like a dictionary
#how to identify set from dict ? dict has key and value both
#but set has only values
#set  doesnt have index and also cant accept duplicate values
set1 = {1,2,2,3,3,3,4,4,4,5}
print(f“Set1 is of type {type(set1)} and values {set1})
# Tuples, List and Sets are convertible into each other forms
set1 = list(set1)
set1.append(7)
set1=set(set1)
print(set1)

list_even = []
for i in tuple(set1):
    if i%2==0:
        list_even.append(i)
print(f“Total even numbers are: {len(list_even)}, and the values are {list_even})

list1 = [44,55,66,44,55,77,88,88,99]
#Wap to remove duplicate values:
list1 = list(set(list1))
print(list1)

set1 = set([669944775588])
set2 = {77,55,88,33,22}
print(set1, “\n”,set2)

# union, intersection, subset, difference, superset

 

Day 11: August 27, 2022

#Day 11: 27 AUGUST 2022
set1 = {1,3,5,7,9,11}
set2 = {7,9,11,13,15}
print(set1 & set2) #intersection
#common elemets between the sets
print(set1.intersection(set2))

## union: find all the values
print(set1 | set2)
print(set1.union(set2))

#difference
print(set1 -set2)
print(set2.difference(set1))
#symetric difference
print(set1 ^ set2)
print(set2.symmetric_difference(set1))
print(“Working with Update methods”)
#same as union of (set1 – set2 and set2 – set1)
#All the above operations are returning us 3rd set
## update: set1 = set1 | set2
## intersection_update: set1 = set1 & set2
## difference_update: set1 = set1 – set2
##summetric_difference_update: set1 = set1 ^ set2
set1.update(set2)
set1.intersection_update(set2)
set1.difference_update(set2)
set1.symmetric_difference_update(set2)
print(set1)
set1 = {79111315}
print(set1.pop()) #any value is removed
#above method returns the value removed
print(set1)
print(set1.remove(15)) #doesnt return
print(set1) #this will not have 15
set2= {7,11,100,200,300}
print(set1.isdisjoint(set2))
set1 = {1,3,5,7,9#superset of set2- it has all the elemets of set2
set2 = {3,5,7}  #subset of set1- all the 
#elements of set2 belongs in set1
print(set1.issuperset(set2))
print(set2.issubset(set1))

#functions
#we are defining a function here
def myfunc1():
    print(“Hello”)
    print(“How are you?”)
    print(“Where are you?”)

#we are not putting returnin in above function
def myfunc2():
    print(“Hello 2”)
    print(“How are you? 2”)
    print(“Where are you? 2”)
    return 100
#above function is returning 100

#now I am calling user defined function:
myfunc1()
print(“Ok, now lets go for second time:”)
myfunc1()
print(myfunc1()) #since myfunc1 doesnt return, it prints None
print(myfunc2()) #since myfunc2 has 100 as return

return_val_myfunc2 = myfunc2()
return_val_myfunc1 = myfunc1()
print(“return_val_myfunc2: “, return_val_myfunc2)
print(“return_val_myfunc1: “, return_val_myfunc1)

#wap to input 3 numbers and print its sum
def myaddition():
    n1 = int(input(“Enter a number: “))
    n2 = int(input(“Enter a number: “))
    n3 = int(input(“Enter a number: “))
    sum = n1 + n2 + n3
    print(“Sum is “,sum)

def myaddition_return():
    n1 = int(input(“Enter a number: “))
    n2 = int(input(“Enter a number: “))
    n3 = int(input(“Enter a number: “))
    sum = n1 + n2 + n3
    return sum 


myaddition()

result = myaddition_return()
print(“Addition of 3 numbers is “,result)
print(“We have added 3 numbers and the result is “,result)

Day 12: August 29, 2022

#AUG 29 2022
#Functions
#You can put your questions in the website as well if you want to reach out to me

###########################
def greetings(): #function definition
print("Hello")
print("How are you?")
print("Where are you now?")

print("Calling the function now")
greetings() # calling the function
#execution of above function is not complete till greetings() is done
print("Calling the function again")
greetings()

def addition_type1():
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
sum = n1 + n2
print("Sum of given two numbers is ",sum)

addition_type1()
# TYPE 1: this is an example of function that doesnt take any input parameter
# and doesnt return any value
def addition_type2():
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
sum = n1 + n2
#print("Sum of given two numbers is ",sum)
return sum

print(addition_type2()) #print directly
result = addition_type2()
print("Type 2 function that returns value as ",result)

#This is example of Type 2 function where we dont provide any
#input but the function returns of output

def addition_type3(n1, n2): #we are providing input parameters
print("Values of n1 and n2 are: ",n1,n2)
sum = n1 + n2
#print("Sum of given two numbers is ",sum)
return sum # return values

print(addition_type3(56,21)) #print directly
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = addition_type3(a,b)
print("Type 3 function that takes input and also returns value ",result)

def addition_type4(n1, n2): #we are providing input parameters
print("Values of n1 and n2 are: ",n1,n2)
sum = n1 + n2
print("Sum of given two numbers is ",sum)


print(addition_type4(56,21)) #print directly
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = addition_type4(a,b)
print("Type 3 function that takes input and also returns value ",result)

#function that we declare are called User Defined Functions
#functions that come preinstalled - print() input() int() - inbuilt functions
def input_val():
n1, n2 = 40, 30
return n1,n2

def calculation(n1,n2):
add = n1 + n2
sub = n1 - n2
mul = n1 * n2
div = n1 / n2
return add, sub,mul,div

def display(r1,r2,r3,r4):
print("Sum of two numbers is ", r1)
print("Difference of two numbers is ", r2)
print("Multiplication of two numbers is ", r3)
print("Ratio of two numbers is ", r4)

a,b = input_val()
result1, result2, result3, result4 = calculation(a,b)
display(result1, result2, result3, result4)

# global v local variable

x = 50 #global variable
def display_info1():
x = 20 #local to display_info1
print("X is ",x)

def display_info2():
print("X is ",x)

def display_info3():
global x
print("X is ",x)
x = 30
print("X is ",x)


display_info1() #local will always take precedence over global
display_info2() #when there is no local, global is called
display_info3()

#WAP to input value and check if the number is odd or even
def check_odd(n):
"""This function takes a number and checks if the number is odd
It returns True if the number is odd otherwise False
"""
if n%2 !=0:
return True
else:
return False

print("Enter the series of numbers to check if odd or even, enter non number to end!")
while True:
inp = input("Enter a number: ")
if inp.isdigit():
inp = int(inp)
check = check_odd(inp)
if check:
print("Its an Odd number")
else:
print("Its an Even number")
else:
break


# Write a function to generate next fibonacci number
def generate_fibonacci(n1, n2):
return n1 + n2


n1 = 0
n2 = 1
print("Fibonacci numbers are: \n 1")
while True:
result = generate_fibonacci(n1, n2)
print(result, end=" ===> ")
ch = input("Hit Enter to continue anyother key to stop!")
n1, n2 = n2, result
if len(ch) != 0:
break

#Doc String: Doc string is always the first """ line (after function declaration)
#this adds to the documentation of the function

help(help)

help(input)
help(print)

Day 13: August 30, 2022

#Example of Function that takes REQUIRED POSITIONAL arguments
def add_numbers(n1,n2):
print("Values of n1 and n2 are: ",n1,n2)

#Example of function with default values
# in below example n1 and n2 are required
# whereas n3, n4,n5 will take default values if not provided
def add_numbers2(n1,n2,n3=3,n4=4,n5=5):
print("Values of n1, n2,n3,n4 and n5 are: ", n1, n2,n3,n4,n5)

def add_numbers3(n1,n2):
print("Values of n1 and n2 are: ",n1,n2)

add_numbers(5,49)
add_numbers2(5,49)
add_numbers2(10,20,30)
add_numbers2(5,15,25,35,45)
add_numbers3(n2=25,n1=36) #example of non-positional
#Required because function definition has 2 parameters so we must
#provide exactly 2 values
#Positional because the order in which we must give will be
#matched from left to right

def create_report(n1=-1,n2=-1,title=""):
if len(title) !=0:
print(" PERFORMING REPORT ")
print("-----------------------------------")
print(" TITLE: ",title)
if n1>0:
print("-----------------------------------")
print(" SCORE : ",n1)
if n2>0:
print("-----------------------------------")
print(" MAX SCORE : ",n2)

create_report(title="Quality Score for Today",n2=5,n1=3.8)

#Variable length arguments
#values are not provided, then it shouldnt be created

def players_info(*names, **information):
# * will make this variable a TUPLE
# ** will make this a dictionary
print("Value and Type of names: ",names, type(names))
print("Value and Type of information: ", information, type(information))
if "home" in information.keys():
print("Home of the players is ",information["home"])
if "sports" in information.keys():
print("Sports they play is ",information["sports"])

players_info("Sachin","Kohli","Kapil","Laxman",sports = "Cricket", country="India",type="BAT")

def isPrime(num):
#flag = True
for i in range(2,num):
if num %i ==0:
return False
return True
#WAF to check if a number is a prime or not
#continue the function to generate series of prime numbers
start_num = int(input("From which number you want to generate Prime: "))
end_num = int(input("Upto which number you want to generate Prime: "))
for j in range(start_num, end_num+1):
if isPrime(j):
print(j, end=", ")

#Recursive Functions

# function that calls itself

def my_factorial(n):
if n==1:
return 1
return n *my_factorial(n-1)

result = my_factorial(9)
print("Result : ",result)

# 5! = 5 *4!
#4! = 4 * 3!
# 3! = 3 * 2!
# 2! = 2 * 1!
# 1! = 1 * 0!
# 0! = 1 #ending line for function

August 31, 2022:  HOLIDAY

Day 14: September 1, 2022

#1 Sep 2022
#Decorators and some inbuilt functions
def display_details(name,about):
print("Name: ",name)
print("About: ",about)


#example 2
def myfunction1():
def my_inside_function():
print("First line from inner function!")
print("I am also getting printed in inside function")

print("Name is getting printed in myfunction1: ",name)
print("Nextline I will call inside function")
my_inside_function()
print("Last line thank you")


#example 3:
def outer_function1():
print("First line from inneouter_function1 function!")
print("I am also getting printed in outer_function1 function")

def outer_function2(param1):
print("First line from inneouter_function1 function!")
print("I am also getting printed in outer_function1 function")
param1()


#example 4:
def my_function1(x):
def my_fun2(y):
return x+y
return my_fun2

if __name__ == "__main__":
# calling the function
name = "Sachin Laxman"
about = "I am an international cricketer and love to play football"
display_details(name, about)
print_details = display_details # creating another name for the function
print_details(name, about)

myfunction1()

outer_function2(outer_function1)
result = my_function1(10)
print(result(5))


##############
##############
# Below code in different file
#######################
import datetime
print("Current time: ", datetime.datetime.now()) #current system time
print("Current year: ", datetime.datetime.now().year)
print("Current ", datetime.datetime.now().month)
print("Current ", datetime.datetime.now().day)
print("Current ", datetime.datetime.now().hour)
print("Current ", datetime.datetime.now().minute)
#print(datetime.datetime.now().strftime('%Y-%m%-%d'))

import random
print(random.randint(10,20))
print(random.random())

var = "hello"

DAY 15: September 2, 2022

# CLASS & OBJECTS
class Student:
def print_info(self,name): #self indicates this method is object level
print("I am being called from an object")
self.name = name
def display_name(self):
print("Name is: ",self.name)

s1 = Student()
s1.print_info("Laxman")
s2 = Student()
s2.print_info("Rahul Dravid")
s3 = Student()
s3.print_info("Zaheer Khan")
s4 = Student()
s4.print_info("Ashish Nehra")
s2.display_name()

class Calculations:
def get_value(self,a,b):
self.num1 = a
self.num2 = b
def __init__(self,a,b):
self.num1 = a
self.num2 = b

def add_values(self):
print("Sum of two numbers are: ",self.num1 + self.num2)

def multiple_values(self):
print("Multiplication of two numbers is: ",self.num1 * self.num2)

c1 = Calculations(21,34)
#c1.get_value(21,34)
c1.multiple_values()

c2 = Calculations(6,8)
c2.add_values()

class Students:
def __init__(self,name,rollno,ph,email):
self.name = name
self.rollno = rollno
self.phone = ph
self.email = email
self.avg = 0 #default values for now not available
self.grade = "Z" #default values

def calc_avg(self):
sum=0
for i in range(3):
m = int(input("Enter marks: "))
sum+=m #sum += m
self.avg = sum/3

def calc_grade(self):
if self.avg >80:
self.grade = "A"
elif self.avg >70:
self.grade = "B"
elif self.avg >60:
self.grade = "C"
elif self.avg >50:
self.grade = "D"
else:
self.grade = "E"

s1 = Students("Sachin Tendulkar",103,989898989898989898,"sachin@tendulkar.com")
s2 = Students("Suresh Raina",109,11118989898,"sraina@tendulkar.com")

s1.calc_avg()
s1.calc_grade()
print("Grade of ",s1.name," is ",s1.grade)

 

DAY 16:  3 SEPTEMBER 2022

class School: #Base class
def __init__(self):
print("Sample Init function")
def display_school_info(self):
print("Parent class")

class Students(School): #Derived class
number_of_students = 0
def __init__(self,name,rollno,ph,email):
self.name = name
self.rollno = rollno
self.phone = ph
self.email = email
self.avg = 0 #default values for now not available
self.grade = "Z" #default values
Students.number_of_students += 1
def calc_avg(self):
sum=0
for i in range(3):
m = int(input("Enter marks: "))
sum+=m #sum += m
self.avg = sum/3

def calc_grade(self):
if self.avg >80:
self.grade = "A"
elif self.avg >70:
self.grade = "B"
elif self.avg >60:
self.grade = "C"
elif self.avg >50:
self.grade = "D"
else:
self.grade = "E"
@classmethod
def display_info(cls):
print("Current number of students are: ",Students.number_of_students)

s1 = Students("Sachin Tendulkar",103,989898989898989898,"sachin@tendulkar.com")
s2 = Students("Suresh Raina",109,13118989898,"sraina@tendulkar.com")
s3 = Students("Dhoni",119,14118989898,"sraina@tendulkar.com")
s4 = Students("Kapil",120,14618989898,"sraina@tendulkar.com")

s1.calc_avg()
s1.calc_grade()
print("Grade of ",s1.name," is ",s1.grade)
print("#########################")
print("Name: ",s1.name)
print("Email: ",s1.email)
print("Number of students: ",s1.number_of_students)
print("#########################")
print("Name: ",s2.name)
print("Email: ",s2.email)
print("Number of students: ",s2.number_of_students)
print("#########################")
print("Name: ",s3.name)
print("Email: ",s3.email)
print("Number of students: ",s3.number_of_students)
print("#########################")
print("Name: ",s4.name)
print("Email: ",s4.email)
print("Number of students: ",s4.number_of_students)
print("#########################")
Students.display_info()

# Inheritance : The derived class (child class) gets access to all the members of Base (parent) class
# except those which are already present in derived (child) class
class School:
def __init__(self):
print("This is Init in School")
def display_info(self):
print("Printing from Display School")
class Student (School):
def __init__(self):
print("This is Init in Student")
def display(self):
print("Printing from Display Student")
class Teacher(School):
def __init__(self):
print("This is Init in Teacher")
def display(self):
print("Printing from Display Teacher")
sc = School()
st = Student()
t1 = Teacher()

DAY 17:  5 SEPTEMBER 2022

class City:
def __print_data(self):
#putting double underscore in front of the
# name(method or variable) will make it private
print("Sample method")
class School(City):
def __init__(self, name, age):
print("This is Init in School")
self.name = name
self.age = age
def display_info(self):
print("Printing from Display School")
print("Name : ", self.name)
print("Age : ",self.age)
class Student (School):
def __init__(self, name, age, marks):
School.__init__(self,name, age)
self.marks = marks
print("This is Init in Student")
def display(self):
print("Printing from Display Student")
School.display_info(self)
print("Marks :",self.marks)
class Teacher(School):
def __init__(self,name,age,salary):
School.__init__(self,name,age)
print("This is Init in Teacher")
self.salary = salary
def display(self):
print("Printing from Display Teacher")
School.display_info(self)
print("Salary :", self.salary)

st = Student("Sachin", 16, 88)
t1 = Teacher("Kapil", 49, 85000)
st.display()
t1.display()
t1.__print_data()

#Attributes of Students: Name, Age, marks
#Attributes of Teachers: Name, Age, salary

#Encapsulation: information hiding
# eg Parent class doesnt want to share its method with derived class

#write a program to check is a number is prime or not

class CheckPrime:
def __init__(self, number):
self.num = number
self.isPrimeVar = False
self.isValid = False
def checkvalid(self):
if self.num <2:
print("Not a valid number to check")
self.isValid = False
else:
self.isValid = True

def calculatePrime(self):
self.checkvalid()
if self.isValid:
self.isPrimeVar = True
for i in range(2,self.num//2): #10: 2,3,4 => 15: 2,3,4,5,6
if self.num%i ==0:
self.isPrimeVar = False
break
else:
self.isPrimeVar = False
def isPrime(self):
self.calculatePrime()
return self.isPrimeVar

if __name__ == '__main__':
st,en = 500,1500
st2,en2 = 1,300
st3,en3 = 50,900
st4,en4 = 5000, 10000
for i in range(st,en+1):
chkPrime = CheckPrime(i)
result = chkPrime.isPrime()
if result:
print(i, end=", ")
print("\n\n Next Output: \n")
for i in range(st2,en2+1):
chkPrime = CheckPrime(i)
result = chkPrime.isPrime()
if result:
print(i, end=", ")
print("\n\n Next Output: \n")
for i in range(st3,en3+1):
chkPrime = CheckPrime(i)
result = chkPrime.isPrime()
if result:
print(i, end=", ")
print("\n\n Next Output: \n")
for i in range(st4,en4+1):
chkPrime = CheckPrime(i)
result = chkPrime.isPrime()
if result:
print(i, end=", ")

DAY 18: September 6, 2022

#SQLITE 3:
import sqlite3 as sq
con = sq.connect('studentsrecord.db')
cursorobj = con.cursor()
#cursorobj.execute("Drop Table Students")
create_table_student= "CREATE TABLE STUDENTS( ROLLNO INT, NAME VARCHAR(18), " \
"FEES REAL, ADM_DATE DATE, AGE INT, PRIMARY KEY (ROLLNO))"
#cursorobj.execute(create_table_student)
# C of CRUD: Create data (Insert)
insert1 = "INSERT INTO STUDENTS VALUES(103,'Virat Kohli', 3500.50, '12-APR-2021',12)"
#cursorobj.execute(insert1)
insert1 = "INSERT INTO STUDENTS(ROLLNO,NAME, AGE) VALUES(104,'Rohit Sharma',8)"
#cursorobj.execute(insert1)

# R of CRUD: Read => SELECT
select1 = "Select * from Students"
cursorobj.execute(select1)
values = cursorobj.fetchall()
print(values)
for i in values:
print(i[1])

# U for Update (CRUD)
update_query = "Update Students set Fees = 1508.20 Where RollNo=104"
cursorobj.execute(update_query)
# D for Delete (CRUD)
delete_str = "Delete from Students where Rollno = 102"
#cursorobj.execute(delete_str)

con.commit()

DAY 19: September 7, 2022

# OLTP - Online Transaction Processing - live applications
# OLAP - Online Analytical Processing: Data Analytics, Machine Learning, Data Science, Data Warehouse,
## Business Intelligence
#SQLITE 3:
import sqlite3 as sq
from datetime import date #datatime has datetime, date and time
con = sq.connect('studentsrecord.db')
cursorobj = con.cursor()
select1 = "Select max(RollNo) from Students"
cursorobj.execute(select1)
values = cursorobj.fetchone()
max_roll = values[0]
#print(max_roll)

fees_list = [2000,2500,2300,2400,1500,1600,1700,1800,1900,2000,2100,2200,2300,2400,2500,2600,2700]
# Part 1: Steps to demonstrate Insert using dynamic query
while False:
#RollNo: Look at the max value in the database, add one to it
RollNo = max_roll+1
max_roll+=1
#Name
name = input("Enter the Name of the Student: ")
#Age
age = int(input("Enter the age of the Student: "))
#Adm Date - default today's date
adm_date = date.today()
#Fees - read from a list based on age
fees = fees_list[age]
#We have to assign values dynamically to the sql query
insert1 = "INSERT INTO STUDENTS(ROLLNO,NAME, AGE,ADM_DATE,FEES) VALUES(?,?,?,?,?)"
cursorobj.execute(insert1,(RollNo,name,age,adm_date,fees))
con.commit()

ch=input("Enter Zero to stop it: ")
if ch=='0':
break

select1 = "Select * from Students where rollno=104"
cursorobj.execute(select1)
values = cursorobj.fetchall()
print(values)

select1 = "Select * from Students where age>8"
cursorobj.execute(select1)
values = cursorobj.fetchall()
print(values)

select1 = "Select * from Students where age>8 and name like 'S%' "
cursorobj.execute(select1)
values = cursorobj.fetchall()
print(values)

select1 = "Select * from Students where age between 9 and 12"
cursorobj.execute(select1)
values = cursorobj.fetchall()
print(values)

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

PRACTICE SQL (Select command only) at:  livesql.oracle.com

Create an account and you have the complete access:

 

select Employee_ID, First_name, last_name, Phone_number from HR.Employees;

select First_name, last_name, first_name ||’ ‘|| last_name  as FullName from HR.Employees;

select * from HR.Employees;

select count(Employee_ID) from HR.Employees;

select sum(Salary) from HR.Employees where department_ID = 90;

select department_ID, avg(Salary) as AVG_SALARY from HR.Employees group by department_ID order by AVG_SALARY DESC;

DAY 20: September 8, 2022

import os
print(os.name)
#current working directory
print(os.getcwd())
print(os.listdir())
filefound = False
for i in os.listdir():
if i=='mydrawing.png':
print("File found")
filefound = True
os.rename('mydrawing.png', 'myowndrawing.png')
if filefound==False:
print("Current Folder doesnt have this file")

if os.name=='nt':
os.system('cls')
else:
os.system('clear')
print("Screen is cleared!")

from pathlib import Path
#os.makedirs("D:/Sep8data")
#os.remove("D:/Sep8data/sample.txt") # will remove files only
#use rmdir to remove folders
#os.rmdir("D:/Sep8data")
import datetime
content = Path("C:/Users/Hp/PycharmProjects")
#iterate through given directory
for c in content.iterdir():
print(c.name)

dir_content = os.scandir("C:/Users/Hp/PycharmProjects/pr1")
for dir_c in dir_content:
dir_time = dir_c.stat().st_mtime
dir_timestamp = datetime.datetime.fromtimestamp(dir_time).strftime("%Y-%m-%d %H:%M")
print(dir_time, " : ",dir_timestamp)

file_obj = open("file1.txt","r")
#open takes 2 parameters: filename with directory & mode
## mode: r - read; w-write a-add to the existing content
#reading option 1: read() -can read any $ of number
print(file_obj.read())
file_obj.seek(0)
print("======================")
print(file_obj.read(500))
file_obj.seek(0)
#reading option 2: readline() - maximum you can read is one line
print(file_obj.readline(7000))

#reading option 3:readlines() - you can read any number of lines
print(file_obj.readlines())
file_obj.seek(0)
entire_lines = file_obj.readlines()
print(type(entire_lines))
print(entire_lines)
print("Total lines of text: ",len(entire_lines))

print("10th line = ",entire_lines[9])
#close the file
file_obj.close()

#### Write content to the file
## this will delete the previous content completely
##
file_obj = open("file1.txt","a+")
txt = "This is the sample text to be added"
file_obj.write(txt)
file_content_list = ["First line\n","second line to be added\n","Third line"]
file_obj.writelines(file_content_list)
file_obj.close()

DAY 21: September 9, 2022

###########################
###### WORKING WITH JSON #
############################

#JSON files - how to work with them
#JavaScript Object Notation
data = '''
{
"Name": "Sachin",
"Game": "Cricket",
"Interests": [
"Playing Music",
"Driving Cars",
"Sleeping"],
"Address": {
"Street": "121, ABC Road",
"Locality":"Bandra",
"City": "Mumbai"
},
"Phone": [
{
"Type":"Personal Mobile",
"Number":"123456"
},
{
"Type":"Landline",
"Number":"323456"
}
]
}
'''
#load / loads /dump / dumps
import json
data_dict = json.loads(data)
print(data_dict)
print(data_dict["Interests"])

#reading the data from a file - load()
file_handle = open("json_demo.json","r")
data_dict2 = json.load(file_handle)
print(data_dict2)
print(data_dict2['Address'])
file_handle.close()
########## Writing JSON object to Screen (dumps) & File (dump)
data_output = json.dumps(data_dict2, indent=4)
print(data_output)

file_handle2 = open("json9Sep.json","w")
json.dump(data_dict2,file_handle2, indent=4, sort_keys=True)
file_handle2.close()

############################
###### WORKING WITH CSV #
############################

import csv
file_handle = open("D:/dataset/csvdata.csv")
csv_obj = csv.reader(file_handle,delimiter = '|')
row_count = 0
header = []
for row in csv_obj:
if row_count==0:
header = row
row_count = 1
else:
print(header[0]," : ",row[0])
file_handle.close()

h_list = ["Employee","Department","EmailID"]
list1 = ["Sachin","Marketing","s@c.com"]
list2 = ["Rahul","Sales","r@c.com"]
file_handle2 = open("D:/dataset/Sep9csv.csv","w")
csv_obj2 = csv.writer(file_handle2,delimiter=';')
csv_obj2.writerow(h_list)
csv_obj2.writerow(list1)
csv_obj2.writerow(list2)
file_handle2.close()

DAY 22: September 10, 2022

import threading
import time
def thread_func():
for i in range(5):
print("Child Thread Has Now Started")
time.sleep(1)

def thread_func2():
for i in range(5):
print("Second Child Thread Has Now Started")
time.sleep(1)

t1 = threading.Thread(target=thread_func)
t2 = threading.Thread(target=thread_func2)
t3 = threading.Thread(target=thread_func2)
t1.start()
t2.start()
t3.start()
t3.join()
t1.join()
t2.join()

##
#### Accessing Critical Section
#### by acquiring and releasing the lock
import threading
import time
#global variable
x=0

def increment():
global x
x+=1

def perform_task(lock):
for i in range(5):
lock.acquire()
increment()
time.sleep(1)
lock.release()

def main_task():
global x
x = 0
lock = threading.Lock()
t1 = threading.Thread(target=perform_task,args=(lock,))
t2 = threading.Thread(target=perform_task,args=(lock,))
t3 = threading.Thread(target=perform_task,args=(lock,))
t4 = threading.Thread(target=perform_task,args=(lock,))
#start the thread
t1.start()
t2.start()
t3.start()
t4.start()
#join - wait until threads are done executing
t1.join()
t2.join()
t3.join()
t4.join()

for i in range(15):
main_task()
print(f"Iteration {i+1}: x = {x}")

 

DAY 23: September  12   2022

# Topic: ERROR HANDLING
# 3types of errors:
## 1. Syntax error: not following the given rule
## print("Hello
## Syntax errors have to be corrected only then program can run

## 2. Logical error
## If I have 5 apples and I get 3 more from my brother, how many apples do I have?
print(5 - 3) # logical error

## 3. Runtime error - when you get error at the runtime mostly based on the values
a=10
b=2
c=a/b #ZeroDivisionError

#num1 = int(input("Enter a number: ")) #ValueError
file_handle = open("file1.txt") #FileNotFoundError

#How to handle runtime errors:
#1. to identify the block of code that can give you runtime error
#2. We put that block in try
#3. using except keyword, catch that error
#4. (optional) else: code that will run if no error
#5. (optional) finally: the code in this will run irrespective of error
### Method 1: we have nested try
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
except ValueError:
print("Sorry, please enter a valid number and try again!")
else:
try:
div = num1/num2
except ZeroDivisionError:
print("Since numerator is zero, we can not proceed!")
else:
print("The division is ",div)


## Method 2: use single try
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
div = num1 / num2

except ValueError:
print("You have not entered valid number.")
except ZeroDivisionError:
print("Can not proceed further as you have entered zero in denominator")
except Exception:
print("Some error has occured but recheck and try again!")
else:
print("The answer is ",div)
finally:
print("Thank you for using the program")

DAY 24: September  13   2022

 

### NUMPY
## Matrix like structure
import numpy as np

data = range(16)
#range() takes 3 parameters: start val =0, end = 16(upto/excluding), increment =1
mat1 = np.reshape(data,(4,4))
print(mat1)
mat1 = np.reshape(data,(2,8)) #(rows,cols)
print(mat1)
mat2 = np.zeros((3,4))
print(mat2)
mat3 = np.ones((3,3))
print(mat3)
mat4 = np.full((4,4),4)
print(mat4)
data = [[2,5,4],[1,0,1],[3,5,2]]
print(type(data))
mat5 = np.array(data)
print(mat5)
print(type(mat5))
#second row second column
print(mat5[1,1]) #left of , is for rows and right is for columns
#first row
print(mat5[0,:]) #: start from 0 and go upto end
print(mat5[0])
#second and third row for first and second column
print(mat5[1:,:2])
data = [[3,4,2],[1,2,1],[3,2,5]]
mat6 = np.array(data)
print("Matrix 5: \n",mat5)
print("Matrix 6: \n",mat6)
print("#perform addition:")
print(mat5 + mat6) #addition
print(np.add(mat5,mat6))
print("#perform subtraction:")
print(mat5 - mat6) #addition
print(np.subtract(mat5,mat6))
print("#perform multiplication:")
print(mat5 * mat6) #addition
print(np.multiply(mat5,mat6))
print("#perform matrix multiplication:")
#What you see above is simple multiplication, not
#Matrix Multiplication
# For matrix multiplication to happen: compare #rows and #columns
# A(a*b) : a number of rows and b number of columns
# B(m*n) : m number of rows and n number of columns
# for A MATMUL B , b should be equal to m, output matrix is (a * n)
# for B MATMUL A, n should be equal to a, output matrix is (m * b)
#please refer your Matrix chapter for calculation steps
print(mat5 @ mat6)
print(np.matmul(mat5,mat6))
print("#perform division:")
print(mat5 / mat6)
print(np.divide(mat5,mat6))

print("#perform dot multiplication:")
print(mat5.dot(mat6))
print("Number of rows and columns in Matrix 6: ",np.shape(mat6))
#iterate through values using flat
for e in mat6.flat:
print(e)

import matplotlib.pyplot as plt
x = np.arange(0, 3*np.pi,0.3)
y = np.sin(x)
plt.plot(x,y)
plt.show()

DAY 25: September  14  2022

Hi all.. due to some urgent work, I will not be able to take session today. We will take  30 min extra on September 15 and 16 and wrap up our training. Thanks for your understanding and sorry for  change in schedule.

DAY 26: September  15  2022

 

# 3 variables linear algebra problem
# 2x +5y +2z = -38 # 6 -40 - 4 = -38
# 3x - 2y +4z = 17 # 9 +16 - 8 = 17
# -6x + y -7z = -12
import numpy as np

# A = Coefficient matrix
A = [[2,5,2],[3,-2,4],[-6,1,-7]]
A = np.array(A)
# v = variable
# v = [[x],[y],[z]] - we need to find the values
# O = Ouput
O = [[-38],[17],[-12]]
O = np.array(O)
# A * v = O
#We know the value of A and O and find the value of v
# v = A inv * O
#if determinand of A is non-zero only then inverse of the matrix can be calculated
det_A = np.linalg.det(A)
if det_A ==0:
print("Solution is not possible")
else:
Inv_A = np.linalg.inv(A)
v = np.matmul(Inv_A,O)
print("Solution is: ",v)
print("Values of X, Y, Z are: ",v[0,0],v[1,0],v[2,0])

########## PANDAS ############
import pandas as pd
player_stats = {"Name":["Sachin","Laxman","Rahul","Zaheer","Ashish"],
"Type": ["Batting","Batting","Batting","Bowling","Bowling"],
"Runs": [12111, 9898,11213,4500,1200]}
print(type(player_stats))
print(player_stats)
player_stats = pd.DataFrame(player_stats)
print(type(player_stats))
print(player_stats)
fruit_prod = [["Apples", 400,390],["Oranges", 389,411],["Bananas",295,656],["Mangoes",568,451]]
fruit_prod = pd.DataFrame(fruit_prod,columns=["Fruit",2021, 2022], index=["January","February","March","April"])

print(fruit_prod)

#Reading the data from github location
#My github location: github.com/swapnilsaurav
data_set = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/Mall_Customers.csv")
print(data_set)
print(data_set.head()) #first 5 rows
print("Specific value:")
print(data_set['Annual Income (k$)'][0])

#There are 2 ways to read the value from a dataframe:
# 1) using the index name or column name: df.loc[]
# 2) read column and row using number: df.iloc[]
#first 3 rows and first 3 columns - iloc
print("1. First three rows and first three columns: \n",data_set.iloc[0:3,2:5])
print("2. ",data_set.loc[[0,12,21,31],:])
print("3. ",data_set.loc[[0,12,21,31],["Gender","Age","Spending Score (1-100)"]])

DAY 27: September  16  2022

#Plotting a Histogram Graph
import matplotlib.pyplot as plt
import numpy as np

data1 = np.random.normal(100,10,200)
data2 = np.random.normal(60,10,200)
data3 = np.random.normal(100,20,200)
data4 = np.random.normal(120,5,200)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
data_all = [data1,data2,data3,data4]
boxplt = ax.boxplot(data_all)
plt.show()
#Histogram using Matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(50,10,100000)
plt.hist(data)
plt.savefig("hist1.png")
plt.show()
#Boxplot using Matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(50,10,200)
plt.boxplot(data)
plt.title("Compare Delivery Times")
plt.suptitle("For Product A")
plt.xlabel("Products")
plt.ylabel("Delivery Days")
plt.savefig("boxplot1.png")
plt.show()
#Multiple Boxplot using Matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(0,10,200)
data2 = np.random.normal(70,20,20000)
data3 = np.random.normal(130,5,200)
data4 = np.random.normal(0,3,200)
fig,ax = plt.subplots()
ax.boxplot([data,data2,data3,data4])
#plt.boxplot(data)
plt.title("Compare Delivery Times")
plt.suptitle("For Product A")
plt.xlabel("Products")
plt.ylabel("Delivery Days")
plt.savefig("boxplot1.png")
plt.show()

#Plotting stacked bar chart
import matplotlib.pyplot as plt
import numpy as np

fruits = ['Apple','Banana','Cherry','Mango']
jan = [112,98,67,45]
feb = [82,88,47,65]
mar = [102,108,37,145]
apr = [55,55,55,55]
jan_feb = np.add(jan,feb).tolist()
jan_feb_mar = np.add(jan_feb,mar).tolist()
#bars = np.add(jan,feb).tolist()
positions = [0,1,2]
plt.bar(fruits,jan)
plt.bar(fruits,feb,bottom=jan)
plt.bar(fruits,mar,bottom=jan_feb)
plt.bar(fruits,apr,bottom=jan_feb_mar)

plt.show()

#Scatter plot using matplotlib
import matplotlib.pyplot as plt
import numpy as np
jan = [112,98,67,45]
feb = [82,88,47,65]
plt.scatter(x=jan,y=feb)
plt.show()

#Heatmap using matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random((30,30))
#print(data)
plt.imshow(data, cmap='hot')
plt.show()

DAY 28: September  17  2022

 

Basic Python Exercises

 

Problem 1: Area of a Circle

from math import pi
r =
float(input (“Input the radius of the circle : “))
print (“The area of the circle with radius ” + str(r) + ” is: ” + str(pi * r**2))

 

Program 2: Accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers

values = input(“Input some comma seprated numbers : “)
list = values
tuple =
tuple(list)
print(‘List : ‘,list)
print(‘Tuple : ‘,tuple)

 

Program 3: Accepts an integer (n) and computes the value of n+nn+nnn.

a = int(input(“Input an integer : “))
n1 =
int( “%s” % a )
n2 =
int( “%s%s” % (a,a) )
n3 =
int( “%s%s%s” % (a,a,a) )
print (n1)
print(n2)
print(n3)
print (n1+n2+n3)

 

Program 4: Program to print the documents (syntax, description etc.) of Python built-in function(s).  

print(abs.__doc__)

 

Program: Check whether a specified value is contained in a group of values

def is_group_member(group_data, n):
   
for value in group_data:
       
if n == value:
           
return True
    return False
print
(is_group_member([1, 5, 8, 3], 3))
print(is_group_member([5, 8, 3], 1))

 

Program: Create a histogram from a given list of integers

def histogram( items ):
   
for n in items:
        output =

       
times = n
       
while( times > 0 ):
          output +=
‘*’
         
times = times – 1
       
print(output)

histogram([2, 3, 6, 5])

 

Program: Concatenate all elements in a list into a string

def concatenate_list_data(list):
    result=

   
for element in list:
        result +=
str(element)
   
return result

print(concatenate_list_data([1, 5, 12, 2]))

 

Program: Program to compute the greatest common divisor (GCD) of two positive integers.

def gcd(x, y):
    gcd =
1

    if x % y == 0:
       
return y

    for k in range(int(y / 2), 0, –1):
       
if x % k == 0 and y % k == 0:
            gcd = k
           
break
    return
gcd

print(gcd(12, 17))
print(gcd(12, 66))

 

Program: Future value of a specified principal amount, rate of interest, and a number of years

amt = 10000
int = 3.5
years = 7

future_value  = amt*((1+(0.01*int)) ** years)
print(round(future_value,2))

 

Program: Program to locate Python site-packages.

import site;
print(site.getsitepackages())

 

 

Program: Find out the number of CPUs using

import multiprocessing
print(multiprocessing.cpu_count())

 

Program: Parse a string to Float or Integer

n = “246.2458”
print(float(n))
print(int(float(n)))

 

Program: List all files in a directory in Python

import glob
file_list = glob.glob(
‘*.*’)
print(file_list)

 

 

Data Types Programs

Program: Program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string

def string_both_ends(str):
   
if len(str) < 2:
       
return

    return str[0:2] + str[-2:]

print(string_both_ends(‘Thunder’))
print(string_both_ends(‘Bird’))
print(string_both_ends(‘A’))

 

Program: Add ‘ing’ at the end of a given string. If the given string already ends with ‘ing’ then add ‘ly’ instead

def add_string(str1):
    length =
len(str1)

    if length > 2:
       
if str1[-3:] == ‘ing’:
            str1 +=
‘ly’
       
else:
            str1 +=
‘ing’

    return str1

print(add_string(‘ab’))
print(add_string(‘abc’))
print(add_string(‘string’)) 

 

Program: Strip a set of characters from a string

def strip_chars(str, chars):
   
return “”.join(c for c in str if c not in chars)

print(\nOriginal String: “)
print(“The quick brown fox jumps over the lazy dog.”)
print(“After stripping a,e,i,o,u”)
print(strip_chars(“The quick brown fox jumps over the lazy dog.”, “aeiou”))
print() 

 

Program: Format a number with a percentage

x = 0.25
y = –0.25
print(\nOriginal Number: “, x)
print(“Formatted Number with percentage: “+“{:.2%}”.format(x));
print(“Original Number: “, y)
print(“Formatted Number with percentage: “+“{:.2%}”.format(y));
print()

 

Program: Prints the unique words in sorted form from a comma separated sequence of words

items = input(“Input comma separated sequence of words: “)

words = [word for word in items.split(“,”)]
print(“,”.join(sorted(list(set(words)))))

 

Program: Function to create the HTML string with tags around the word(s)

def add_tags(tag, word):
   
return “<%s>%s</%s>” % (tag, word, tag)
print(add_tags(‘i’, ‘Python’))
print(add_tags(‘b’, ‘Python Tutorial’))

 

Program: Sort a string lexicographically

def lexicographi_sort(s):
   
return sorted(sorted(s), key=str.upper)

print(lexicographi_sort(‘This is a long sentence’))
print(lexicographi_sort(‘ThisIsASingleWord’))

 

Program: Reverse words in a string

def reverse_string_words(text):
   
for line in text.split(\n):
       
return(‘ ‘.join(line.split()[::-1]))
print(reverse_string_words(“The quick brown fox jumps over the lazy dog.”))
print(reverse_string_words(“Python Exercises.”)) 

 

Program: Program to get the largest number from a list

def max_num_in_list( list ):
    max = list[
0 ]
   
for a in list:
       
if a > max:
            max = a
   
return max
print(max_num_in_list([1, 2, –8, 0]))

 

Program: Program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples

def last(n): return n[-1]

def sort_list_last(tuples):
   
return sorted(tuples, key=last)

print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))

 

Program: Print a list after removing specified elements

color = [‘Red’, ‘Green’, ‘White’, ‘Black’, ‘Pink’, ‘Yellow’]
color = [x
for (i,x) in enumerate(color) if i not in (0,4,5)]

print(color)

 

Program: Difference between the two lists

list1 = [1, 2, 3, 4]
list2 = [
1, 2]
print(list(set(list1) – set(list2)))

 

Program: Sieve of Eratosthenes method, for computing prime number

def prime_eratosthenes(n):
    prime_list = []
   
for i in range(2, n+1):
       
if i not in prime_list:
           
print (i)
           
for j in range(i*i, n+1, i):
                prime_list.append(j)

print(prime_eratosthenes(100))

 

Program: Program to check if a given key already exists in a dictionary

d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
 
if x in d:
     
print(‘Key is present in the dictionary’)
 
else:
     
print(‘Key is not present in the dictionary’)
is_key_present(
5)
is_key_present(
9)

 

Program: Merge two Python dictionaries

d1 = {‘a’: 100, ‘b’: 200}
d2 = {
‘x’: 300, ‘y’: 200}
d = d1.copy()
d.update(d2)
print(d) 

 

Program: Sum all the items in a dictionary

my_dict = {‘data1’:100,‘data2’:-54,‘data3’:247}
print(sum(my_dict.values()))

 

Program: Get the maximum and minimum value in a dictionary

my_dict = {‘x’: 500, ‘y’: 5874, ‘z’: 560}

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min =
min(my_dict.keys(), key=(lambda k: my_dict[k]))

print(‘Maximum Value: ‘, my_dict[key_max])
print(‘Minimum Value: ‘, my_dict[key_min])

 

Program: Reverse a tuple

#create a tuple
x = (“samplestring”)
# Reversed the tuple
y = reversed(x)
print(tuple(y))
#create another tuple
x = (5, 10, 15, 20)
# Reversed the tuple
y = reversed(x)
print(tuple(y))

 

Program: Find maximum and the minimum value in a set

#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find maximum value
print(max(seta))
#Find minimum value
print(min(seta)) 

 

Conditional statements and loops Programs

 

Program: Construct a specified pattern, using a nested for loop

n = 5;
for i in range(n):
   
for j in range(n, i, –1):
       
print(” “),
   
for k in range(i):
       
print (‘* ‘),
   
print(‘ ‘)

for i in range(n, 0, –1):
   
for j in range(n, i, –1):
       
print(” “),
   
for k in range(i):
       
print(‘* ‘),
   
print(‘ ‘)

        *  

      *  *  

    *  *  *  

  *  *  *  *  

*  *  *  *  *  

  *  *  *  *  

    *  *  *  

      *  *  

        *

 

 

Program: Prints each item and its corresponding type from a list

datalist = [1452, 11.23, 1+2j, True, ‘w3resource’, (0, –1), [5, 12],
{
“class”:‘V’, “section”:‘A’}]
for item in datalist:
  
print (“Type of “,item, ” is “, type(item))

 

Program: Fibonacci series between 0 to 50

x, y = 0, 1

while y < 50:
   
print(y)
    x, y = y, x + y

 

Program: Calculate the number of digits and letters in a string

s = raw_input(“Input a string: “)
d=l=
0
for c in s:
   
if c.isdigit():
        d=d+
1
   
elif c.isalpha():
        l=l+
1
   
else:
       
pass
print
(“Letters”, l)
print(“Digits”, d)

 

Program: Check the validity of a password

Validation:

·        At least 1 letter between [a-z] and 1 letter between [A-Z].

·        At least 1 number between [0-9].

·        At least 1 character from [$#@].

·        Minimum length 6 characters.

·        Maximum length 16 characters.

 

import re

p = raw_input(“Input your password: “)
x =
True
while
x:
   
if (len(p) < 6 or len(p) > 12):
       
break
    elif not
re.search(“[a-z]”, p):
       
break
    elif not
re.search(“[0-9]”, p):
       
break
    elif not
re.search(“[A-Z]”, p):
       
break
    elif not
re.search(“[$#@]”, p):
       
break
    elif
re.search(“\s”, p):
       
break
    else
:
       
print(“Valid Password”)
        x =
False
        break

if x:
   
print(“Not a Valid Password”)

 

Program: Program to print alphabet pattern ‘A’.

result_str=“”;     
for row in range(0,7):     
   
for column in range(0,7):      
       
if (((column == 1 or column == 5) and row != 0) or ((row == 0 or row == 3) and (column > 1 and column < 5))):     
            result_str=result_str+
“*”     
       
else:       
            result_str=result_str+
” ”     
   
result_str=result_str+\n”     
print(result_str); 

  *** 

 *   *

 *   *

 *****

 *   *

 *   *

 *   *

 

Program: A Math Quiz Program

import random
import math
print “Welcome to Math Quiz World”
num1= random.randint(1, 10)
num2= random.randint(
1, 10)
num3= random.randint(
1, 10)
list=[num1, num2, num3]
maxNum=
max(list)
minNum=
min(list)
sqrtOne= math.sqrt(num1)

correct= False
while
(correct == False):
    guess1=
input(“Which number is the highest? “+ str(list) + “: “)
   
if maxNum == guess1:
       
print(“Correct!”)
        correct =
True
    else
:
       
print(“Incorrect, try again”)

correct= False
while
(correct == False):
    guess2=
input(“Which number is the lowest? ” + str(list) +“: “)
   
if minNum == guess2:
       
print(“Correct!”)
        correct =
True
    else
:
       
print(“Incorrect, try again”)

correct= False
while
(correct == False):
    guess3=
raw_input(“Is the square root of ” + str(num1) + ” greater than or equal to 2? (y/n): “)
   
if sqrtOne >= 2.0 and str(guess3) == “y”:
        
print(“Correct!”)
        correct =
True
    elif
sqrtOne < 2.0 and str(guess3) == “n”:
       
print(“Correct!”)
        correct =
True
    else
:
       
print(“Incorrect, try again”)

print(“Thanks for playing!”)

 

Functions Programs

Program: Multiply all the numbers in a list

def multiply(numbers):
    total =
1
   
for x in numbers:
        total *= x
   
return total
print(multiply((8, 2, 3, –1, 7))) 

 

Program: Calculate the factorial of a number

def factorial(n):
   
if n == 0:
       
return 1
   
else:
       
return n * factorial(n-1)
n=
int(input(“Input a number to compute the factiorial : “))
print(factorial(n)) 

 

Program: Write a Python function that that prints out the first n rows of the Pascal’s triangle

Note: Pascal’s triangle is an arithmetic and geometric figure first imagined by Blaise Pascal.

def pascal_triangle(n):
   trow = [
1]
   y = [
0]
  
for x in range(max(n,0)):
     
print(trow)
      trow=[l+r
for l,r in zip(trow+y, y+trow)]
  
return n>=1
pascal_triangle(6)

 

 

Search and Sorting Programs

Program: Program for binary search

def binary_search(item_list, item):
    first =
0
   
last = len(item_list) – 1
   
found = False
    while
(first <= last and not found):
        mid = (first + last) //
2
       
if item_list[mid] == item:
            found =
True
        else
:
           
if item < item_list[mid]:
                last = mid –
1
           
else:
                first = mid +
1
   
return found

print(binary_search([1, 2, 3, 5, 8], 6))
print(binary_search([1, 2, 3, 5, 8], 5))

 

Program: Bubble sort

def bubbleSort(nlist):
   
for passnum in range(len(nlist) – 1, 0, –1):
       
for i in range(passnum):
           
if nlist[i] > nlist[i + 1]:
                temp = nlist[i]
                nlist[i] = nlist[i +
1]
                nlist[i +
1] = temp

nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
bubbleSort(nlist)
print(nlist)

 

Program: Selection sort

def selectionSort(nlist):
   
for fillslot in range(len(nlist) – 1, 0, –1):
        maxpos =
0
       
for location in range(1, fillslot + 1):
           
if nlist[location] > nlist[maxpos]:
                maxpos = location

        temp = nlist[fillslot]
        nlist[fillslot] = nlist[maxpos]
        nlist[maxpos] = temp

nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
selectionSort(nlist)
print(nlist) 

 

Program: Shell sort

def shellSort(alist):
    sublistcount =
len(alist) // 2
   
while sublistcount > 0:
       
for start_position in range(sublistcount):
            gap_InsertionSort(alist, start_position, sublistcount)

        print(“After increments of size”, sublistcount, “The list is”, nlist)

        sublistcount = sublistcount // 2

def gap_InsertionSort(nlist, start, gap):
   
for i in range(start + gap, len(nlist), gap):

        current_value = nlist[i]
        position = i

        while position >= gap and nlist[position – gap] > current_value:
            nlist[position] = nlist[position – gap]
            position = position – gap

        nlist[position] = current_value

nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
shellSort(nlist)
print(nlist)

 

Program: Quick sort

def quickSort(data_list):
    quickSortHlp(data_list,
0, len(data_list) – 1)

def quickSortHlp(data_list, first, last):
   
if first < last:
        splitpoint = partition(data_list, first, last)

        quickSortHlp(data_list, first, splitpoint – 1)
        quickSortHlp(data_list, splitpoint +
1, last)

def partition(data_list, first, last):
    pivotvalue = data_list[first]

    leftmark = first + 1
   
rightmark = last

    done = False
    while not
done:

        while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
            leftmark = leftmark +
1

        while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
            rightmark = rightmark –
1

        if rightmark < leftmark:
            done =
True
        else
:
            temp = data_list[leftmark]
            data_list[leftmark] = data_list[rightmark]
            data_list[rightmark] = temp

    temp = data_list[first]
    data_list[first] = data_list[rightmark]
    data_list[rightmark] = temp

    return rightmark

data_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
quickSort(data_list)
print(data_list)

 

Program: Counting sort algorithm

def counting_sort(array1, max_val):
    m = max_val +
1
   
count = [0] * m

    for a in array1:
       
# count occurences
       
count[a] += 1
   
i = 0
   
for a in range(m):
       
for c in range(count[a]):
            array1[i] = a
            i +=
1
   
return array1

print(counting_sort([1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7))

 

Recursion Programs

Program: Program to calculate the sum of a list of numbers using Recursion.

def list_sum(num_List):
   
if len(num_List) == 1:
       
return num_List[0]
   
else:
       
return num_List[0] + list_sum(num_List[1:])

print(list_sum([2, 4, 5, 6, 7])) 

 

Program: Think of a recursive version of the function f(n) = 3 * n, i.e. the multiples of 3

def mult3(n):
   
if n == 1:
       
return 3
   
else:
       
return mult3(n-1) + 3
for i in range(1,10):
   
print(mult3(i))

 

Program:  Write a function which implements the Pascal’s triangle:

     1

    1 1

   1 2 1

  1 3 3 1

 1 4 6 4 1

1 5 10 10 5 1

def pascal(n):
   
if n == 1:
       
return [1]
   
else:
        p_line = pascal(n-
1)
        line = [ p_line[i]+p_line[i+
1] for i in range(len(p_line)-1)]
        line.insert(
0,1)
        line.append(
1)
   
return line

 

Program:  The sum of the squares of two consecutive Fibonacci numbers is also a Fibonacci number, e.g. 2 and 3 are elements of the Fibonacci sequence and 2*2 + 3*3 = 13 corresponds to Fib(7).

memo = {0:0, 1:1}
def fib(n):
   
if not n in memo:
        memo[n] = fib(n-
1) + fib(n-2)
   
return memo[n]

def find_index(*x):
  
“”” finds the natural number i with fib(i) = n “””
  
if len(x) == 1:
     
# started by user
      # find index starting from 0
     
return find_index(x[0],0)
  
else:
      n = fib(x[
1])
      m = x[
0]
     
if  n > m:
        
return 1
     
elif n == m:
        
return x[1]
     
else:
        
return find_index(m,x[1]+1)

print(” index of a |    a |     b | sum of squares | index “)
print(“=====================================================”)
for i in range(15):
   square = fib(i)**
2 + fib(i+1)**2
  
print( ” %10d |  %3d |   %3d | %14d | %5d ” % (i, fib(i), fib(i+1), square, find_index(square)))

 

Program: Program to calculate the sum of the positive integers of n+(n-2)+(n-4)… (until n-x =< 0)

def sum_series(n):
   
if n < 1:
       
return 0
   
else:
       
return n + sum_series(n – 2)

print(sum_series(6))
print(sum_series(10))

 

Program: Write a Python program to calculate the harmonic sum of n-1

The harmonic sum is the sum of reciprocals of the positive integers

def harmonic_sum(n):
   
if n < 1:
       
return 0
   
else:
       
return (harmonic_sum(n – 1))+ 1/n

print(harmonic_sum(7.0))
print(harmonic_sum(4.0))

 

Program: Program to find  the greatest common divisor (gcd) of two integers.

def Recurgcd(a, b):
    low =
min(a, b)
    high =
max(a, b)

    if low == 0:
       
return high
   
elif low == 1:
       
return 1
   
else:
       
return Recurgcd(low, high % low)

print(Recurgcd(28, 14)

 

Date Time Programs

 

Program: Python script to display the various Date Time formats

import time
import datetime
print(“Current year: “, datetime.date.today().strftime(“%Y”))
print(“Month of year: “, datetime.date.today().strftime(“%B”))
print(“Week number of the year: “, datetime.date.today().strftime(“%W”))
print(“Weekday of the week: “, datetime.date.today().strftime(“%w”))
print(“Day of year: “, datetime.date.today().strftime(“%j”))
print(“Day of the month : “, datetime.date.today().strftime(“%d”))
print(“Day of week: “, datetime.date.today().strftime(“%A”))

 

Program: Find the date of the first Monday of a given week

import time
print(time.asctime(time.strptime(‘2015 50 1’, ‘%Y %W %w’)))

 

 

Class Programs

Program: Program to get all possible unique subsets from a set of distinct integers

Input : [4, 5, 6]

Output : [[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]

 

class py_solution:
   
def sub_sets(self, sset):
       
return self.subsetsRecur([], sorted(sset))

    def subsetsRecur(self, current, sset):
       
if sset:
           
return self.subsetsRecur(current, sset[1:]) + self.subsetsRecur(current + [sset[0]], sset[1:])
       
return [current]

print(py_solution().sub_sets([4, 5, 6]))

 

Program: A class has two methods. First method accept a string from the user, Second method print the string in upper case

class IOString():
   
def __init__(self):
       
self.str1 = “”

    def get_String(self):
       
self.str1 = raw_input(“Please enter a string: “)

    def print_String(self):
       
print(self.str1.upper())

str1 = IOString()
str1.get_String()
str1.print_String()

 

Program: Get the class name of an instance

import itertools
x = itertools.cycle(
‘ABCD’)
print(type(x).__name__)

 

Program: A class constructed by a radius and two methods which will compute the area and the perimeter of a circle

class Circle():
   
def __init__(self, r):
       
self.radius = r

    def area(self):
       
return self.radius ** 2 * 3.14

    def perimeter(self):
       
return 2 * self.radius * 3.14

NewCircle = Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())

 

File Input Output Programs

Program: Count the frequency of words in a file

from collections import Counter
def word_count(fname):
   
with open(fname) as f:
       
return Counter(f.read().split())

print(“Number of words in the file :”, word_count(“readme.txt”))

 

Program: Read a file line by line store it into an array

def file_read(fname):
    content_array = []
   
with open(fname) as f:
       
# Content_list is the list that contains the read lines.
       
for line in f:
            content_array.append(line)
       
print(content_array)

file_read(‘test.txt’)

 

Program: Get the file size of a plain file

def file_size(fname):
   
import os
    statinfo = os.stat(fname)
   
return statinfo.st_size

print(“File size in bytes of a plain file: “, file_size(“test.txt”))

Regular Expression Programs

Program: Match a string that contains only upper and lowercase letters, numbers, and underscores

import re

def text_match(text):
    patterns =
‘^[a-zA-Z0-9_]*$’
   
if re.search(patterns, text):
       
return ‘Found a match!’
   
else:
       
return (‘Not matched!’)

print(text_match(“The quick brown fox jumps over the lazy dog.”))
print(text_match(“Python_Exercises_1”))

 

 

Program: Search the numbers (0-9) of length between 1 to 3 in a given string

import re

results = re.finditer(r”([0-9]{1,3})”, “Exercises number 1, 12, 13, and 345 are important”)
print(“Number of length 1 to 3”)
for n in results:
    
print(n.group(0)) 

 

Program: Abbreviate ‘Road’ as ‘Rd.’ in a given string

import re
street =
’36 Charungee Road’
print(re.sub(‘Road$’, ‘Rd.’, street))

 

Program: Convert camel case string to snake case string

def camel_to_snake(text):
   
import re
    str1 = re.sub(
‘(.)([A-Z][a-z]+)’, r’\1_\2′, text)
   
return re.sub(‘([a-z0-9])([A-Z])’, r’\1_\2′, str1).lower()

print(camel_to_snake(‘PythonExercises’)) 

 

Program: Split a string with multiple delimiters

import re
text =
‘The quick brown\nfox jumps*over the lazy dog.’
print(re.split(‘; |, |\*|\n,text))

 

 

Some More Programs to Test Your Skills

1.      Design a simple Battleship game. It is a strategy type guessing game between you and the computer. The program should create a 5*5 board and computer will conceil its battleship in a perticular row and column (generated using random number). You will be calling “shots” by guessing where the computer has conceiled its battleship. If you guess the position right then computer’s fleet is destroyed and you win.

 

2.      Generate random password for your gmail ID

Password should be a combination of LOWERCASE_CHARS, UPPERCASE_CHARS, DIGITS and SPECIALS CHARS (‘!’, ‘@’, ‘#’, ‘$’, ‘%’, ‘^’, ‘&’, ‘*’)

 

3.      Print All Integers That Aren’t Divisible by Either 2 or 3 and Lie between 1 and 50

 

4.       Number Reverser: This Python number reverser script will reverse any given number. So, 1234 becomes 4321.

 

5.      URL String Parser: Read a URL string and parse it to get information. Example:

www.cardetails.com?model=x&color=black&package=signature&interior=brown&wheels=alloy

one can parse the domain name, model, color, package, interior and wheels information from the above URL. Output should look something like this:

{‘model’: ‘x’, ‘color’: ‘black’, ‘package’: ‘signature’, ‘interior’: ‘brown’, ‘wheels’: ‘alloy’}

Model: x

Color: black

Package: signature

Interior: brown

Wheels: alloy

 

6.      Hangman Program: Write a program to guess the secret word. Enter a word as input and start guessing the game. Initially  _ will be printed to show the number of characters in the word and then as the user guess it correctly the characters appear on the screen. Max wrong guess is 10 and if the guess is correct then chance is not lost.

 

7.      Write a program that prints the numbers from 1 to 100.

 

But for multiples of three print “Fizz” instead of the number

and for the multiples of five print “Buzz”.

For numbers which are multiples of both three and five print “FizzBuzz”.

 

8.      Dice Roller program for your game of ludo: write a program to generate random number generated between 1-6 (or any range you’d like if you tweak the code), and also you can change the number of dice you want to roll.

 

9.      Search a Computer For Specific Files

In this example, we will see how to use the os.walk() module function to walk a directory tree, and the fnmatch module for matching file names.

 

What is OS.walk?

It generates the file names in a directory tree by walking the tree either top-down or bottom-up.

For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

        dirpath                # is a string, the path to the directory.

        dirnames             # is a list of the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’).

        filenames            # is a list of the names of the non-directory files in dirpath.

        To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

 

The fnmatch module is purely a string matching operation.

Simple Matching: fnmatch() compares a single file name against a pattern and returns a boolean indicating whether or not they match. The comparison is case-sensitive when the operating system uses a case-sensitive file system.

 

Filtering: To test a sequence of filenames, you can use filter(). It returns a list of the names that match the pattern argument.


NO VIDEO - PRACTICE DAY- Practice Above Programs Please

Day 29 : Setember 19, 2022

#Plotting a Histogram Graph
import matplotlib.pyplot as plt
import numpy as np

data1 = np.random.normal(100,10,200)
data2 = np.random.normal(60,10,200)
data3 = np.random.normal(100,20,200)
data4 = np.random.normal(120,5,200)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
data_all = [data1,data2,data3,data4]
boxplt = ax.boxplot(data_all)
plt.show()

import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/Dataset/master/student.csv")
plt.boxplot(dataset['age'])
plt.show()

#395 -1 is outlier : 394
#394/4 =98.5

Introduction to Machine Learning

DAY 30: September  20   2022 : Linear Regression

 

 

import pandas as pd
import matplotlib.pyplot as plt
data_df = pd.read_csv("https://raw.githubusercontent.com/swapnilsaurav/MachineLearning/master/2_Marks_Data.csv")
#print(data_df)
plt.scatter(data_df['Hours'],data_df['Marks'])
plt.show()

#features:
X = data_df.iloc[:,0:1].values
print(X)
#Target:
y = data_df.iloc[:,1].values
#pip install scikit-learn package
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
#training the model
regressor.fit(X,y)
print("Linear Regression Output: ")
print("Coefficient/Slope = ",regressor.coef_)
print("Intercept /Constant = ",regressor.intercept_)

# Y = 7.57 * X + 20.7 = 58.5
#37.8 +20.7
#predicting using the model:
output = regressor.predict(X)
output_df = pd.DataFrame({
'Actual': y,
'Predicted': output
})
print(output_df)
 
Thats the end of this training. hope you enjoyed learning with me, i enjoyed interacting with you. If you need any help or you have question for me, please post the question here and I will try to answer them as soon as possible.
Python For Juniors-2

DAY 1 : 16 AUG 2022

Download The Python Installer From Here (We Will Install Python 3.9.9):

https://www.python.org/downloads/release/python-399/

You can follow the instructions to install from here:
http://learn.swapnil.pw/python/pythoninstallation/


Watch Installation Video From Here:   https://www.youtube.com/watch?v=mhpu9AsZNiQ

Download & Install IDE for Python Programming

Follow The Steps From Here: https://learn.swapnil.pw/python/pythonides/

Day 2: AUGUST 18, 2022

 

print("Hello")
print()
print("How \nare you?"); # \n within quotes will give us newline
# \\n is used for newline in Python
print("\\\\n is used for newline in Python")
print()
print(5+3); # this is how we use comment in Python
print("5+3"); #text is represented in Python- " / '
print("Good",end=" ")
print("Evening")
x=10
x=15
#when you change the value, its called variable, in above examples
# x is a variable which takes first value of 10 and then 15
#variable name can contain : a...z, 0..9 and _
first_number =100
number1 = 50
# basic data type: integer (int), float (float), string (str), boolean (bool), complex (complex)
# int - no decimal point
second_number = -99
# type
print(type(second_number))
number3 = -5.0
print(type(number3))
val1 = "How are you?"
print(type(val1))
val2 = True # True or False
print(type(val2))

#Arithmetic operators:
num1 = 54
num2 = 5
print(num1 + num2)
print(num1 - num2)
print(num1 * num2) #multiplication
print(num1 / num2) #division
print(num1 // num2) #integer division -only integer
print(num1 % num2) #modulo - remainder
print(num1 ** num2) #power
import math
print(math.pi)

## int + int = int
# int - int = int
# int / int = float
# int //int = int

# float + float = float
#float - float = float

DAY 3: AUGUST 23, 2022

var1 = 5 #int
print(type(var1))
var2 = 5.0 #float
print(type(var2))
str1 = “Hello” #str – string, data is given within -pair of ‘ or “
print(type(str1))
var3 = True # or False : bool or boolean
print(type(var3))
var4 = 5j  #complex numbers
# square root of -1 – i in Maths
print(type(var4))
print(var4**2)

cost_price = 59
quantity = 27
total_cost = cost_price * quantity

print(“Cost Price is”,cost_price,“and the total quantity bought is”,quantity,“and so the total Cost calculated is”,total_cost)
# f string
print(f“Cost Price is {cost_price} and the total quantity bought is {quantity} and so the total Cost calculated is {total_cost})
a=50
b=23
c=a*b

sduotfhdsfhdsvncx = 50
weuru = 23
sdfjhsdkjfnh = sduotfhdsfhdsvncx * weuru

total_cost = 200
quanity = 77
cost_price = total_cost /quantity
print(f“TC is {total_cost}, quantity is {quantity} and cost is {cost_price:0.2f})
bats,country,pos = “Kohli”,“India”,“Captain”
print(f{bats:<17} plays for {country:>16} as {pos:^15} of the team”)
bats,country,pos = “Momgabera”,“Zimbabwe”,“Wicket-keeper”
print(f{bats:17} plays for {country:>16} as {pos:^15} of the team”)

print(“Good”, end=” “)
print(“Evening”)
# \n – newline: text goes to next line
print(“Hello \zHow are you doing today?”)
print(“Hello \nHow are you doing today?”)

#input
var1 = int(input(“Enter a number: “))  #var1 is str
#var1 = int(var1)   #explicit converting to int
print(f“You have entered {var1})
print(f“data type is {type(var1)})

#assignment 1: WAP to get length and breadth as input and calculate and display
#area and perimeter for a rectangle
#assignment 1: WAP to get radius as input and calculate and display
#area and circumference for a circle

DAY 4: AUGUST 25 2022

#Variables and data types
a = 5 #a is called variable
#variable names are not declared in quotes
print(a)
a=-10  #integer – int : number with no decimal point
print(“Value of a is “, a,“Type of a is “,type(a))
a=10.5   #float : decimal number
print(“Value of a is “, a,“Type of a is “,type(a))
a=“hello”   #string – str : text
print(“Value of a is “, a,“Type of a is “,type(a))
a=False   # or True: boolean – bool : just 2 values
print(“Value of a is “, a,“Type of a is “,type(a))
a=5j # square root of -1
print(“Value of a is “, a,“Type of a is “,type(a))
print(5j**2)

#Basic data types: int, float, str, bool, complex
#variable names: should not start with a number and 
### can have only _ along with alphabets and numbers
#valid examples: A_number, number_one, num1, n1u2m3
#Invalid examples:  8Five, first number, first$number
First = 10
first = 20

# 1 set of operations: ARITHEMATIC OPERATIONS
# performed on numbers- int, float, complex
print(first + First)
print(first – First)
print(first * First)
print(first / First)  #2.0
print(first // First) # 2
print(first % First) # 0
print(first **4)

#ASSIGNMENT 
val1 = First # = and then right side values goes to the left

#COMPARISON OPERATORS
# input values are numbers 
# output values are bool
num1 = 30
num2 = 30
print(num1 > num2) #is num1 greater than num2: F
print(num1 >= num2)  #True
print(num1 < num2)  #False
print(num1 <= num2 )  #True
print(num1 == num2 ) #comparing is == True
print(num1 != num2 ) #False

print(“Hello” > “hello”)
# ASCII A= 65, a=90s
print(“hello” > “hellO”)
print(“hELLO” > “Hello”)

#Boolean – LOGICAL OPERATORS
# input: bool
# output: bool
# and  or not:
#I am NOT going – YES/NO
print(not True)  #False
print(not False#True
num1 = 50
num2 = 48
print(not num1 >= num2) #False
#and: needs both input as True (or all) to be True
# otherwise it will give False (even 1 false will make false)
print(True and True)  #True
print(False and True#False
print(True and False#False
print(False and False#False
print(num1 == num2 and num2 <= num1) # False and True

## or: even if 1 value if True- result is True
### its false only  if all the values are false
print(True or True)  #True
print(False or True#True
print(True or False#True
print(False or False#False

#and has a highest precedence among and,or
# 2+3-2*3 = -1
# not a or b and c

#xor : will be True incase of odd number of True
## else False

#BITWISE:
# input is number
# output is also a number

num1 = 21   # 10101
num2 = 14   # 01110
            # 00100
print(num1 & num2)  #4
print(f{num1} equivalent in binary is {bin(num1)})
print(f{num2} equivalent in binary is {bin(num2)})
print(f“00100 is decimal is {int(0b100)})
#  &  |   ^
print(num1 | num2 )  #bitwise or  – 31
print(num1 ^ num2)  #bitwise xor  – 27

DAY 5:  30- AUG- 2022: IF and Nested IF

 

# IF - Conditions & For & While - LOOPS
num=6
if num%2 ==0:
print("the number is even")
print("I am in EVEN condition")
print()
else:
print("Number is Odd")
print("I am the MAIN program")
print("Thank you")
num=3
if num<0:
print("Sorry, we dont work with negative numbers")
elif num%2 ==0:
print("the number is even")
print("I am in EVEN condition")
else:
print("Number is Odd")

print("Continue...")

choice = "Y"
if choice =="Y":
print("Its a uppercase Y")
elif choice =="y":
print("Its a lowercase y")
else:
print("Its not Y")

if "asD" > "asd":
print("Its asd")
else:
print("ZSD") #lowercase have higher value than capital letters


avg = 95
#>80: Grade A, 70-80: B, 60-70: C, 50-60: D, less than 50: E

if avg>=80:
print("You have scored Grade A")
if avg >= 90:
print("Congratulation on Appreciation Letter")
if avg >=95:
print("You win President's Medal as well")
elif avg>=70:
print("You got Grade B")
elif avg>=60:
print("You got Grade C")
elif avg>=50:
print("You got Grade D")
else:
print("You got Grade E")

#Assignment: modify grade example to check for E grade to A

#WAP to check if a number is divisible by 5 and/or 3
num=30
#Approach 1:
#Calculate:
## Best performance: 8 times
## Worst performance: 8 times
## Average performance: (Best + Worst) / 2
if num%5 ==0 and num%3==0:
print("Number is divisible by 5 and 3")
print()
if num%5 ==0 and num%3!=0:
print("Number is divisible by 5 but not by 3")
if num%5 !=0 and num%3==0:
print("Number is divisible by 3 but not by 5")
if num%5 !=0 and num%3!=0:
print("Number is not divisible by 5 or 3")

#Approach:2
#Best performance: 2
#Worst performance: 3

num=30
if num%5==0:
if num%3==0:
print("Number is divisible by 5 and 3")
else:
print("Number is divisible by 5 but not by 3")
else:
if num%3==0:
print("Number is divisible by 3 but not by 5")
else:
print("Number is not divisible by 5 or 3")

#Nested condition: condition inside a condition

DAY 6: SEPTEMBER 1, 2022

import turtle

#setting up screen
screen = turtle.Screen()
screen.bgcolor("light green")
screen.title("Turtle Program: September 2, 2022")

#create my pen
pen =turtle.Turtle()

for i in range(5,21,3): # 0 - start (inclusive), 4 is the end (exclusive), increment
# range: 5, 8, 11,14
pen.forward(100) #moving -drawing
pen.right(60) #degree

#pen.left(90)
pen.hideturtle() #make turtle invisible
pen.penup()
pen.goto(100,100)
pen.pendown()
for i in range(5,20,3): # 0 - start (inclusive), 4 is the end (exclusive), increment
# range: 5, 8, 11,14

pen.forward(180) #moving -drawing
pen.right(144) # degree

pen.hideturtle() #make turtle invisible
pen.left(90)
pen.penup()
pen.goto(250,250)
pen.pendown()
#done
col = ["red","blue","orange","yellow","purple","green","indigo"]
for i in range(1,3,1):
pen.circle(5*i)
pen.circle(-5*i)
pen.pencolor(col[i%7])

pen.penup()
pen.goto(-300,0)
pen.pendown()

import random
for i in range(10):
val = random.randint(50,200)
pen.forward(val) # moving -drawing
angle = random.randint(20,180)
pen.right(angle)

ts = pen.getscreen()
ts.getcanvas().postscript(file="mydrawing.eps")
turtle.done()

DAY 7:  6 SEPTEMBER 2022

from platform import python_version

print(python_version())

http_code = "209"
match http_code:
case "200":
print("Success")
case "301":
print("Permanently moved to new location")
case "404":
print("Page not found")
case _:
print("Unknown Error Code")

# loops: for & while
print("Printing using For loop")
for i in range(5): #parameters: start =0, end <5, increment
print("Value of I is ",i)
print("Hello")
print("Good Evening")

print("Printing using While loop")
j=0
while j<5:
print("Value of J is ",j)
print("Hello")
print("Good Evening")
j+=1

#range(start =,end <,increment)
#range(3,9,3) = 3,6

#range(start, end) : if you see range() with just 2 values:
# these are START & END, which means default INCREMENT = 1
#range(3,8): 3,4,5,6,7

#range(end) : if you see range() with just 1 value:
# that is END, which means default, START =0, INCREMENT = 1
#range(5): 0,1,2,3,4

# first 5 odd numbers
for i in range(5):
print((i*2)+1)
print("########")
for i in range(1,10,2):
print(i)
print("########")
n=5
for j in range(n):
for i in range(n):
print("*",end=" ")
print()

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

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

#printing multiplication table
n=1
mul = 13
for j in range(mul):
for i in range(mul):
print(f"{(i+1):<2} * {j+1:<2} = {(j+1) * (i+1):<3}", end=" ")
print()

DAY 8:  8 SEPTEMBER 2022

count=5
j=1
while j <=count:
i=1
while i<= count:
print("*",end=" ")
i+=1
print()
j+=1

while True:
num = int(input("Enter a number: "))
if num%2==0:
print("Its an even number")
else:
print("Its an odd number")
ch = input("Enter Y to continue: ")
if ch!="Y":
break

ch = int(input("How many students do you have? "))
count = 1
while count <= ch: # for i in range(ch)
sum = 0
for i in range(3): # subjects
m = int(input("Enter marks: "))
sum += m
avg = sum / 3
'''
Write the logic to find grade
'''
count += 1


#Guessing game version 1
import random
number = random.randint(1,100)
count=0
while True:
guess = int(input("Whats your guess? "))
count+=1
if guess ==number:
print(f"You have guessed it right in {count} attempts!")
break
elif guess > number:
print("Sorry, you have guessed a higher number. Please try again!")
else:
print("Sorry, you have guessed a lower number. Please try again!")

#Guessing game version 2
import random
import time
import datetime as dt
start = time.time()
number = random.randint(1,100)
print("======================")
print("We are guessing: ",number)
print("======================")
count=0
low,high = 1,100
while True:

guess = random.randint(low,high) #int(input("Whats your guess? "))
count+=1
if guess <1 or guess >100:
print("What have you done!!!! Try again")
continue #will go to the beginning of the loop
elif guess ==number:
print(f"You have guessed {guess} right in {count} attempts!")
break
elif guess > number:
print(f"Sorry, you have guessed {guess}, a higher number. Please try again!")
high = guess-1
else:
print(f"Sorry, you have guessed {guess}, a lower number. Please try again!")
low=guess+1
#input()
time.sleep(2)
end = time.time()
print(f"Program started executing at {dt.datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S %p')}"
f" and it finished at {dt.datetime.fromtimestamp(end).strftime('%H:%M:%S')} "
f"so total execution time is {end-start} seconds")

#version 3 :
import random
import time
import datetime as dt
best_time = 0
start = time.time()
total_chances = 0
for i in range(1000):
print("i is ",i)
number = random.randint(1,100)
count=0
low,high = 1,100
while True:
guess = random.randint(low,high) #int(input("Whats your guess? "))
count+=1
if guess <1 or guess >100:
print("What have you done!!!! Try again")
continue #will go to the beginning of the loop
elif guess ==number:
#print(f"You have guessed {guess} right in {count} attempts!")
total_chances+=count
if count <7:
best_time+=1
break
elif guess > number:
#print(f"Sorry, you have guessed {guess}, a higher number. Please try again!")
high = guess-1
else:
#print(f"Sorry, you have guessed {guess}, a lower number. Please try again!")
low=guess+1
#input()
#time.sleep(2)

end = time.time()
print(f"Program started executing at {dt.datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S %p')}"
f" and it finished at {dt.datetime.fromtimestamp(end).strftime('%H:%M:%S')} "
f"so total execution time is {end-start} seconds")
print("Average time per iteration is: ",(end-start)/1000)
print("Average chances per iteration is: ",total_chances/1000)
print("Total better than average attempts: ",best_time)

DAY 9: 13 SEPTEMBER 2022

#Strings
txt1 = 'Hello'
txt2 = "Hello how are youer wekjfdsjf sdjfsdjf jfopdskjpo spodjfopsdfo sodpkfsodpk"
txt3 = '''Hello
good evening
how was your day'''
txt4 = """Hello
have a good day"""
print(type(txt1),type(txt2),type(txt3),type(txt4))
print(txt3)
# What's Your name?
print("What's Your name?")
print('What\'s Your name?')

#slicing / indexing
print(txt2[0]) #first character
num_char = len(txt2) #5
print(txt2[num_char-1])
#3 to 7 characters
print(txt2[2:7]) #starting val is including, ending is upto
print(txt2[0:3]) #first 3 characters
print(txt2[:3]) #first 3 characters
print(txt2[num_char-3:num_char]) #last 3 characters
print(txt2[num_char-3:]) #last 3 characters
print(txt2)
print(txt2[:]) #
## backward indexing
print(txt2[-1]) #last char
print(txt2[-num_char]) #first char
print(txt2[-3:]) #last 3 characters

############
print(txt1 + txt2)
print(txt1*5)
print('E' in "HELLO")
search_txt = 'e'
main_txt = "HEllO"
print(search_txt.lower() in main_txt.lower())
print(search_txt.upper() in main_txt.upper())

#for loop using string
for t in txt1:
print(t)
for i in range(len(txt1)):
print(txt1[i])
txt1 = "hello"
print(txt1.islower())
txt1 = "hello 9"
print(txt1.isalnum())
name = input("Enter your first name: ")
if name.isalpha():
print("Name is saved")
else:
print("Invalid name")

num1 = input("Enter first number: ")
if num1.isdigit():
num1 = int(num1)
else:
print("Can not save this invalid number")


txt1 = "HeLLO HooW are YOU?"
print(txt1.lower())
print(txt1.upper())
print(txt1.title())
txt1 = "HeLLO. HooW are YOU? What are you DOING?"
txt1 = txt1.lower()
txt1=txt1[0].upper() + txt1[1:]
#Strings are immutable
print(txt1)
for c in txt1:
if not c.isalnum() and not c.isspace():
#print(c)
pos =txt1.index(c)
txt1 = txt1[:pos+2] + txt1[pos+2].upper() + txt1[pos+3:]

print(txt1)

DAY 10: 15 SEPTEMBER 2022

#Strings
txt1 = "Hello"
num = txt1.count("l",0,4)
print(num)
num = txt1.find("klo") #returns the position of match
print(num)

txt1 = "How are you doing today?"
content = txt1.split() #returns a list
print(content)
txt2 = "-------------".join(content) #accepts a list value
print(txt2)
old_text = "today"
if txt1.find(old_text) != -1:
txt3 = txt1.replace(old_text,"yesterday")
print(txt3)
else:
print("original text not in the string")

CONST_Name = "Sachin"

27 SEPTEMBER 2022

#Collections in Python
#1 List
list1 = [2,4,True,"Hello", [10,20,30]]
print(list1)
print(type(list1))
print(type(list1[1]))
print(list1[0])
print(list1[1:4])
print(list1[-1])
l2 = list1[-1]
print(type(l2))
print(l2[1])
print(list1[-1][1])

l1 = [1,3,5]
l2 = [2,4,6]
print(l1 + l2)
l3 = l1 * 3
print(l3)
for i in l3:
print(i)
print("###############")
for i in range(len(l3)):
print(l3[i])

# membership test: in
print(3 in l3)

#strings are immutable
str1 = "Hello"
#str1[1]="E"

#lists are mutable
l3[1] = 100
print(l3)

# inbuilt
list3 = [] #creating a blank list
print(type(list3))
print(len(list3))
list3.append(45)
list3.append(35)
list3.append(15)
list3.append(40)
list3.insert(2,80)
list3.insert(99,99)
print(list3)

sum=0
marks = []
for i in range(5):
m = int(input("Enter the marks: "))
marks.append(m)
sum+=m

print("List of marks are: ",marks)
print("Total sum = ",sum)


# [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

total_marks=[]
for j in range(3):
marks = []
print("#####################")
print("Entering marks for student ",j+1)
for i in range(5):
m = int(input("Enter the marks: "))
marks.append(m)
total_marks.append(marks)

print("Total marks: ",total_marks)

total_marks = [[55, 66, 77, 88, 77], [99, 88, 77, 88, 66], [77, 66, 77, 66, 88]]
#index of first subject marks: total_marks[0][0], [1][0], [2][0]

#finding marks in first subject for all the students
print(len(total_marks))
for i in range(len(total_marks)):
print(total_marks[i][0])

#find highest marks in all the subjects
###############################
#finding highest marks in subject 1
max= total_marks[0][0]
for i in range(1,len(total_marks)):
if max < total_marks[i][0]:
max=total_marks[i][0]
print("Highest marks: ",max)

max= -1
for i in range(len(total_marks)):
if max < total_marks[i][0]:
max=total_marks[i][0]
print("Highest marks: ",max)

### solving using first logic
max= []
for j in range(len(total_marks[0])):
for i in range(len(total_marks)):
if i==0:
max.append(total_marks[i][j])
print("max = ",max)
else:
print("i & j = ",i,j)
print("size of max = ",len(max))
if max[j] < total_marks[i][j]:
max[j] = total_marks[i][j]

print("Highest marks: ",max)

29 SEPTEMBER 2022

#list - mutable ordered collection
list1 = [10,3,10,4,10,8,10,2,10]
list1.append(6)
list1.insert(2,10)
print(list1)

#pop - removes element from given position
list1.pop(3)
print(list1)
#remove - removes the element that you give
list1.remove(10)
print(list1)
#want to remove all 10, so first count and then run the loop
tot_ele = list1.count(10)
for i in range(tot_ele):
list1.remove(10)
print(list1)

#reverse the order of the elements
list1.reverse()
print(list1)
list1.sort() #sort in ascending order
print(list1)
list1.sort(reverse=True) #sort in descending order
print(list1)

#index() - gives the position
print("Index of 4 is ",list1.index(4))
#index will give the position of first occurence

list1 = [3, 4, 8, 2, 6]
list2 = list1 #DEEP copy the elements
list3 = list1.copy() #Shallow copy: copies the elements
print("Printing 1")
print(list1)
print(list2)
print(list3)
list1.append(22)
list2.append(33)
list3.append(44)
print("Printing 2")
print(list1)
print(list2)
print(list3)
list4 = list1+list3
list1.extend(list3) #list1 = list1 + list3
print(list1)

###
#input:
#date: 29
#month: 9
#year: 2022
#output: 29th September 2022
date_end=['st','nd', 'rd']+ 17*['th'] + ['st','nd', 'rd']+7*['th']+['st']
month_convert=['January','February','March','April',
'May','June','July','August',
'September','October','November','December']
date = int(input("Enter the date: "))
month = int(input("Enter the month: "))
year = input("Enter the year: ")
output = str(date)+date_end[date-1] + " "+month_convert[month-1] + " "+ year
print(output)


# Tuple: immutable ordered collection
list1 = [4,5,6,7,89,10]
print(type(list1))
t1 = tuple(list1)
print(type(t1))
l1 = list(t1)
print(type(l1))

#immutable:
t1 = (2,2,4,6,7)
t1 = list(t1)
t1.append(8)
t1=tuple(t1)
print(type(t1))
print(len(t1))

t1 = (1,2,3,4) #packing

a,b,c,d = t1 #unpacking
print(a,b,c,d)

a,b,c,d = (1,2,3,4) #unpacking
print(a,b,c,d)

for i in t1:
print(i)
print(t1[2])

OCTOBER 4 2022 (Tuesday)

var1 = {True:50,5:"Sachin","City": "Mumbai"}
print(type(var1))
print(var1[True])
print(var1["City"])
print(var1)

var2 = {"Runs": 15900}
var1.update(var2)
print(var1)

for i in var1.keys(): #gets all the keys
print(i)
print(var1[i])
print(i," : ",var1[i])
for j in var1.values(): #gets all the values
print(j)

for k,v in var1.items():
print(k,":",v)

maindata={"Sachin": ["Sachin Tendkular","India", 15900],
"Ricky": ["Ricky Ponting","Australia",8990],
"Paine":["Tim Paine","Australia",7800],
"Kohli":["Virat Kohli","India",8900]}
filter="Australia"
for i in maindata.keys():
if maindata[i][1] == filter:
print(maindata[i][0])

maindata2 = maindata #deep copy
maindata3 = maindata.copy() #shallow copy
temp = {"Rohit":["Rohit Sharma","India",9281],
"Boucher":["Mark Boucher","South Africa",5600]}
maindata.update(temp)
print("Values after Update to maindata: ")
print(maindata)
print(maindata2)
print(maindata3)

maindata.popitem()
print(maindata2)
maindata.pop("Paine")
print(maindata2)

maindata.clear()
print(maindata2)

#SETS
#Sets
set1 = {3,6,7,3,6,7,3,6,7,3,6,7,3,6,7,3,6,7,3,6,7,3,6,7}
print(type(set1))
print(set1)

for num in set1:
print(num)
list1 = [3,6,73,6,73,6,73,6,73,6,73,6,73,6,73,6,7]
print(list1)
#remove duplicate elements from the list
list1 = list(set(list1))
print(list1)
set1.add(9)

print(set1)
#pop will remove a value
set1.pop()
#remove will remove the given value
set1.remove(3)
print(set1)

set1 = {1,10,2,6,8}
set2 = {2,6,8,21,22}
print(set1 | set2)
print(set1.union(set2))
#print(set1.update(set2))
print(set1)
#union(): set3 = set1.union(set2)
#update(): set1 = set1.union(set2)

print(set1 & set2)
print(set1.intersection(set2))
#intersection_update()

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

print(set1 ^ set2)
print(set2 ^ set1)
print(set1.symmetric_difference(set2))
#symmetric_difference_update()

#isdisjoint
print(set1.isdisjoint(set2))
#issuperset
print(set1.issubset(set2))
#issubset
print(set1.issuperset(set2))

OCTOBER 6, 2022

list_items = [5,10,15,20,25,30,35,40,45]
element = 20
pos = -1
counter = 0
for i in list_items:
if element == i:
pos=counter
else:
counter+=1
if pos==-1:
print("Element is not in the list")
else:
print("Element is found at index ",pos)

#Sorting
## Bubble sort
## Linear sort
## Merge sort
## Insertion sort
## Shell sort
list_items = [5,10,15,20,25,30,35,40,45]
new_list=list_items.copy()

#bubble sort - descending order
for i in range(len(new_list)-1):
for j in range(len(new_list)-1-i):
if new_list[j] < new_list[j+1]:
new_list[j] , new_list[j+1] = new_list[j+1] , new_list[j]
print("Sorted list: \n",new_list)

seq_list = new_list.copy()
#sequential sort - ascending order
for i in range(len(seq_list)-1):
for j in range(i+1, len(seq_list)):
if seq_list[i] > seq_list[j]:
seq_list[i] , seq_list[j] = seq_list[j] , seq_list[i]
print("Sorted list: \n",seq_list)

#Binary search
list_val = seq_list
element = 45
le = len(list_val)
fe = 0
mid = (le+fe)//2
pos = -1

while fe <=le:
if element==list_val[mid]:
#print("Element is found at index ",mid)
pos = mid
break
elif element <list_val[mid]:
le = mid-1
mid = (le + fe) // 2
else:
fe=mid+1
mid = (le + fe) // 2
if pos==-1:
print("Element is not in the list")
else:
print("Element is found at index ",pos)

13 OCTOBER 2022

#Function
def mystatements():
print("Hello")
print("How are you doing?")
print("Good morning")
def mystatements2(name,greeting): #required & positional
print("Hello",name)
print("How are you doing?")
print(greeting)

def mystatements3(name, greeting="Good Morning"): #default & positional
#name is required and greeting is default
#required parameters are given before default
print("Hello",name)
print("How are you doing?")
print(greeting)
return 100

mystatements()
result = mystatements2("Sachin","Good Morning")
print(result) #None is returned
result = mystatements3("Sachin")
print(result)

#function to take 2 numbers as input and
# perform add, sub,multiplication & division
# create - 2 functions: 1)required positional
# 2)default wheren numbers are 99 & 99
#return 4 answers as tuple

20 OCTOBER 2022

#ax**2 + bx +c = 0 ; a,b,c are given then find x
# value of x is given as: (-b +/- sqroot(b**2 - 4ac))/2a
#Solve this:
# 2x**2 +3x -4 = 0
import math
math.sqrt(100)
def QuadEq(a,b,c=-4):
sol1 = (-b+(b**2 - 4*a[0]*c)**0.5)/(2*a[0])
sol2 = (-b-(b**2 - 4*a[0]*c)**0.5)/(2*a[0])
return sol1,sol2


solutions = QuadEq(b=3,a=[2,4,6])
print("Values of x are: ",solutions[0],"and",solutions[1])

#Values of x are: 0.8507810593582121 and -2.350781059358212

#variable length functions
def myfunc1(val1,val2, *values, **setofvalues):
print("Value 1: ",val1)
print("Values: ",values)
print("Set of Values: ", setofvalues)
myfunc1(10,11,12,13,14,15,"16",17,18,19,20,roll=34,name="Sachin",sports="Cricket")

def myfacto(x):
if x==1:
return 1
return x * myfacto(x-1)#recursion

result = myfacto(6)
print("Factorial = ",result)

25 OCTOBER 2022

# OBJECT ORIENTED PROGRAMMING
class Apple:
color="red"
shape="round"
count=0
def __init__(self,kind,price):
self.k = kind
self.cost = price
Apple.count+=1

def display(self):
print("So you have bought "+self.k+" apple at a cost of $",self.cost)

@classmethod
def classdisplay(cls):
print("This is an Apple class with color "+cls.color+" and shape is "+cls.shape)
print("Total Apple objects created are: ",cls.count)

app1 = Apple("Washington", 2)
app2 = Apple("Indian", 2)
app3 = Apple("Fizi", 2)
app4 = Apple("Washington", 3)
app5 = Apple("Fize", 2.5)
app3.display()
app1.classdisplay()
app4.classdisplay()

app6 = Apple("Indian", 5)
app6.display()
app4.classdisplay()

27 OCT 2022

INHERITANCE in PYTHON

class School:
def __init__(self):
print("School Object is created")

def printhi(self):
print("Hello from School")

class Student(School):
def __init__(self):
print("Student Object is created")
def studenthi(self):
print("Hello from Student")
def printhi(self):
print("This feature is not available")

class Teacher(School):
def __init__(self):
print("Teacher Object is created")
def teacherhi(self):
print("Hello from Teacher")
st1 = Student()
st1.studenthi()
st1.printhi()

NOV 1 , 2022

#SQL - Structured Programming Language
#CRUD - Create Read Update Delete

import sqlite3
connection = sqlite3.connect('mydb.db')
cur_obj = connection.cursor()

#cur_obj.execute('Drop Table MEMBERS')

create_table = '''
cREAte Table Members(
MemberID Integer Primary Key,
Name Text,
Address Varchar2(30),
Phone text,
Email text
)
'''
#cur_obj.execute(create_table)
#Create = INSERT command
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(1,"Sachin","Mumbai","123","sa@s.com")
'''
cur_obj.execute(insert_data)
connection.commit()
#SQL - Structured Programming Language
#CRUD - Create Read Update Delete

import sqlite3
connection = sqlite3.connect('mydb.db')
cur_obj = connection.cursor()

#cur_obj.execute('Drop Table MEMBERS')

create_table = '''
cREAte Table Members(
MemberID Integer Primary Key,
Name Text,
Address Varchar2(30),
Phone text,
Email text
)
'''
#cur_obj.execute(create_table)
#Create = INSERT command
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(1,"Sachin","Mumbai","123","sa@s.com")
'''
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(2,"Laxman","Hyderabad","123","la@s.com")
'''
#cur_obj.execute(insert_data)
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(3,"Sourav","Kolkata","123","sg@s.com")
'''
#cur_obj.execute(insert_data)
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(4,"Zaheer","Mumbai","223","za@s.com")
'''
#cur_obj.execute(insert_data)
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(5,"Gautam","Delhi","123","ga@s.com")
'''
#cur_obj.execute(insert_data)
insert_data = '''
Insert into Members (MemberID,Name,Address,Phone,Email) values(6,"Rohit","Mumbai","113","ra@s.com")
'''
#cur_obj.execute(insert_data)

#update the phone number to 222 for MemberID = 2
update_query= '''Update Members Set Phone = "222" where memberid = 2'''
#cur_obj.execute(update_query)

#update the phone number to 222 for MemberID = 2
delete_query= '''Delete from Members where memberid = 3'''
cur_obj.execute(delete_query)

#Reading the content from the table
select_query = '''Select * from Members'''
cur_obj.execute(select_query)
output = cur_obj.fetchall()
for row in output:
print(row)

select_query = '''Select MemberID, Name, Address from Members where MemberID in (5,9,12,15)'''
cur_obj.execute(select_query)
output = cur_obj.fetchall() # []
for row in output:
print(row[0])

connection.commit()
# C - INSERT R- SELECT U-UPDATE D- DELETE
# Read to a file and write to a file
import os
print(os.getcwd())
#os.mkdir("C:\\Users\\Hp\\PycharmProjects\\pr1\\Nov_2")

#absolute path
#relative path

#1. Create File Object
file1 = open("Nov_2\\abc.txt","r") #mode: r-read w-write a-append, r+ w+ a+
poem1 = '''Twinkle Twinkle Little Star
How I WOnder What You Are
Up Above the World So High
Like a Diamond in the Sky
'''

#2 functions to write to a text file: Write & Writelines
#if file1.writable():
#file1.write(poem1)
file1.seek(30)
content1 = file1.readline()
file1.seek(0)
content2 = file1.read()
print("Readline: \n",content1)
print("Read: \n",content2)

#seek() - this is like a pointer/tracker which tracks where you are in the content reading
import sqlite3
conn = sqlite3.connect("mydb.db")
cursorobj = conn.cursor()

select_query1 = "Select Name from Sqlite_schema where type='table'"
select_query2 = "Select * from members"
cursorobj.execute(select_query2)
info = cursorobj.fetchall()
for i in info:
print(i[1])
# Create - Insert
#Read - Select
#Update
#Delete

############ Reading Files ##################
# operations you can perform on a file: Read, Write, Append
# creating, renaming, deleting - operating systems

import os
#os.makedirs("Nov_9") #make directory
#os.rmdir("Nov_9") #remove directory
file_name = "Nov_1/abcd.txt"
file_handle = open(file_name,"a")
#file mode - r, r+, w, w+, a, a+
str_val = """Twinkle Twinkle Little Star
How I wonder
What you are
Up above the world
so high
like a diamond
in the sky
"""
file_handle.write(str_val)

file_handle.close()

###################### NUMPY ################
#Numpy - matrices
import numpy as np
val = range(15)
mat1 = np.reshape(val,(5,3))
print(mat1)
print(mat1.shape)
print(mat1[2:,1])
#matrix 1
val = range(9)
mat1 = np.reshape(val,(3,3))
print("Matrix 1: \n",mat1)
#create matrix out of list of lists
list_val = [[1,2,1],[3,2,1],[2,2,2]]
mat2 = np.array(list_val)
print("Matrix 2: \n",mat2)

print(mat1 + mat2)
print(np.add(mat1,mat2))
#if mat 1 of shape m*n, mat2 should alse be m*n and output is also m*n
print(mat1 - mat2)
print(np.subtract(mat1,mat2))
print(mat1 / mat2)
print(np.divide(mat1,mat2))

## Multiplication - This is NOT MATRIX MULTIPLICATION
print(mat1 * mat2)
print(np.multiply(mat1,mat2))

####Matrix Multiplication
print(mat1 @ mat2)
print(np.matmul(mat1,mat2))

MATPLOTLIB

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randn(1000)
plt.hist(data, bins=30,color="red")
plt.savefig("10NOVHIST.png")
plt.show()

data1 = np.random.normal(100,60, 500) #mean, sd, total
data2 = np.random.normal(100,20, 500) #mean, sd, total
data3 = np.random.normal(180,60, 500) #mean, sd, total
data4 = np.random.normal(180,20, 500) #mean, sd, total
fig = plt.figure()
ax=fig.add_axes([0,0,1,1])
plot_data = [data1,data2,data3,data4]
ax.boxplot(plot_data)
plt.show()

num_hrs = [3,5,9,4,2,8,6,7]
marks = [45,80,89,54,34,90,67,75]
plt.scatter(num_hrs,marks)
plt.show()

num_hrs = [3,5,9,4,2,8,6,7]
marks = [45,80,89,54,34,90,67,75]
marks.reverse()
plt.scatter(num_hrs,marks)
plt.title("Scatter Plot Hrs v Marks")
plt.xlabel("Hours / Week")
plt.ylabel("Marks (out of 100)")
plt.show()
Python For Junior – July 2022
a=5.0
b=6
c=8
d=a+b+c
print(d)
print()
f="hello"
print(type(f))
print(type(d))
#print(type(a)) #comment
# comment
# Data types
#1. int - integer = numbers without decimal (.) - 5, 6, 99, -90
val1 = 5 #int
print(val1)
print(type(val1))
val2 = 5.0 #float
print(type(val2))
#output:
val3 = "asfsdfsdfdsfdf5" #str for string
print(type(val3))
val4 = True #bool - boolean
print(type(val4))
#Operations that can be performed on all the values
#Type of operation: ARITHEMATIC Operations: +, -, *, /, //, %, **
#input: it can take only numbers (int & float)
#output: output will be either int or float
var1 = 40
var2 = 50
print(var1+var2)
print(var1-var2)
print(var1*var2)
print(var1/var2)
# power
print(3**4) # ?
print(10/3) #integer division
print(10//3)
print(10%3) #modulo - gives us remainder

#Assignment
value1 = 50

#comparison operation: Is ... ? Output type is always a boolean: True or False
val1 = 50
val2 = 60
print("val1 > val2: ", val1 > val2) # is val1 greater than val2?
print("val2 > val1: ",val2 > val1) #is val2 greater thab val1?
print("val1 < val2: ", val1 < val2) # is val1 less than val2?
print("val2 < val1: ",val2 < val1) #is val2 less than val1?
val1 = 50; val2 = 60
val1,val2,val3,val4 = 50,50,60,60
print("val1 >= val2: ", val1 >= val2) # is val1 greater than or equal to val2?
print("val2 >= val1: ",val2 >= val1) #is val2 greater than or equal to val1?
print("val1 <= val2: ", val1 <= val2) # is val1 less than or equal to val2?
print("val2 <= val1: ",val2 <= val1) #is val2 less than or equal to val1?

print(val1 == val2)# is it equal to
print(val1 != val2)# is it not equal to

############################
#logical operations -> input is boolean and output is also boolean
#operators: and or not
print(5+3-2*3+2) # / * + -
# 2 + 2
print(True and False or False) #and or
# FALSE OR FALSE = False
val1, val2 = 30, 40
print(val1> val2 or val1 == val2 and val1 <= val2 or val2 > val1 and val1 !=val2)
# T

#True

# 2 softwares: Python (python.org)
# pycharm (jetbrains.com)

print(4+5)
print("4+5")
print("4+5 =",4+5)
var1 = -15 #lets take a variable with name var1 and lets assume its value is -15
print(type(var1)) # int = integer - any numeric value without the decimal part (.)
var1 = 5.0
print(type(var1)) #float - will have decimal part
var1 = "5"
var1 = "Hello"
var2 = var1
print(type(var1)) #str - string - all text
FALSE =False
var1 = "FALSE" #bool - boolean values True
print(type(var1))
# complex - square root (-1)
# i = square root of -1
# i * i = -1
# square root (-25 = -1 * 25): 5i
#int()
val1 = 5j
print(type(val1))
print(5j * 5j)
a = 6-2j
b = 6 + 2j
print(a*b) #( (x-y)*(x+y) = x2 - y2 :36 +4 = 40 +0j)
val1 = 6
val2 = 12
print(val1 + val2)
print(val1 - val2)
print(val1 * val2)
print(val1 / val2) #0.5
print(val1 // val2) #integer division - 0
print(4 ** 3) #power : exponent: 4 ** 3 = 4 cube
print(13 % 5)
### Arithematic operations
#bin
val1 = 8
print("Binary format = ",bin(8))
print("Octal format = ",oct(8))
print("Hexadecimal format = ",hex(8))
print("Octal value = ",oct(0b1011)) # 8, 9, 10, 11 => 10,11,12,13 => 0o13
print("Decimal value = ",int(0b1011)) # 11

quantity = 25
price = 21
total = quantity * price
# The total cost of 25 pens each costing 21 is
print("The total cost of",quantity,"pens each costing",price,"is",total)
print("The total cost of {quantity} pens each costing {price} is {total}")
print(f"The total cost of {quantity} pens each costing {price} is {total}")
total = 1000 #implicit
quantity = 30
test_val = total+quantity #implicit conversion
price = total /quantity #implicit conversion
print(f"The total cost of {quantity} pens each costing {price:0.2f} is {total}")

#input()
user_value = input("Enter a number: ")
print("User input value = ",user_value)
print("Data type of user input is ",type(user_value))
user_value = int(user_value) #explicit conversion
print("User input value = ",user_value)
print("Data type of user input is ",type(user_value))
user_value2 = float(input("Enter another number: "))
print(user_value2)

#WAP to find area and perimeter of a rectangle by taking length and breadth as input
### the area and perimeter of a rectangle of lenght XX and breadth YY is AA and PP respectively
# a = l*b / p = 2 (l+b)
#WAP to find area and circumference of a circle by taking radius as input
### the area and circumference of a circle of radius XX is AA and CC respectively
# pi = 3.04 / a= pi r square / c = 2 * pi * r
a= int(input("a = "))
b= int(input("b = "))
print(a+b)
a= int(input("a = "))
b= int(input("b = "))
print(a+b)

total = 1000 #implicit
quantity = 30
test_val = total+quantity #implicit conversion
price = total /quantity #implicit conversion
print(f"The total cost of {quantity} pens each costing {price:0.1f} is {total}")

a=6
b=5
area = a * b
perimeter = 2 * (a + b)
print(f"area is {area:0.2f}")
print("perimeter is"+ str(perimeter))


## 22 JULY 2022
# IF - elif elif -ELSE

num = 0
if num <0:
print("Its a negative value")
elif num >0:
print("Its a positive value")
else:
print("Its zero!!!")

#repeat set of code
# for - when you know how many times to repeat
# while - repeat untill a condition becomes false
for i in range(0,10): #start, end, increment (default value of increment when not mentioned is 1)
print("How are you?")
print("The value of i =",i)

for i in range(4): #start (default zero when no value given, end, increment (default value of increment when not mentioned is 1)
print("How are you?")
print("The value of i =",i)


for i in range(3,31,3):
print("How are you?")
print("The value of i=", i)

print("I am done")
'''
#wap to print:
*
*
*
*
*
'''
'''
* * * * *
* * * *
* * *
* *
*
'''
n=5
for j in range(n):
for i in range(n-j):
print("*",end= ' ')
print()

## We will not have session on Monday

# wap to print: * * * * *
#generate values from 1 to 20 and check which numbers are divisible by 5
#5 is divisible by 5
#10 is divisible by 5
#15 is divisible by 5
#20 is divisible by 5
for i in range(1,21):
if i%5 ==0:
print(i,"is divisible by 5")

for i in range(1, 21):
print(i)
if i % 5==0:
print("not divisible")
else:
print("divisible")

'''
#1. WAP to generate multiple of a given number, eg 3:
3 * 1 = 3
3 * 2 = 6
...
3 * 10 = 30
'''
'''
Generate multiplication table from 1 to 10
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3 ... 10 * 1 = 10
1 * 2 = 2 2 * 2 = 4 3 * 2 = 6 ... 10 * 2 = 20
...

1 * 10 = 10 2 * 10 = 20 3 * 10 = 30 .... 10 * 10 = 100
'''

# 3. Enter 2 values (length & breadth) and check if they are rectangle or square and find area & perimeter
# Sum of first n natural numbers: 1 + 2 + 3... +100 = n*(n+1)/2
# 4. WAP to find sum of first n natural numbers (given n) using loop and then calculate using formula and confirm
# if they give you same result.

# 5. generate first n odd numbers and first n even numbers

#For
for i in range(1, 11):
for j in range(1, 11):
print(f"{j:2} * {i:2}={j*i:2}",end=" ")
print()
#While
i=1
while True:
print(i)
i=i+1
ch = input("Press y to continue else stop!")
if ch!='y':
break

i=1
while True:
if i%5==0:
print(i)
i=i+1
#ch = input("Press y to continue or else stop!")
if i==60:
break

#Guessing game - between 1 and 100
import random
main_num = random.randint(1,100)
count_steps = 0
start = 1
end = 100
while True:
guess = random.randint(start,end)
count_steps += 1 # a = a+ b => a+=b
if guess == main_num:
print(f"Congratulations! You got the correct value {guess} in {count_steps} chances.")
break
elif guess < main_num:
print(f"Sorry! Its higher than {guess}. Guess again")
start = guess+1
else:
print(f"Sorry! Its lower number than {guess}. Guess again")
end = guess - 1

AUGUST 1  2022: DAY 7

name = "What's Your Name?"
name2 = 'Rahul Dravid'
name3 = '''I am doing fine
You are fine
We are fine'''
name4 = """Where are you going?
Where are you coming from?
Why are you doing \\thi\'s?
Who you are?"""
print(name4)
print(type(name4))
print(name)
# He asked,"What's Your Name?"
t1 = 'He asked,\"What\'s Your Name?\"'
print(t1)
t2 = '''He asked,"What's Your Name?"'''
print(t2)
t3 = name + name2
print(t3)
print(name2 * 4)
t2 = '''He asked,"What's Your Name?"'''
print("Total characters in t2 is ",len(t2))
print(t2[4]) #indexing or slicing
print(t2[2:7])
print(t2[-6:])
print(t2[:])
total_vowel = 0
for i in t2: #aeiou
if i =="a" or i=="A" or i=="e" or i=="E" or i=="I" or i=="i" or i=="o" or i=="O" or i=="u" or i=="U":
#print(i)
total_vowel+=1
print("Total vowel in the text is ",total_vowel)
total_vowel = 0
for i in t2: #aeiou
if i in "aeiouAEIOU":
#print(i)
total_vowel+=1
print("2. Total vowel in the text is ",total_vowel)

 

total_c = 0
for i in t2: #aeiou
if i not in ”’aeiouAEIOU ,’;:!@#$%^&*””’:
#print(i)
total_c+=1
print(“2. Total consonants in the text is “,total_c)

t1 = “Good MOrning”
print(t1.count(‘o’) + t1.count(‘O’))
print(t1.upper().count(‘O’))
print(t1.split()) #when you dont pass any value in split-it splits on space

txt = “Enter,the,comma,separated,content”
words = txt.split(‘,’)
print(words)
new_txt = “”.join(words)
print(new_txt)

txt = “Enter the comma separated content: “
new_txt=“”
for i in txt:
if i.lower() not in “aeiou”:
new_txt+=i
print(new_txt)

txt3 = “HOWARE YOU”
print(txt3.isalpha() and txt3.isupper())

#Assignmets

Assignments

1. Write a Python program to move spaces to the front of a given string.

               Input: Hello from Hyderabad

               Output:   HellofromHyderabad

2. Write a Python program to compute sum of digits of a given string.

               Input: ABC369abc810xyz

               Output:27

3. Write a Python program to capitalize first and last letters of each word of a given string.

               Input: hello from hyderabad

               Output: HellO FroM HyderabaD

4. Write a Python program to print the index of the character in a string.

               Input: Hello

               Output:

                              Current character h position at 0

                              Current character e position at 1

                              Current character l position at 2

                              Current character l position at 3

                              Current character 0 position at 4

5. Write a Python program to swap comma and dot in a string.

               Input: 75.99,25.11

               Output: 75,99.25,11

More Programs to Practice

.     Swap commas and dots in a String

     Program to convert String to a List

.     Count and display vowels in a string

    Python program to check the validity of a Password (Atleast 1 caps, 1 digit and minimum 8 characters)

.     Python program to count number of vowels using sets in given string

6.     Check for URL in a String

7.     Check if a Substring is Present in a Given String

8.     Check if two strings are anagram or not (contains same set of characters)

9.     Map function and Dictionary in Python to sum ASCII values

10.  Map function and Lambda expression in Python to replace characters

11.  SequenceMatcher in Python for Longest Common Substring

12.  Print the initials of a name with last name in full

13.  Find the k most frequent words from data set in Python

14.  Find all close matches of input string from a list

15.  Check if there are K consecutive 1’s in a binary number

16.  Check if both halves of the string have same set of characters in Python

17.  Find the first repeated word in a string in Python

18.  Second most repeated word in a sequence in Python

19.  K’th Non-repeating Character in Python

20.  Reverse words in a given String in Python

21.  Print number with commas as 1000 separators in Python

22.  Remove all duplicates words from a given sentence

23.  Sort words of sentence in ascending order

24.  Reverse each word in a sentence

25.  Python code to print common characters of two Strings in alphabetical order

26.  Python program to count upper and lower case characters without using inbuilt functions

 

SOLUTIONS

 

 (First Make attempt to solve on your own and only then look for the solutions

 

inputStr = input("Enter the String: ")
noSpacesChars = [ch for ch in inputStr if ch!=' ']
print(noSpacesChars)
spacesCount = len(inputStr) - len(noSpacesChars)
result = ' '*spacesCount
result = '"'+result + ''.join(noSpacesChars)+'"'
print(result)

 

inputStr = input("Enter the String: ")
sumDigit = 0
for ch in inputStr:
    if ch.isdigit() == True:
        chr2int = int(ch)
        sumDigit = sumDigit + chr2int
print("Sum of Digits in the String are: ", sumDigit)

 

inputStr = input("Enter the String: ")
inputStr = inputStr.title()  #Set to Title Case
result = ""
for
word in inputStr.split():
    result += word[:-1] + word[-1].upper() + " "
print(result[:-1])

 

inputStr = input("Enter the String: ")
for counter, ch in enumerate(inputStr):
    print("Current character", ch, "position at", counter)

 

amount = "75.99,25.11"
amountTrans = amount.maketrans('.,', ',.')
# maketrans() method returns a translation table
# translate
amount = amount.translate(amountTrans)
print(amount)

 

 

 

DAY 8: AUGUST  3, 2022

#LIST
## Basic datatypes - str, int, float, bool, complex
#Collections
mylist = [10,20.5,False,"Hello",50,[2,3,4]]
print(type(mylist)) #data type of the variable
print(len(mylist)) #counting the members in the list
members = len(mylist)
print(mylist) #dislaying all the members
print(mylist[0])
print(mylist[members-1])
print(mylist[-1])
print(type(mylist[-3]))

#go through each member of the list
for i in mylist:
print(i)
print([1,2,3]+[2,4,6])
print([1,2,3]*3)

#WAP to store marks of 5 subjects
marks = []
for i in range(5):
m = int(input("Enter the marks: "))
marks.append(m)

print(marks)
marks.insert(1,100)
print("After Insert: ",marks)
l1 = [20,10,30,25,45,40]
l1.sort()
print(l1)
l1.reverse()
print("After reverse: ",l1)

#Lists are mutable
l1 = [1,3,5,7]
l1[2]=50
print("After edit: ",l1)

#strings are immutable - you cant edit (you can overwrite)
s1 = "Hello"
#s1[0]="h" - this is not possible in string

#assignment & copy
l1 = [1,3,5,7]
l2 = l1 #they both point to same lists
l3 = l1.copy() #l3 is a different list created with same values as l1
print("==> l1",l1)
print("==> l2",l2)
print("==> l3",l3)
l1.append(77)
l2.append(99)
l3.append(66)
l1.append(88)
print("After ==> l1",l1)
print("After ==> l2",l2)
print("After ==> l3",l3)
mainlist = []
while True:
print("Select your option: ")
print("1. Display the content\n2. Add member to end of list\n3. Add member to a specific position")
print("4. Remove a member\n5. Remove member from a specific position\n6. Display sorted list")
print("7. Display reverse list \n8. Exit")
ch = int(input("Enter you choice: "))
if ch==1:
print("Current list is:\n",mainlist)
elif ch==2:
value = int(input("Enter the element to be added: "))
mainlist.append(value)
elif ch==3:
value = int(input("Enter the element to be added: "))
pos = int(input("Enter the position where element to be added: "))
mainlist.insert(pos,value)
elif ch==4:
value = int(input("Enter the element to be removed: "))
if value in mainlist:
mainlist.remove(value)
else:
print(f"{value} is not in the list")
elif ch==5:
pos = int(input("Enter the position of element to be removed: "))
if pos > len(mainlist):
print(f"Sorry, {pos} position doesnt exist")
elif pos<=0:
print("Invalid option!")
else:
pos-=1
mainlist.pop(pos)
elif ch==6:
mainlist.sort()
#print("Sorted list is:\n", mainlist)
elif ch==7:
mainlist.reverse()
#print("Reverse list is:\n",mainlist)
elif ch==8:
break
else:
print("Invalid choice! Please select from below list")
continue

print("Thank you for using my program, see you soon!")

DAY 9: Aug 5 2022

l1 = [2,4,6,8]  #list
t1 = (2,4,6,2,8,2,6)
print(t1.count(2))
print(t1.index(6))
#Tuple is immutable version of List
l1 = tuple(l1)

for i in l1:
print(i)
t2 = (1,False,3,"hello",[2,4,6])
t3 = (1,1)
print("ASCII value: ",ord('a'))
print("ASCII value: ",ord('0'))
if t2 > t3:
print("larger: ",t2)
else:
print("larger: ",t3)
print(t2)
val1,val2,val3,val4,val5 = t2
print(val3)

# you cant compare string with anyother values
#float, int & bool (False 0 True 1)
#complex
if 'abc' > 'aaC':
print("Smaller")
else:
print("Capital")
t3 = list(t3)

# Dictionary
val1 = {'Name':'Sachin',"Age": 32, "Runs": 20000,4:"Mumbai"}
print(val1[4])

d1 = {}
name = "Rahul"
age = 43
runs = 15000
d2 ={"Name": name,"Age": age,"Runs": runs}
d1.update(d2)

print(d1)

#WAP to add 5 students marks (3 subjects) in a dictionary, where RollNo is the key and
#marks should be saved as a list
marks_all = {}
for i in range(3):
rollno = int(input("Enter the Roll No.: "))
list=[]
for i in range(3):
m = int(input("Enter marks: "))
list.append(m)
t_dict = {rollno:list}
marks_all.update(t_dict)

print("Marks = ", marks_all)

DAY 10: 8 AUGUST 2022

 

dict1 = {}
t_dict = {21:"Sachin"}
dict1.update(t_dict)
#Add books
### bookid, title, author,price, copies
all_books={}
t_dict = {102:["Python Programming","AB CD", 25.90, 5]}
all_books.update(t_dict)
t_dict = {103:["Python Programming by Someone","Someone", 15.90, 3]}
all_books.update(t_dict)
print(all_books)
#add members
print("Printing items:")
for i in all_books.items():
print(i)
print("Printing items:")
bid = 103
for i,j in all_books.items():
if i == 103:
print(i," : ",j[0],j[-1])

print("Printing only keys:")
for i in all_books.keys():
print(i)
print("Printing only values:")
for i in all_books.values():
print(i)

### Edit the values for bid 103
t_dict={}
for i,j in all_books.items():
if i == 103:
j[3] = j[3]-1
t_dict={i:j}

all_books.pop(103)
all_books.update(t_dict)
print(all_books)

#SET
s1 = {1,2,3,4,5,2,3,4,5} #set will not print duplicate values
print(s1) #set doesnt have any order
s1.pop() #it will remove any value
print(s1)
s1.clear() #remove all the members
print(s1)
#you can convert set to list, set to tuple,
#list to set , tuple to set
# tuple to list, list to tuple
l1 = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
print(l1.count(5))
l1 = list(set(l1))
print(type(l1))
print(l1)
#specific set operations
#UNION
s1={1,2,3,4}
s2 = {3,4,5,6}
print("UNION:",s1 | s2)
print("UNION:",s1.union(s2))
#INTERSECTION
print("INTERSECTION:",s1 & s2)
print("INTERSECTION:",s1.intersection(s2))
#DIFFERENCE
print("DIFFERENCE:",s1 - s2)
print("DIFFERENCE:",s1.difference(s2))
#SYMMETRIC DIFFERENCE
print("SYMMETRIC DIFFERENCE:",s1 ^ s2)
print("SYMMETRIC DIFFERENCE:",s1.symmetric_difference(s2))
s1.update(s2)
s1.intersection_update(s2)
s1.difference_update(s2)
s1.symmetric_difference_update(s2)

##Functions
print() #inbuilt functions

#definition of a function:
## should begin with def keyword, followed by the function
##name that you want to give and then ():
## in the body of definition, write the logic
def mysum():
a=50
b=60
print("Sum is: ",a+b)

mysum()

def mysum1():
a=50
b=60
#print("Sum is: ",a+b)
return a+b #function is sending the value back to the called function

val = mysum1() #called function should catch
print("The answer is: ",val)

#third type when we also pass the value to
# function definition
def mysum2(x,y): #a is passed to x and b is passed to y
sum = x+y
return sum
a=11
b=24
val = mysum2(a,b)
print("Value is: ",val)

#code reusability

DAY 11: August 10 2022


#How to use functions

def fun_sum(a,b,c):
print(a)
print(b)
print(c)
sum = a+b+c
#print("Sum = ",sum)
return sum

x = 51
y = 52
z = 59
fun_sum(x,z,y) #mapping of variables in function definition is done left to right
#number of values that you pass in same as the parameters defined in the function

# simple interest = principle * timeline (in years) * rate of interest (%)
#Priciple is the amount that you borrow
#Timeline is for how many years you borrow
# rate of interest is the ammount / hundred that you need to pay because you borrowed
# How much simple interest I will pay if I borrow 45000 for 9 months @ of 5% interest
# 45000 * 9/12 * 5/100 = ?
# Write a function that takes 3 values- p,t,r and returns simple interest
#In the main program take the input and pass on to the function and
#after you get the simple interest from the function, add it to the amount
#and display today amount due.

#Function - which has required positional arguments
def simple_interest(p,t,r):
si = p*t*r/100
return si
principle = float(input("Enter borrowed money ($): "))
time = float(input("Enter time (in years):"))
rate = float(input("Enter rate of interest (%):"))
si = simple_interest(principle, time,rate)
print("The interest is ",si,"and total payment due is $",si+principle)
print("Total interest paid is: ",si)


# Function with default values
def simple_interest(p,t,r=5):
si = p*t*r/100
return si
principle = float(input("Enter borrowed money ($): "))
time = float(input("Enter time (in years):"))
rate = float(input("Enter rate of interest (%):"))
si = simple_interest(principle, time,rate)
print("The interest is ",si,"and total payment due is $",si+principle)
print("Total interest paid is: ",si)
si = simple_interest(principle, time)
print("The interest is ",si,"and total payment due is $",si+principle)
print("Total interest paid is: ",si)

# Function with keyword argument
def simple_interest(p,t,r=5):
si = p*t*r/100
return si
principle = float(input("Enter borrowed money ($): "))
t = float(input("Enter time (in years):"))
rate = float(input("Enter rate of interest (%):"))
si = simple_interest(t=t,p=principle,r=rate) #example of keyword
print("The interest is ",si,"and total payment due is $",si+principle)
print("Total interest paid is: ",si)
si = simple_interest(principle, t) #positional
print("The interest is ",si,"and total payment due is $",si+principle)
print("Total interest paid is: ",si)

# create a function which will take as parameter: num1, num2 and operator
#my_calculator(n1,n2,op) #op can be: + , - / * **, // %
#based on what you pass to the function, it should return the result
#call the function from main
# demonstrate using same program - positional and required functions,
## default functions and keyword arguments

#variable length arguments functions
def my_func(x,a,b,*y, **z): #function definition has *parameter (tuple) and **parameter (read as dictionary)
print(x)
print(y)
print(z)
if 'name' in z.keys():
print("name is ",z['name'])
if 'city' in z.keys():
print("Belongs to ",z['city'])

my_func(56,12,24,36,48,60,70,75,80,85,90,95,name="Sachin",team="India",type="Batting")
print()

#wap to calculate area of a square/rectangle

def my_area(*data):
if len(data)==1:
return 3.15*data[0]*data[0]
if len(data)==2:
return data[0] * data[1]
area = my_area()
print(area)
area = my_area(3)
print(area)
area = my_area(5,6)
print(area)

## Single function to calculate 2 areas:
def my_area(data1, data2=-1):
if data2==-1:
return 3.15*data1*data1
if data2!=-1:
return data1 * data2

Day 12  August 12, 2022

 

######################  MODULE FILE:  test1.py ##############

#Required positional
#Default
#Keyword
#variable length

def add_val(list1, val):
list1.append(val)
return list1

def insert_val(list1, val,pos):
'''This function takes a list and appends a value to it'''
list1.insert(pos,val)
return list1

if __name__=="__main__":
listn = [2,4,6,8,10]
listn = add_val(listn,12)
print(listn)
listn = insert_val(listn,pos=3,val=18)
print(listn)
help(insert_val)
help(input)

 

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

####################  FILE 2 – from where we call #################

import test1

list2 = [1,2,3,4,5]
result = test1.add_val(list2,99)
print(result)

def test_func():
print("HEllo")
#recursive function is to call itself
test_func()

#test_func()

#Factorial ?
# 9! = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
# 9! = 9 * 8!
# 8! = 8 * 7!

def my_factorial(n):
#...
if n<=1:
return 1
return n * my_factorial(n-1)

result = my_factorial(-1)
print("Factorial is ",result)

#
import time
print("Hello")
time.sleep(1)
print("hello")
import datetime
print("Time now is ",datetime.datetime.now())
print("Time now is ",datetime.datetime.utcnow())
print("Date: ", datetime.date.today())

#Module: python file
# functions or it have classes

#Datetime is a module which has following classes:
## 1. Datetime
## 2. Date
## 3. Time
## 4. timedelta
date_1 = datetime.date(2022,8,12)
print(type(date_1), " : ",date_1)

 

Day 13  AUGUST  15, 2022

CLASS & OBJECTS – 1

 

class Apple:
#Class level variables
color = "Red"
shape = "Round"

#Object level Function - METHODS
def apple_name(self,name):
self.name = name
def eat(self):
print(f"I am eating the apple {self.name}")

apple1 = Apple()
apple2 =Apple() #Creating objects
apple2.apple_name("Fizi Apple")
apple1.apple_name("Washington Apple")
Apple.color = "Black"
print("apple1.name: ",apple1.name)
print("apple1.color: ",apple1.color)
print("apple2.name: ",apple2.name)
print("apple2.color: ",apple2.color)
print(Apple.color)


class Student:
school_name = "Indigo International School"
def create_new_student(self,name,phoneno):
self.name = name
self.phoneno = phoneno
def get_book(self,title,author):
self.title = title
self.author = author
def print_values(self):
print("Name: ",self.name)
print("School: ",Student.school_name)
print("Phone No: ",self.phoneno)
print("Title: ",self.title)
print("Author: ",self.author)
s2 = Student()
s1 = Student()
s1.create_new_student("Sachin", 1234)
s1.get_book("Python","John")
s2.create_new_student("Rahul", 3234)
s2.get_book("ML","George")

s2.print_values()

#constructor => initialization or init()
# its the best place to assign values
class Student: #something is being designed
school_name = "Indigo International School"
total_students = 0
def __init__(self,name,phoneno): #called automatically when object is created-
self.name = name
self.phoneno = phoneno
self.title = ""
self.author = ""
Student.total_students += 1

def get_book(self,title,author):
self.title = title
self.author = author
def print_values(self):
print("Name: ",self.name)
print("School: ",Student.school_name)
print("Phone No: ",self.phoneno)
print("Title: ",self.title)
print("Author: ",self.author)
@classmethod
def counter(cls):
print("Total students are: ",cls.total_students)

s2 = Student("Sachin", 1234) #object is born
s1 = Student("Rahul", 3234)
s1.get_book("Python","John")
s2.get_book("ML","George")

s2.print_values()
s1.counter()
#Assignment:
#create more objects for Apple and Student classes and see the behavior
#

 

DAY 14 :  AUGUST 17, 2022

#Class & Objects
class School:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"School class is initialized by {self.name}")
def display(self):
print(f"My name is {self.name} and I am {self.age} years old!")
def tell(self):
print("Sample method in parent class")
class Teacher(School):
def __init__(self):
print("Teacher class is initialized")

class Student(School):
def __init__(self,sname,sage):
School.__init__(self,sname,sage)
print("Student class is initialized")
def tell1(self):
print("Sample method in Student")
school1 = School("ABC International School", 110)
school2 = School("XYZ Private School", 10)
student1 = Student("ABC Private School", 18)
student1.tell()
student1.display()
school2.display()


########################
class Shape:
def area(self):
print("Sorry area is not possible for this shape")
def perimeter(self):
print("Sorry perimeter is not possible for this shape")
def length(self):
print("Sorry length is not possible for this shape")
class Point(Shape):
def __init__(self, value):
self.value = value
print("Got the value as ",self.value)
class Line(Shape):
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
print("Got the values as ",self.value1, self.value2)
class Square(Shape):
def __init__(self, value):
self.value = value
print("Got the side as ",self.value)
class Rectangle(Shape):
def __init__(self, l,b):
self.l = l
self.b = b
print("Got the length and breadth as ",self.l, self.b)
def area(self):
self.area = self.l * self.b
print("Area is ",self.area)
print("###########################")
r1 = Rectangle(5,6)
s1 = Square(5)
l1 = Line(10,5)
p1 = Point(9)
p1.area()
r1.length()

##########################
# A program to find if a number if Prime or not
class CheckPrime:
#initializaton
def __init__(self,number):
self.num = number
#self.valid = False
print(f"Got {self.num} to check")
def checkvalid(self):
if self.num >=1:
return True
else:
return False
def isPrime(self):
for i in range(2,self.num//2):
if self.num % i==0:
return False
return True
def generatePrime(self,st=2,en=100):
for i in range(st,en+1):
self.num = i
if self.isPrime():
print(self.num, end=" ")

# 11: 2,3,4,5,6,7,8,9
if __name__ == "__main__":
num = 331
cp = CheckPrime(num)
if cp.checkvalid():
if cp.isPrime():
print("Number is a Prime")
else:
print("Number is not a Prime")
else:
print("Sorry, number is invalid")
start,end = 10,2000
print(f"Now generating Prime Numbers between {start} and {end}")
cp.generatePrime(start,end)

DAY  15:  AUGUST  19, 2022

 

#Work with files
fileobj = open("abc.txt","r")
'''
open() takes filename and mode:
a - append
r - read
w - write w+
'''
val1 = """Hello My name is Sachin
I am a cricketer
I live in Mumbai"""
val2=["Hello everyone, how are you doing today?\n",
"I am fine and great\n","Hope you are doing good too\n"]
#fileobj.writelines(val2)
fileobj.close()
fileobj = open("abc.txt","r+")
#file_content = fileobj.read()
print(fileobj.readline())
print("========================")
fileobj.seek(0)
filecont = fileobj.read()
n =filecont.lower().count("hello")
print(n)
#print(type(file_content))

##
#most common database is RDBMS - Relational Database Management System
# SQL (Structured Query Language) is the programming language of database
#RDBMS - MySql, Oracle, SQL Server,DB2, SQLITE2
## to work with SQLITE2 database, we need to import sqlite3

import sqlite3
con = sqlite3.connect("learnDB.db")
connobj = con.cursor()
#SQL command to create a table
q1 = '''create table students(ID Integer, Name text, Phone text, EMAIL text)'''
#connobj.execute(q1)
q2 = '''Insert into students(ID, NAME, PHONE,EMAIL) VALUES(101,'Sachin','123456','sachin@sachin.com')'''
q22 = '''Insert into students(ID, NAME, PHONE,EMAIL) VALUES(102,'Rahul','223456','rahul@sachin.com')'''
q23 = '''Insert into students(ID, NAME, PHONE,EMAIL) VALUES(103,'Laxman','323456','laxman@sachin.com')'''
#connobj.execute(q2)
#connobj.execute(q22)
#connobj.execute(q23)
#insert or update or delete - these commands need to be commited
con.commit()
q3 = '''Select * from students'''
connobj.execute(q3)
data = connobj.fetchall()
for d in data:
print(d[1]) #list

########## Working with operating system ###########
#disclaimer: different for windows and mac
import os
print(os.name)
print(os.getcwd())
#os.rename('abc.txt','xyz.txt')
print(os.listdir())
os.system('cls')

DAY 16 :  AUGUST 24, 2022


#inheritance in class
class City:
    def dummy(self):
        print(“Dummy method of City class”)
class School:
    school_info = {}
    def __init__(self,sname,city,website):
        self.sname = sname
        self.website = website
        self.city = city
        print(f“School object {self.sname} is created”)
        t_dict = {sname:[city,website]}
        School.school_info.update(t_dict)
    def myschool_info(self):
        print(“Displaying all the information of My School:”)
        print(“School Name: “,self.sname)
        print(”      City : “,self.city)
        print(”    Website: “,self.website)
    def dummy(self):
        print(“This is a dummy method in School class”)
    @classmethod
    def display_allinfo(cls):
        print(“Displaying all the information of Schools:”)
        for i,j in cls.school_info.items():
            print(i,” : “,j)

class Student(SchoolCity):
    def __init__(self,name,rollno,emailid,sname,city,website):
        School.__init__(self,sname,city,website)
        self.name = name
        self.rollno = rollno
        self.emailid = emailid
        print(f“Student with name {self.name} is created”)

    def student_info(self):
        print(”    NAME: “,self.name)
        print(” ROLL NO: “,self.rollno)
        print(“EMAIL ID: “,self.emailid)
    def dummy(self):
        print(“This is a dummy method in Student class”)
class Teacher(CitySchool):
    def __init__(self,name,age,sname,city,website):
        School.__init__(self,sname,city,website)
        self.name = name
        self.age = age
        print(f“Teacher with name {self.name} is created”)
    def teacher_info(self):
        print(“NAME: “,self.name)
        print(” AGE: “,self.age)
    def dummy123(self):
        print(“This is a dummy method in Teacher class”)

sc1 = School(“ABC School”“Vizag”,“www.abcschool.org”)
sc2 = School(“DEF International School”“Delhi”,“www.defschool.org”)
st1 = Student(“Sachin”121,“sachin@sachin.com”,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#sc1.display_allinfo()
#sc2.myschool_info()
#st1.student_info()
t1 = Teacher(“Kapil Dev”49,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#t1.teacher_info()
t1.myschool_info()
t1.dummy()

# Encapsulation: data hiding
## 3 levels of access:
## 1. Public access – methods can be called by subclass and also by the 
###    main program- anybody can call anytime
## 2. Private access – nobody can call (neither subclass nor the main program)
####  private will have __before variable/methods name
## 3. Protected access – (only subclass can call but not main program) THIS IS NOT
###  STRICTLY IMPLEMENTED IN PYTHON
####  protected variables/methods will have _ before its name

#inheritance in class
class City:
    def __dummy(self):  #made it private (__ double underscore added)
        print(“Dummy method of City class”)
class School:
    school_info = {}
    def __init__(self,sname,city,website):
        self.sname = sname
        self.website = website
        self.city = city
        print(f“School object {self.sname} is created”)
        t_dict = {sname:[city,website]}
        School.school_info.update(t_dict)
    def myschool_info(self):
        print(“Displaying all the information of My School:”)
        print(“School Name: “,self.sname)
        print(”      City : “,self.city)
        print(”    Website: “,self.website)
    def dummy(self):
        print(“This is a dummy method in School class”)
    @classmethod
    def display_allinfo(cls):
        print(“Displaying all the information of Schools:”)
        for i,j in cls.school_info.items():
            print(i,” : “,j)

class Student(SchoolCity):
    def __init__(self,name,rollno,emailid,sname,city,website):
        School.__init__(self,sname,city,website)
        self.name = name
        self.rollno = rollno
        self.emailid = emailid
        print(f“Student with name {self.name} is created”)

    def student_info(self):
        print(”    NAME: “,self.name)
        print(” ROLL NO: “,self.rollno)
        print(“EMAIL ID: “,self.emailid)
    def dummy(self):
        print(“This is a dummy method in Student class”)
class Teacher(CitySchool):
    def __init__(self,name,age,sname,city,website):
        School.__init__(self,sname,city,website)
        self.name = name
        self.age = age
        print(f“Teacher with name {self.name} is created”)
    def teacher_info(self):
        print(“NAME: “,self.name)
        print(” AGE: “,self.age)
    def dummy123(self):
        print(“This is a dummy method in Teacher class”)
        #City.__dummy()# private is not callable

sc1 = School(“ABC School”“Vizag”,“www.abcschool.org”)
sc2 = School(“DEF International School”“Delhi”,“www.defschool.org”)
st1 = Student(“Sachin”121,“sachin@sachin.com”,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#sc1.display_allinfo()
#sc2.myschool_info()
#st1.student_info()
t1 = Teacher(“Kapil Dev”49,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#t1.teacher_info()
t1.myschool_info()
t1.dummy123()

## Demonstration of Protected members

#inheritance in class
class City:
    def _dummy(self):  #made it protected (_ single underscore added)
        print(“Dummy method of City class”)
class School:
    school_info = {}
    def __init__(self,sname,city,website):
        self.sname = sname
        self.website = website
        self.city = city
        print(f“School object {self.sname} is created”)
        t_dict = {sname:[city,website]}
        School.school_info.update(t_dict)
    def myschool_info(self):
        print(“Displaying all the information of My School:”)
        print(“School Name: “,self.sname)
        print(”      City : “,self.city)
        print(”    Website: “,self.website)
    def dummy(self):
        print(“This is a dummy method in School class”)
    @classmethod
    def display_allinfo(cls):
        print(“Displaying all the information of Schools:”)
        for i,j in cls.school_info.items():
            print(i,” : “,j)

class Student(SchoolCity):
    def __init__(self,name,rollno,emailid,sname,city,website):
        School.__init__(self,sname,city,website)
        self.name = name
        self.rollno = rollno
        self.emailid = emailid
        print(f“Student with name {self.name} is created”)

    def student_info(self):
        print(”    NAME: “,self.name)
        print(” ROLL NO: “,self.rollno)
        print(“EMAIL ID: “,self.emailid)
    def dummy(self):
        print(“This is a dummy method in Student class”)
class Teacher(CitySchool):
    def __init__(self,name,age,sname,city,website):
        School.__init__(self,sname,city,website)
        self.name = name
        self.age = age
        print(f“Teacher with name {self.name} is created”)
    def teacher_info(self):
        print(“NAME: “,self.name)
        print(” AGE: “,self.age)
    def dummy123(self):
        print(“This is a dummy method in Teacher class”)
        #City.__dummy()# private is not callable

sc1 = School(“ABC School”“Vizag”,“www.abcschool.org”)
sc2 = School(“DEF International School”“Delhi”,“www.defschool.org”)
st1 = Student(“Sachin”121,“sachin@sachin.com”,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#sc1.display_allinfo()
#sc2.myschool_info()
#st1.student_info()
t1 = Teacher(“Kapil Dev”49,“Mumbai International”,“Mumbai”,“mumintschool.org”)
#t1.teacher_info()
t1.myschool_info()
t1.dummy123()
t1._dummy()  ## this is protected meaning – doesnt appear when you call
# but doesnt throw error when you call it

class Shape:
    def area(self):
        print(“Area of this shape is not possible”)
    def perimeter(self):
        print(“Perimeter of this shape is not possible”)
    def circumference(self):
        print(“Circumference of this shape is not possible”)
import math
class Rectangle(Shape):
    def __init__(self,l,b):
        self.l = l
        self.b = b
    def area(self):
        print(“Area is “,self.l * self.b)
    def perimeter(self):
        print(“Perimeter is “,2 * (self.l + self.b))
class Circle(Shape):
    def __init__(self,r):
        self.r = r
    def area(self):
        print(“Area is “,math.pi *self.r ** 2)
    def circumference(self):
        print(“Perimeter is “,2 * self.r *math.pi)

r1 = Rectangle(6,9)
r1.circumference()
r1.area()
c1 = Circle(5)
c1.perimeter()
c1.area()

DAY  17:  SEPTEMBER  5, 2022

 

import turtle

#setting up screen
screen = turtle.Screen()
screen.bgcolor("light green")
screen.title("Turtle Program: September 2, 2022")

#create my pen
pen =turtle.Turtle()

for i in range(5,21,3): # 0 - start (inclusive), 4 is the end (exclusive), increment
# range: 5, 8, 11,14
pen.forward(100) #moving -drawing
pen.right(60) #degree

#pen.left(90)
pen.hideturtle() #make turtle invisible
pen.penup()
pen.goto(100,100)
pen.pendown()
for i in range(5,20,3): # 0 - start (inclusive), 4 is the end (exclusive), increment
# range: 5, 8, 11,14

pen.forward(180) #moving -drawing
pen.right(144) # degree

pen.hideturtle() #make turtle invisible
pen.left(90)
pen.penup()
pen.goto(250,250)
pen.pendown()
#done
col = ["red","blue","orange","yellow","purple","green","indigo"]
for i in range(1,3,1):
pen.circle(5*i)
pen.circle(-5*i)
pen.pencolor(col[i%7])

pen.penup()
pen.goto(-300,0)
pen.pendown()

import random
for i in range(10):
val = random.randint(50,200)
pen.forward(val) # moving -drawing
angle = random.randint(20,180)
pen.right(angle)

ts = pen.getscreen()
ts.getcanvas().postscript(file="mydrawing.eps")
turtle.done()

 

DAY  18:  SEPTEMBER 29, 2022

 

DAY  19:  SEPTEMBER  , 2022

DAY  20:  SEPTEMBER 2, 2022