Monday 4 March 2019

Counter in Python

What is counter?
Counter is a container included in the collections module.

What is container?
Containers are objects that hold objects. They provide a way to access the contained objects and iterate over them. Examples of built in containers are Tuple, list and dictionary. Others are included in Collections module.
A Counter is a subclass of dict. Therefore it is an unordered collection where elements and their respective count are stored as dictionary. This is equivalent to bag or multiset of other languages.

Syntax:
class collections.Counter([iterable-or-mapping])
initialization
The constructor of counter can be called in any one of the following ways :
1.With sequence of items
2.With dictionary containing keys and counts
3.With keyword arguments mapping string names to counts
Example of each type of initialization :
# A Python program to show different ways to create
# Counter
from collections import Counter
# With sequence of items
print Counter(['B','B','A','B','C','A','B','B','A','C'])
# with dictionary
print Counter({'A':3, 'B':5, 'C':2})
# with keyword arguments
print Counter(A=3, B=5, C=2)
Output of all the three lines is same :
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})

Updation:
We can also create an empty counter in the following manner :
coun = collections.Counter()
And can be updated via update() method .Syntax for the same :
coun.update(Data)
# A Python program to demonstrate update()
from collections import Counter
coun = Counter()
coun.update([1, 2, 3, 1, 2, 1, 1, 2])
print(coun)
coun.update([1, 2, 4])
print(coun)

Output:
Counter({1: 4, 2: 3, 3: 1})
Counter({1: 5, 2: 4, 3: 1, 4: 1})

Function use in Python

Function Calls

A callable object is an object that can accept some arguments (also called parameters) and possibly return an object (often a tuple containing multiple objects). A function is the simplest callable object in Python, but there are others, such as classes or certain class instances.

Defining Functions

A function is defined in Python by the following format:
def functionname(arg1, arg2, ...):
statement1
statement2
def functionname(arg1,arg2):
return arg1+arg2
t = functionname(24,24) # Result: 48
If a function takes no arguments, it must still include the parentheses, but without anything in them:
def functionname():
statement1
statement2


The arguments in the function definition bind the arguments passed at function invocation (i.e. when the function is called), which are called actual parameters, to the names given when the function is defined, which are called formal parameters. The interior of the function has no knowledge of the names given to the actual parameters; the names of the actual parameters may not even be accessible (they could be inside another function).

A function can 'return' a value, for example:
def square(x):
return x*x

A function can define variables within the function body, which are considered 'local' to the function. The locals together with the arguments comprise all the variables within the scope of the function. Any names within the function are unbound when the function returns or reaches the end of the function body. You can return multiple values as follows:

def first2items(list1):
return list1[0], list1[1]
a, b = first2items(["Hello", "world", "hi", "universe"])
print a + " " + b

 Declaring Arguments

When calling a function that takes some values for further processing, we need to send some values as Function Arguments. For example:
def find_max(a,b):
if(a > b):
print str(a) + " is greater than " + str(b)
elif(b > a):
print str(b) + " is greater than " + str(a)
find_max(30, 45) #Here (30, 45) are the arguments passing for finding max between this two numbers
The ouput will be: 45 is greater than 30

Default Argument Values
If any of the formal parameters in the function definition are declared with the format "arg = value," then you will have the option of not specifying a value for those arguments when calling the function. If you do not specify a value, then that parameter will have the default value given when the function executes.
def display_message(message, truncate_after=4):
print message[:truncate_after]
display_message("message")
mess
display_message("message", 6)
message

Variable-Length Argument Lists

Python allows you to declare two special arguments which allow you to create arbitrary-length argument lists. This means that each time you call the function, you can specify any number of arguments above a certain number.
def function(first,second,*remaining):
statement1
statement2

When calling the above function, you must provide value for each of the first two arguments. However, since the third parameter is marked with an asterisk, any actual parameters after the first two will be packed into a tuple and bound to "remaining."
def print_tail(first,*tail):
print tail
print_tail(1, 5, 2, "omega")
(5, 2, 'omega')

If we declare a formal parameter prefixed with two asterisks, then it will be bound to a dictionary containing any keyword arguments in the actual parameters which do not correspond to any formal parameters. For example, consider the function:
def make_dictionary(max_length=10, **entries):
return dict([(key, entries[key]) for i, key in enumerate(entries.keys()) if i < max_length])

If we call this function with any keyword arguments other than max_length, they will be placed in the dictionary "entries." If we include the keyword argument of max_length, it will be bound to the formal parameter max_length, as usual.
make_dictionary(max_length=2, key1=5, key2=7, key3=9)
{'key3': 9, 'key2': 7}

By Value and by Reference
Objects passed as arguments to functions are passed by reference; they are not being copied around. Thus, passing a large list as an argument does not involve copying all its members to a new location in memory. Note that even integers are objects. However, the distinction of by value and by reference present in some other programming languages often serves to distinguish whether the passed arguments can be actually changed by the called function and whether the calling function can see the changes.
Passed objects of mutable types such as lists and dictionaries can be changed by the called function and the changes are visible to the calling function. Passed objects of immutable types such as integers and strings cannot be changed by the called function; the calling function can be certain that the called function will not change them. For mutability, see also Data Types chapter.
def appendItem(ilist, item):
ilist.append(item) # Modifies ilist in a way visible to the caller
def replaceItems(ilist, newcontentlist):
del ilist[:] # Modification visible to the caller
ilist.extend(newcontentlist) # Modification visible to the caller ilist = [5, 6] # No outside effect; lets the local ilist point to a new list object, # losing the reference to the list object passed as an argument
def clearSet(iset):
iset.clear()
def tryToTouchAnInteger(iint):
iint += 1 # No outside effect; lets the local iint to point to a new int object,
# losing the reference to the int object passed as an argument
print "iint inside:",iint # 4 if iint was 3 on function entry
list1 = [1, 2]
appendItem(list1, 3)
print list1 # [1, 2, 3]
replaceItems(list1, [3, 4])
print list1 # [3, 4]
set1 = set([1, 2])
clearSet(set1 )
print set1 # set([])
int1 = 3
tryToTouchAnInteger(int1)
print int1 # 3
Calling Functions
A function can be called by appending the arguments in parentheses to the function name, or an empty matched set of parentheses if the function takes no arguments.
foo()
square(3)
bar(5, x)
A function's return value can be used by assigning it to a variable, like so:
x = foo()
y = bar(5,x)
As shown above, when calling a function you can specify the parameters by name and you can do so in any order
def display_message(message, start=0, end=4):
print message[start:end]
display_message("message", end=3)
This above is valid and start will have the default value of 0. A restriction placed on this is after the first named argument then all arguments after it must also be named. The following is not valid
display_message(end=5, start=1, "my message")
because the third argument ("my message") is an unnamed argument.

Sunday 3 March 2019

Find the Hash of File in Python

# Python rogram to find the SHA-1 message digest of a file
# import hashlib module
import hashlib
def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""
# make a hash objectv h = hashlib.sha1()
# open file for reading in binary mode
with open(filename,'rb') as file:
# loop till the end of the file
chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)
# return the hex representation of digest return h.hexdigest()
message = hash_file("track1.mp3") print(message)


Output:
633d7356947eec543c50b76a1852f92427f4dca9

Find the size of Image in Python

def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")


Output:
The resolution of the image is 280 x 280

Merge Mails in Python

# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt",'r',encoding = 'utf-8') as names_file:
# open body.txt for reading
with open("body.txt",'r',encoding = 'utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello "+name+body
# write the mails to individual files
with open(name.strip()+".txt",'w',encoding = 'utf-8') as mail_file:
mail_file.write(mail)

Count the Number of Vowel in Python

# Program to count the number of each vowel in a string
# string of vowels
vowels = 'aeiou'
# change this value for a different result
ip_str = 'Hello, have you tried our turorial section yet?'
# uncomment to take input from the user
#ip_str = input("Enter a string: ")
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)


Output:
{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}

Different Set Operations in Python

# Program to perform different set operations like in mathematics
# define three sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)


Output:
Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}

Sort Words in Python

# Program to sort alphabetically the words form a string provided by the user
# change this value for a different result
my_str = "Hello this Is an Example With cased letters"
# uncomment to take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)


Output:
The sorted words are:
Example
Hello
Is
With
an
cased
letters
this

Remove Punctuation in Python

# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hello!!!, he said ---and went."
# To take input from the user
# my_str = input("Enter a string: ")
# remove punctuation from the string
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
# display the unpunctuated string
print(no_punct)


Output:
Hello he said and went

Check String is Palindrome or not in Python

# Program to check if a string
# is palindrome or not
# change this value for a different output
my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")


Output:
It is palindrome

Multiply two Matrix in Python

# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)


Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

Transpose a Matrix in Python

# Program to transpose a matrix using nested loop
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)


Output:
[12, 4, 3]
[7, 5, 8]

Add two Matrix in Python

# Program to add two matrices using nested loop
X = [ [12,7,3],
[4 ,5,6],
[7 ,8,9] ]
Y = [ [5,8,1],
[6,7,3],
[4,5,9] ]
result = [ [0,0,0],
[0,0,0],
[0,0,0] ]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)


Output:
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

Fibonacci Sequence in Python

# Python program to display the Fibonacci sequence up to n-th term using recursive functions,
def recur_fibo(n):
"""Recursive function to print Fibonacci sequence""" if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# Change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):

Output:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

Display Calendar in Python

# Python program to display calendar of given month of the year
# import module
import calendar
yy = 2014
mm = 11
# To ask month and year from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))


Output:
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

Shuffle Deck of Cards in Python

# Python program to shuffle a deck of card using the module random and draw 5 cards
# import modules
import itertools, random
# make a deck of cards
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))
# shuffle the cards
random.shuffle(deck)
# draw five cards
print("You got:")
for i in range(5):
print(deck[i][0], "of", deck[i][1])


Output:
You got:
5 of Heart
1 of Heart
8 of Spade
12 of Spade
4 of Spade

Make a Simple Calculator in Python

''' Program make a simple calculator that can add, subtract, multiply and divide using functions '''
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
## This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

Output:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210

Find Factors of Numbers in Python

# Python Program to find the factors of a number
# define a function
def print_factors(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
# change this value for a different result.
num = 320
# uncomment the following line to take input from the user
#num = int(input("Enter a number: "))
print_factors(num)


Output:
The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320

Find LCM in Python

# Python Program to find the L.C.M. of two input number # define a function def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# change the values of num1 and num2 for a different result
num1 = 54
num2 = 24
# uncomment the following lines to take input from the user
#num1 = int(input("Enter first number: "))
#num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))


Output:
The L.C.M. of 54 and 24 is 216

Find HCF to GCD in Python

# Python program to find the H.C.F of two input number
# define a function
def computeHCF(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = 54
num2 = 24
# take input from the user
# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))

Output:
The H.C.F. of 54 and 24 is 6

ASCII value of character in Python

#Program to find the ASCII value of the given character
# Change this value for a different result
c = 'p' # Uncomment to take character from user
#c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))


Output:
The ASCII value of 'p' is 112

Decimal to Binary in Python

#Python program to convert decimal number into binary, octal and hexadecimal number system
# Change this line for a different result
dec = 344
print("The decimal value of",dec,"is:")
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")
Output:
The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

Saturday 2 March 2019

Number Divisible by Number in Python

#Python Program to find numbers divisible by thirteen from a list using anonymous function
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
Output:
Numbers divisible by 13 are[65,39,221]

Display Power of 2 in Python

# Python Program to display the powers of 2 using anonymous function
# Change this value for a different result
terms = 10
# Uncomment to take number of terms from user
#terms = int(input("How many terms? "))
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
# display the result
print("The total terms is:",terms)
for i in range(terms):
print("2 raised to power",i,"is",result[i])
Output:
The total terms is: 10
2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512

Sum of Natural Number in Python

# Python program to find the sum of natural numbers up to n where n is provided by user
# change this value for a different result
num = 16
# uncomment to take input from the user
#num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
Output:
The sum is 136

Check Armstrong Number in Python

#Python program to check if the number provided by the user is an Armstrong number or not
# take input from the user
# num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:

digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Output 1:

Enter a number:663
663 is not an Armstrong number

Output 2:

Enter a number:407
407 is an Armstrong number

Fibonacci Sequence in Python

#Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms <= 0:

print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output:

Fibonacci sequence upto 10 :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Display Multiple Table in Python

'''Python program to find the
multiplication table (from 1 to 10)'''
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1, 11):

print(num,'x',i,'=',num*i)

Output:

12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

Factorial of Number in Python

#Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = 7
# uncomment to take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:

print("Sorry, factorial does not exist for negative numbers")
elif num == 0:

print("The factorial of 0 is 1")
else:

for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Output:

The factorial of 7 is 5040

Print Prime Number in Python

#Python program to display all the prime numbers within an interval
# change the values of lower and upper for a different result
lower = 900
upper = 1000
# uncomment the following lines to take input from the user
#lower = int(input("Enter lower range: "))
#upper = int(input("Enter upper range: "))
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):

# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

Output:

Prime numbers between 900 and 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997

Check Prime Number in Python


#Python program to check if the input number is prime or not
num = 407
# take input from the user
# num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:

# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:

print(num,"is not a prime number")

Output:

407 is not a prime number
11 times 37 is 407

Check Largest Among Three Numbers

# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user #num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):

largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)

Output:

The largest number between 10, 14 and 12 is 14.0

Check Leap Year in Python

# Python program to check if the input year is a leap year or not
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
if (year % 4) == 0:

if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

Output:

2000 is a leap year

Check Number Odd or Even in Python

# Python 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 number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

Output1:

Enter a number: 43
43 is Odd

Output2:

Enter a number: 18
18 is Even

Convert Celsius To Fahrenheit in Python

# Python Program to convert temperature in celsius to fahrenheit
# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

Output:

37.5 degree Celsius is equal to 99.5 degree Fahrenheit

Convert Kilometres To Miles in Python

kilometers = 5.5
# To take kilometers from the user, uncomment the code below
kilometers = input("Enter value in kilometers")
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))

Output:

5.500 kilometers is equal to 3.418 miles

Swap Two Variables in Python

#Python program to swap two variables
# To take input from the user
# x = input('Enter value of x: ')
# y = input('Enter value of y: ')
x = 5
y = 10
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Output:

The value of x after swapping: 10
The value of y after swapping: 5

Solve Quadratic Equation in Python


#Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a = 1
b = 5
c = 6
# To take coefficient input from the users
# a = float(input('Enter a: '))
# b = float(input('Enter b: '))
# c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

Output:

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

Area of Triangle in Python


# Python Program to find the area of triangle
a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output:

The area of the triangle is 14.70

Find Square Root in Python

# Python Program to calculate the square root
# Note: change this value for a different result
num = 8
# uncomment to take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Output:

The square root of 8.000 is 2.828

Friday 1 March 2019

R packages

R packages are a collection of R functions, complied code and sample data. They are stored under a directory called "library" in the R environment. By default, R installs a set of packages during installation. More packages are added later, when they are needed for some specific purpose. When we start the R console, only the default packages are available by default. Other packages which are already installed have to be loaded explicitly to be used by the R program that is going to use them.
All the packages available in R language are listed at R Packages.
Below is a list of commands to be used to check, verify and use the R packages.

Check Available R Packages

Get library locations containing R packages
.libPaths()

When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc.
[2] "C:/Program Files/R/R-3.2.2/library"

Get the list of all the packages installed

library()
When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc.
Packages in library ‘C:/Program Files/R/R-3.2.2/library’:

base                    The R Base Package
boot                    Bootstrap Functions (Originally by Angelo Canty
                        for S)
class                   Functions for Classification
cluster                 "Finding Groups in Data": Cluster Analysis
                        Extended Rousseeuw et al.
codetools               Code Analysis Tools for R
compiler                The R Compiler Package
Get all packages currently loaded in the R environment
search()
When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc.
[1] ".GlobalEnv"        "package:stats"     "package:graphics" 
[4] "package:grDevices" "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"         "package:base" 

Install a New Package

There are two ways to add new R packages. One is installing directly from the CRAN directory and another is downloading the package to your local system and installing it manually.

INSTALL DIRECTLY FROM CRAN

The following command gets the packages directly from CRAN webpage and installs the package in the R environment. You may be prompted to choose a nearest mirror. Choose the one appropriate to your location.
 install.packages("Package Name")
 
# Install the package named "XML".
 install.packages("XML")

INSTALL PACKAGE MANUALLY

Go to the link R Packages to download the package needed. Save the package as a .zip file in a suitable location in the local system.
Now you can run the following command to install this package in the R environment.
install.packages(file_name_with_path, repos = NULL, type = "source")

# Install the package named "XML"
install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source")

Load Package to Library

Before a package can be used in the code, it must be loaded to the current R environment. You also need to load a package that is already installed previously but not available in the current environment.
A package is loaded using the following command −
library("package Name", lib.loc = "path to library")

# Load the package named "XML"
install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source")

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (89) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (741) Python Coding Challenge (192) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses