Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Monday 4 March 2019

Iterators in Python

Iterator in python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators because they implement following methods. In fact, any object that wants to be an iterator must implement following methods.

1.__iter__ method that is called on initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.
2.next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.

Below is a simple Python program that creates iterator type that iterates from 10 to given limit. For example, if limit is 15, then it prints 10 11 12 13 14 15. And if limit is 5, then it prints nothing.

# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
# An iterable user defined type
class Test:
# Cosntructor
def __init__(self, limit):
self.limit = limit
# Called when iteration is initialized
def __iter__(self):
self.x = 10
return self
# To move to next element. In Python 3,
# we should replace next with __next__
def next(self):
# Store current value of x
x = self.x
# Stop iteration if limit is reached
if x > self.limit:
raise StopIteration
# Else increment and return old value
self.x = x + 1;
return x
# Prints numbers from 10 to 15
for i in Test(15):
print(i)
# Prints nothing
for i in Test(5):
print(i)

Output:
10
11
12
13
14
15

Accessing Counters in Python

Once initialized, counters are accessed just like dictionaries. Also, it does not raise the Key Value error (if key is not present) instead the value’s count is shown as 0.

Example:
# Python program to demonstrate accessing of
# Counter elements
from collections import Counter
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
col_count = Counter(z)
print(col_count)
col = ['blue','red','yellow','green']
# Here green is not in col_count
# so count of green will be zero
for color in col:
print (color, col_count[color])

Output:
Counter({'blue': 3, 'red': 2, 'yellow': 1})
blue 3
red 2
yellow 1
green 0

elements()
The elements() method returns an iterator that produces all of the items known to the Counter. Note : Elements with count <= 0 are not included.

Example:
# Python example to demonstrate elements() on
# Counter (gives back list)
from collections import Counter
coun = Counter(a=1, b=2, c=3)
print(coun)
print(list(coun.elements()))

Output:
Counter({'c': 3, 'b': 2, 'a': 1})
['a', 'b', 'b', 'c', 'c', 'c']

most_common() :
most_common() is used to produce a sequence of the n most frequently encountered input values and their respective counts.
# Python example to demonstrate most_elements() on
# Counter
from collections import Counter
coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219)
# This prints 3 most frequent characters
for letter, count in coun.most_common(3):
print('%s: %d' % (letter, count))

Output:
f: 219
d: 120
c: 3

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

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 (191) 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