Topics covered

Python

Saturday, 4 July 2020

How To Create Integer Array Matrix In Python

This article is all about creating an integer array. There are lot of beginners who face challenges in creating array matrix when they start learning python. So keeping that in mind I have created this article. 

Since we are creating an array matrix, let me give you a brief of what exactly array is, Array is basically a collection of items of same data type. Each and every item that get stored in array is called element which are usually identified by its index.


 To create matrix, I have defined a function create_integer_matrix(rows,cols,intgr), which takes three input parameters as below:

  • Rows=Number of Rows
  • Cols=Number of Columns
  • Intgr=Integer Value

Here Rows & Cols are used to define number of rows and columns of a matrix and Intgr will define the starting number to print a sequence of numbers as per size of matrix.

for example: If my matrix is of size 3x3(Rows x Cols) and Ingr value is 1 then output will be :

                                            [1, 2, 3]
                                            [4, 5, 6]
                                            [7, 8, 9]

Below is the function:


def create_integer_matrix(rows, cols, intgr):
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(intgr)
intgr = intgr + 1
matrix.append(row)
matrix = '\n'.join(str(r) for r in matrix)
return matrix


So in the above function a list matirx=[] is declared and a nested for loop is defined which loops based on input rows and columns. The outer loop will iterate as per number of rows and inner loop for range of columns. 

After each iteration of inner loop the intgr value will get incremented by 1 and get appended to row=[] list variable, which further gets appended to matrix variable to form first row of matrix like "[1, 2, 3]"

Below is the full code:


def create_integer_matrix(rows, cols, intgr):
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(intgr)
intgr = intgr + 1
matrix.append(row)
matrix = '\n'.join(str(r) for r in matrix)
return matrix

#main function
def main():

rows=3 #Number of matrix row
cols=3 #Number of columns
intgr=1 # Start of integr series number

mtrx=create_integer_matrix(rows,cols,intgr)
print(mtrx)

if __name__ == '__main__':
main()


Hope that you find it helpful.












Thursday, 2 July 2020

Python Program To Check And Print Whether Tuple Is Having Duplicate Items

In this article I will share a python code which will check for the existence of duplicate item in a tuple and print the same.

To achieve this I have defined a function name : check_duplicate_tuple()

In this function I have passed a tuple as a function parameter.  

Inside this function I have declared one list variable duplicate=[] which is used to store duplicate tuples that we will print if there is a duplicate item.

A for loop is used to iterate through each element of tuple and checked for count. If any of the element count is greater than one then that element will get appended to a list we declared.

 Function: Below is the code snippet of function which will check if tuple value is duplicate or not and return the duplicate values 

def check_duplicate_tuple(l):
#declared a list variable in which we will store duplicate values
duplicate=[]
#using this for loop we will try to check count for tuple element
# and append to list if it occurs more than one
for i in l:
if l.count(i) > 1:
#print("It has duplicate values")
duplicate.append(i)
else:
continue
return duplicate

Full Code:



def check_duplicate_tuple(l):
#declared a list variable in which we will store duplicate values
duplicate=[]
#using this for loop we will try to check count for tuple element
# and append to list if it occurs more than one
for i in l:
if l.count(i) > 1:
#print("It has duplicate values")
duplicate.append(i)
else:
continue
return duplicate

def main():

tup1 = (2,3,5,4,4,2,6,6, 11.56)

#calling function to check duplicate tuple
duplicate=check_duplicate_tuple(tup1)
print("duplicate tuple values are "+ str(list(set(duplicate))))


if __name__ == '__main__':
main()

Hope the above information and code will be helpful. 

Wednesday, 1 July 2020

Python Function To Check If A Key Exists In Dictionary

There are multiple ways to see if key exists in Python dictionary or not, like using keys(), has_key(), get(), Try and Except.

To me Try and Except is a best and more efficient way in python to check if a key exists in dictionary because it provides an appropriate way of handling unexpected errors without interrupting the code flow.

Now I'm sharing a code snippet showing the way to use Try and Except block to check a key in Python dictionary.

In this code, I have created one function "key_check" which basically accepts a dictionary and a key where we will check the existence of a key in that dictionary.

If the key is present in the dictionary this function will return true else false.

For example: for Key='Name'. This function will return true and print 'Name' exists. 

def key_check(mydict, key):
#Python function to check if key in dictionary already exists
try:
mydict[key]
return True
except KeyError:
return False

def main():

#createing a dictionary
mydict = {
"Name": "Python",
"Hello": "World",
"Version": 3
}

# key to check
key = 'Name'

print('calling key check function in if block')

if key_check(mydict, key):
print("'%s' exists"%key)
else:
print("'%s' does not exists"%key)

if __name__ == '__main__':
main()


I hope that you find this helpful.