python basic program – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 13:24:24 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 python basic program – Java2Blog https://java2blog.com 32 32 Reverse array in Python https://java2blog.com/reverse-array-python/?utm_source=rss&utm_medium=rss&utm_campaign=reverse-array-python https://java2blog.com/reverse-array-python/#respond Tue, 29 Dec 2020 07:11:31 +0000 https://java2blog.com/?p=10982 In this post, we will see a different ways to reverse array in Python.
Let’s see the example first.
Example:

Input  : [10 20 30 40 50 60]
Output : [60 50 40 30 20 10]

As we know, Python language has not come up with an array data structure. So in python there are some ways to create an array like data structure. Some ways like: use list, use array module and use numpy module for array.

Using list

Now first, we will see different ways to reverse a list in Python.

You can use the list as array in python and perform various operations on the list to reverse it.

Using a concept of list slicing.

Here, we are using concept of Python list slicing to reverse a list. List slicing performs in-place reversal , so no extra space is required.

Below is the Python code given:

# list
arr = [10, 20, 30, 40, 50, 60]
print("Original array is:", arr)

# reverse the list using list slicing
rev_arr = arr[: : -1]
print("Reversed array is:", rev_arr)

Output:

Original array is: [10, 20, 30, 40, 50, 60]
Reversed array is: [60, 50, 40, 30, 20, 10]

Using a reverse() method of list.

Here, we are using reverse() method of list to reverse a list. reverse() method performs in-place reversal , so no extra space is required.

Below is the Python code given:

# list
arr = [10, 20, 30, 40, 50, 60]
print("Original array is:", arr)

# reverse the list using reverse() method
arr.reverse()

print("Reversed array is:", arr)

Output:

Original array is: [10, 20, 30, 40, 50, 60]
Reversed array is: [60, 50, 40, 30, 20, 10]

Using a reversed() built-in function.

Here, we are using reversed() function to reverse a list. This function returns reversed iterator object , so we convert it into list by using list() function.

Below is the Python code given:

# list
arr = [10, 20, 30, 40, 50, 60]
print("Original array is:", arr)

# reverse the list using reversed() function
rev_arr = list(reversed(arr))

print("Reversed array is:", rev_arr)

Output:

Original array is: [10, 20, 30, 40, 50, 60]
Reversed array is: [60, 50, 40, 30, 20, 10]

Using array modile

Now, we will see different ways to reverse an array using array module in Python.

Using a reverse() method of array object.

Here, we are using reverse() method of list to reverse an array. reversed() method performs in-place reversal , so no extra space is required.

Below is the Python code given:

# import array module
import array

# integer array
arr = array.array('i',[10, 20, 30, 40, 50, 60])

print("Original array is:", arr)

# reverse an array using reverse() method
arr.reverse()

print("Reversed array is:", arr)

Output:

Original array is: array('i', [10, 20, 30, 40, 50, 60])
Reversed array is: array('i', [60, 50, 40, 30, 20, 10])

Using a reversed() built-in function.

Here, we are using reversed() function to reverse an array. This function returns reversed iterator object ,so we convert it into array by using array.array() function.

Below is the Python code given:

# import array module
import array

# integer array
arr = array.array('i', [10, 20, 30, 40, 50, 60])

print("Original array is:", arr)

# reverse an array using reversed() function
rev_arr = array.array('i', reversed(arr))

print("Reversed array is:", rev_arr)

Output:

Original array is: array('i', [10, 20, 30, 40, 50, 60])
Reversed array is: array('i', [60, 50, 40, 30, 20, 10])

Using numpy array

Now, we will see a different ways to reverse a numpy array in Python.

Using a flip() method of numpy module.

Here, we are using flip() method of numpy to reverse a numpy array. `flip() method returns numpy array object.

Below is the Python code given:

# import numpy module
import numpy as np

# numpy array
arr = np.array([10, 20, 30, 40, 50, 60])

print("Original array is:", arr)

# reverse an array using flip() method
# 0 denotes horizonatl axis
rev_arr = np.flip(arr, 0)

print("Reversed array is:", rev_arr)

Output:

Original array is: [10 20 30 40 50 60]
Reversed array is: [60 50 40 30 20 10]

Using a concept of array slicing.

Here, we are using concept of slicing to reverse a numpy array. slicing performs in-place reversal , so no extra space is required.

Below is the Python code given:

# import numpy module
import numpy as np

# numpy array
arr = np.array([10, 20, 30, 40, 50, 60])

print("Original array is:", arr)

# reverse an array using slicing
rev_arr = arr[: : -1]

print("Reversed array is:", rev_arr)

Output:

Original array is: [10 20 30 40 50 60]
Reversed array is: [60 50 40 30 20 10]

Using a flipud() method of numpy module.

Here, we are using flipud() method of numpy to reverse a numpy array. flipud method returns numpy array object.

Below is the Python code given:

# import numpy module
import numpy as np

# numpy array
arr = np.array([10, 20, 30, 40, 50, 60])

print("Original array is:", arr)

# reverse an array using slicing
rev_arr = np.flipud(arr)

print("Reversed array is:", rev_arr)

Output:

Original array is: [10 20 30 40 50 60]
Reversed array is: [60 50 40 30 20 10]

Print array in reverse order

You can loop through the array in reverse order. Loop will start from array.lenght -1 and end at 0 by step value of 1.

#Initialize array     
arrInt = [1, 2, 3, 4, 5];     
print("Original array: ");    
for i in range(0, len(arrInt)):    
    print(arrInt[i],end=' '),     
print("\nArray in reverse order: ");    
# Print array in reverse order
for i in range(len(arrInt)-1, -1, -1):     
    print(arrInt[i],end=' ')

Output:

Original array: 
1 2 3 4 5 
Array in reverse order: 
5 4 3 2 1

That’s all about how to reverse array in Python.

]]>
https://java2blog.com/reverse-array-python/feed/ 0
Matrix multiplication in Python using user input https://java2blog.com/matrix-multiplication-in-python-using-user-input/?utm_source=rss&utm_medium=rss&utm_campaign=matrix-multiplication-in-python-using-user-input https://java2blog.com/matrix-multiplication-in-python-using-user-input/#respond Sun, 20 Dec 2020 18:35:09 +0000 https://java2blog.com/?p=10976 In this post, we will see a how to take matrix input from the user and perform matrix multiplication in Python.
Let’s see the example first.
Example:

Input  : matrix1 = [[1, 2],
                    [2, 3]]

         matrix2 = [[1, 2],
                    [2, 3]]
Output : [5, 8]
         [8, 13]

Now, let’s see the different ways to do this task:

Using Nested loops(for / while).

In this method, we have to iterate through each row and each column items that’s why we use nested loops here.
Below is the Python code given:

print("Enter order of 1st matrix:")

# take integer inputs in one line
m,n = list(map(int,input().split()))

print("Enter Row wise values")

# empty list for 1st matrix
mat1 = []

# row wise insertion in the matrix
for i in range(m) :
    print("Enter row",i,"value:")

    # take 1d- integer array input in one line
    row = list(map(int,input().split()))
    mat1.append(row)

print("Enter order of 2nd matrix:")

# take integer inputs in one line
p,q = list(map(int,input().split()))

print("Enter Row wise values")

# empty list for 2nd matrix
mat2 = []

# row wise insertion in the matrix
for j in range(p) :
    print("Enter row",j,"value:")

    # take 1d- integer array input in one line
    row = list(map(int,input().split()))
    mat2.append(row)

# showing 1st and 2nd matrix
print("Matrix 1:",mat1)
print("Matrix 2:",mat2)

# empty list for resulatant matrix
resultant = []

# create a 0-matrix of order m x q
for i in range(m):
    row = []
    for j in range(q):
        row.append(0)

    resultant.append(row)

print("Matrix Multiplication: ")

# perform matrix multiplication
# using nested for loops
for i in range(m):
    for j in range(q):
        for k in range(n) :
            resultant[i][j] += mat1[i][k] * mat2[k][j]

# matrix printing row wise            
for row in resultant:
    print(row)

Output:

Enter order of 1st matrix:
2 2
Enter Row wise values
Enter row 0 value:
1 2
Enter row 1 value:
2 3
Enter order of 2nd matrix:
2 2
Enter Row wise values
Enter row 0 value:
1 2
Enter row 1 value:
2 3
Matrix 1: [[1, 2], [2, 3]]
Matrix 2: [[1, 2], [2, 3]]
Matrix Multiplication: 
[5, 8]
[8, 13]

Using dot() method of numpy library.

In this method, dot() method of numpy is used. dot() method is used to find out the dot product of two matrices. dot product is nothing but a simple matrix multiplication in Python using numpy library. We have to pass two matrices in this method for which we have required dot product.

Below is the Python code given:

# import numpy library
import numpy 

print("Enter order of 1st matrix:")
m,n = list(map(int,input().split()))

print("Enter Row wise values")
mat1 = []

# row wise insertion in the matrix
for i in range(m) :
    print("Enter row",i,"value:")
    row = list(map(int,input().split()))
    mat1.append(row)

print("Enter order of 2nd matrix:")
p,q = list(map(int,input().split()))

print("Enter Row wise values")
mat2 = []

# row wise insertion in the matrix
for j in range(p) :
    print("Enter row",j,"value:")
    row = list(map(int,input().split()))
    mat2.append(row)

print("Matrix 1:",mat1)
print("Matrix 2:",mat2)

print("Matrix Multiplication: ")

# perform matrix multiplication using 
# dot method of numpy library
resultant = numpy.dot(mat1,mat2)

# matrix printing row wise 
for row in resultant:
    print(row)

Output:

Enter order of 1st matrix:
2 2
Enter Row wise values
Enter row 0 value:
1 2
Enter row 1 value:
2 3
Enter order of 2nd matrix:
2 2
Enter Row wise values
Enter row 0 value:
1 2
Enter row 1 value:
2 3
Matrix 1: [[1, 2], [2, 3]]
Matrix 2: [[1, 2], [2, 3]]
Matrix Multiplication: 
[5, 8]
[8, 13]

Using list-comprehension and zip() function.

In this method, zip() function is used to combine list and generated zip object which is the object of list of tuples and list-comprehension is used for creating list and perform operation in one-line code.

Below is the Python code given:

print("Enter order of 1st matrix:")
m,n = list(map(int,input().split()))

print("Enter Row wise values")
mat1 = []

# row wise insertion in the matrix
for i in range(m) :
    print("Enter row",i,"value:")
    row = list(map(int,input().split()))
    mat1.append(row)

print("Enter order of 2nd matrix:")
p,q = list(map(int,input().split()))

print("Enter Row wise values")
mat2 = []

# row wise insertion in the matrix
for j in range(p) :
    print("Enter row",j,"value:")
    row = list(map(int,input().split()))
    mat2.append(row)

print("Matrix 1:",mat1)
print("Matrix 2:",mat2)

print("Matrix Multiplication: ")

# perfrom matrix multiplication using 
# list comprehension
resultant = [[ sum(ele1*ele2 for ele1,ele2 in zip(row,col))
              for col in zip(*mat2) ]
                                    for row in mat1 ]
# matrix printing row wise 
for row in resultant:
    print(row)

Output:

Enter order of 1st matrix:
2 2
Enter Row wise values
Enter row 0 value:
1 2
Enter row 1 value:
3 4
Enter order of 2nd matrix:
2 2
Enter Row wise values
Enter row 0 value:
5 6
Enter row 1 value:
7 8
Matrix 1: [[1, 2], [3, 4]]
Matrix 2: [[5, 6], [7, 8]]
Matrix Multiplication: 
[19, 22]
[43, 50]

That’s all about Matrix multiplication in Python using user input.

]]>
https://java2blog.com/matrix-multiplication-in-python-using-user-input/feed/ 0
Remove All Instances of Element from List in Python https://java2blog.com/remove-all-instances-element-from-list-python/?utm_source=rss&utm_medium=rss&utm_campaign=remove-all-instances-element-from-list-python https://java2blog.com/remove-all-instances-element-from-list-python/#respond Tue, 27 Oct 2020 18:48:32 +0000 https://java2blog.com/?p=10932 In this article, we will see different ways to remove all occurrences or instances of a given element from the list in Python.

Let’s see the example:
Example:

Input  : ["java", "Python", "R", "Scala", "java"]
element: "java"
Output : ["Python", "R", "Scala"]

Input  : ["java", "c", "ruby", "java", "java","java script"]
element: "java"
Output : ["c", "ruby", "java script"]

Now, let’s see different methods:

Using remove() method of list with for loop

remove() method is used to remove the 1st occurrence of given element from the list. So here we are looping through the list, and whenever we find the given element, then we will remove that element from the list using remove() method.
Here is Python code:

# input list
items = ["java", "Python", "R", "Scala", "java"]

# input element
element = "java"

# loop through all element
for item in items :

    # if element is found 
    # then remove
    if item == element:
        items.remove(item)

# print result  
print(items)

Output:

['Python', 'R', 'Scala']

Using pop() method of list

pop() method is used to remove the 1st occurrence of given index element from the list. So here we are looping through the list, and whenever we find the given element, then we will remove that element from the list using pop() method by passing its corresponding index.

Here is Python code:

# input list
items = ["java", "Python", "R", "Scala", "java"]

# input element
element = "java"

# loop through all element
for i in range(len(items)) :

    # if element is found 
    # then pop out
    if items[i] == element:
        items.pop(i)

# print result
print(items)

Output:

['Python', 'R', 'Scala']

Using list-comprehension

Here, we are creating a new list by adding elements that are not matching with the given element using list-comprehension.
This is recommended solution to use, and here we are creating a sublist that satisfies certain conditions. In this scenario, if item is not matching with the given element

Here is Python code:

# input list
items = ["java", "Python", "R", "Scala", "java"]

# input element
element = "java"

# list comprehension
items = [item for item in items if item != element]

# print result
print(items)

Output:

['Python', 'R', 'Scala']

Using filter()

We can also use inbuilt filter(function,iterable) method which can return an itertor from elements of the list for which function returns true.
Here is Python code:

# input list
items = ["java", "Python", "R", "Scala", "java"]

# input element
element = "java"

# list comprehension
items = list(filter(lambda item: item != element, items))

# print result
print(items)

Using remove() method of list with while loop

We can also use remove() method with while loop rather than for loop as seen in first approach.

We will iterate the elements using while loop and when we find the element in the list, we will remove it.
Here is Python code:

# input list
items = ["java", "Python", "R", "Scala", "java"]

# input element
element = "java"

# while loop through all element
while element in items: items.remove(element)

# print result  
print(items)

Output:

['Python', 'R', 'Scala']

That’s all about how to remove all occurrences or instances of a given element from the list in Python.

]]>
https://java2blog.com/remove-all-instances-element-from-list-python/feed/ 0