Python

Python Numpy: flatten() vs ravel() | Difference between the ravel numpy and flatten numpy functions

In this tutorial, python beginners and experts can easily learn about the difference between numpy ravel and flatten functions. The main aim of both numpy.ravel() and numpy.flatten() functions are the same i.e. to flatten a numpy array of any shape. Before learning about flatten ravel differences, let’s take a look at the basic overview of both the numpy functions from here.

numpy.ravel()

ravel() is a built-in function in the module of numpy that returns a view of the original array and also returns a flattened 1D view of the numpy array object. Moreover, it accepts an array-like element as a parameter.

Syntax of the ravel() function in numpy:

numpy.ravel(a, order='C')

numpy.ndarray.flatten()

Flatten always returns a copy. The function of the flatten() is a faster member function of the numpy array where it returns a flattened 1D copy of the numpy array object.

Syntax of Numpy flatten() function:

ndarray.flatten(order='C')

Let’s discuss some of the differences between the numpy ravel & flatten function:

Differences between ravel() & flatten()

First of all, import the numpy module,

import numpy as np

A quick view about the difference between flatten and ravel functions in numpy is furnished below:

a.flatten()

(i) Return copy of the original array

(ii) If you modify any value of this array value of the original array is not affected.

(iii) Flatten() is comparatively slower than ravel() as it occupies memory.

(iv) Flatten is a method of a ndarray object.

a.ravel()

(i) Return only reference/view of original array

(ii) If you modify the array you would notice that the value of the original array also changes.

(iii) Ravel is faster than flatten() as it does not occupy any memory.

(iv) Ravel is a library-level function.

For in-depth knowledge on the difference between flatten and ravel numpy functions, kindly check out the further sections without any fail.

Difference 1: Performance: Copy vs view

Thenumpy.ndarray.flatten()function returns a flatten copy of numpy array object only, whereas numpy.ravel() returns a flattened view of the input array if possible.

Difference Between flatten and ravel numpy

import numpy as sc
# Creation of 2D Numpy array
arr_twoD = sc.array([[10, 20, 30],
                [40, 50, 60],
                [70, 85, 90]])
print('2D array')                
print(arr_twoD)
# Convert the 2D array to flattened 1d view
flatn_arr = arr_twoD.flatten()
print('Flattened 1D view')
flatn_arr[1] = 55
print(flatn_arr)
print(arr_twoD)
Output :
2D array
[[10 20 30]
 [40 50 60]
 [70 85 90]]
Flattened 1D view
[10 55 30 40 50 60 70 85 90]
[[10 20 30]
 [40 50 60]
 [70 85 90]]

Here we can successfully change 2nd element of the numpy array that is reflected in the 1D numpy array. But the original 2D array is unaffected which denotes that flatten() returns a copy of the input array.

Let’s try using numpy.ravel() to convert 2D numpy array to 1D array

ravel() returns a flattened view of the numpy array object if possible. When there is any change done in the view object it will also get reflected in the original numpy array.

convert 2D numpy array to 1D array using numpy.ravel()

import numpy as sc
# Creation of 2D Numpy array
arr_twoD = sc.array([[10, 20, 30],
                [40, 50, 60],
                [70, 85, 90]])
print('2D array')                
print(arr_twoD)
# Convert the 2D array to flattened 1d view
flatn_arr = sc.ravel(arr_twoD)
flatn_arr[1] = 55
print('Flattened 1D view:')
print(flatn_arr)
print(arr_twoD)
Output :
2D array
[[10 20 30]
 [40 50 60]
 [70 85 90]]
Flattened 1D view:
[10 55 30 40 50 60 70 85 90]
[[10 55 30]
 [40 50 60]
 [70 85 90]]

We can check of the ravel()function returns a view object or not by using the base attribute of the returned object. If it is None then it returns to the original numpy array i.e. it returns a flattened array which is a view only.

using numpy.ravel() to convert 2D numpy array to 1D array

import numpy as sc
# Creation of 2D Numpy array
arr_twoD = sc.array([[10, 20, 30],
                [40, 50, 60],
                [70, 85, 90]])
print('Original 2D array')                
print(arr_twoD)
# Convert the 2D array to flattened 1d view
flatn_arr = sc.ravel(arr_twoD)
if flatn_arr.base is not None:
    # Change the 2nd element of flat array
    flatn_arr[1] = 55
    # Modification will be reflected in 2D numpy array and flattened array
    print('Flattened 1D view:')
    print(flatn_arr)
    print(arr_twoD)
Output :
Original 2D array
[[10 20 30]
 [40 50 60]
 [70 85 90]]
Flattened 1D view:
[10 55 30 40 50 60 70 85 90]
[[10 55 30]
 [40 50 60]
 [70 85 90]]

So ravel() returns a view of the input array and hence here the performance of ravel() is better than flatten().

Difference 2: Compatibility with other array-like sequences (list etc)

The ndarray.flatten()function can be used to flatten a numpy array object only. In the case of a numpy.ravel()function being a built-in function, it accepts an array-like element, so we can even pass a list to it.

Program for Compatibility with other array like sequences

import numpy as sc
# Creation of list of lists
list_lists = [[10, 20,30],
[40, 50, 60],
[70, 85, 90]]
# Creation of flattened numpy array from list of lists
flatn_arr = sc.ravel(list_lists)
print('Flattened 1D Array:')
print(flatn_arr)
Output :
Flattened 1D Array:
[10 20 30 40 50 60 70 85 90]

While this is not feasible with ndarray.flatten() function.

Conclusion on A view of the original array using numpy ravel

Therefore, to conclude in the end there are 2 main differences between the ndarray.flatten() and numpy.ravel() function,

  1. ravel() function returns a view of the array if possible, where flatten() always returns a copy. Therefore the performance of ravel() is much better than flatten()
  2. ravel() function can accept other array-like elements like lists etc. Although, flatten() can work with numpy arrays only.

Python Numpy: flatten() vs ravel() | Difference between the ravel numpy and flatten numpy functions Read More »

Semicolon in Python

Semicolon in Python | How & Why Python Semicolon is Used?

Let’s have a look at how the semicolon is used in Python. In different programming languages, the semicolon(;) signifies the end or termination of the current statement.

A semicolon is required to end a line of code in programming languages such as C, C++, and Java. Python, on the other hand, is not like that. So, does using semicolons in Python programming make a difference? Let’s have a look.

All About Python Semicolon

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Why Python semicolons are allowed?

To terminate the statements, Python does not require semicolons. If you want to write a number of statements on the same line, Semicolons may be used to delimit statements.

In Python, a semicolon denotes separation instead of completion. It enables many statements to be written on the same line. It also makes it legal at the end of a single sentence to put a semicolon. In fact, it’s two statements that empty the second.

When to Use a Semi-colon?

The most commonly asked logical question here would be: Why are Semi-colons allowed in Python?

I believe that it was done to make a transition from other programming languages slightly easier. Programmers with a background in Java, C++, and PHP habitually put a (useless) terminator at the end of every line.

But, there are certain conditions where semicolons are helpful.

  • Running Scripts from Shell
  • Evaluating Expressions for Side Effects

Role of Semicolons in Python

  1. Python is known as a simple coding language as there is no need of using Semicolon and if we even forget to place, it doesn’t throw an error.
  2. In Python, a Semicolon is not used to denote the end of the line.
  3. Python doesn’t use Semicolons but it is not restricted.
  4. Sometimes Python makes use of Semicolon as a line terminator where it is used as a divider to separate multiple lines.

How to Print a Semi-Colon in Python?

A semi-colon in Python means separation, rather than termination. It lets you compose various statements on the same line. Let’s examine what happens to us when we attempt to print semi-colons.

Below is the implementation:

#printing the semi colon
print(";")

Output:

;

It just treats the semicolon as a string (having one character) in python.

Split Statements Using Semicolons

Now, let’s look at how we can separate declarations using semicolons into Python. In this situation, we are going to try to employ a semicolon with more than two statements on the same course.

Syntax:

statement1; statement2 ; statement3

Semicolon in Python

Example:

Let us take four statements without semicolons

# printing four statements without using the semicolon
print("Hello")
print("This")
print("is")
print("BTechGeeks")

Output:

Hello
This
is
BTechGeeks

Now, let us take the same four statements using semicolons:

# printing four statements with using the semicolon
print("Hello");print("This");print("is");print("BTechGeeks")

Output:

Hello
This
is
BTechGeeks

As you can see, after splitting them with semicolons, Python performs the four commands individually. The interpreter would give us an error without this use.

Using semicolons with loops in Python

A semicolon may be used in loops like ‘For loop,’ if the entire statement begins with a loop and a semi-colon is used for a cohesive statement like a loop body.

Below is the implementation:

for i in range(10):print("Hello");print("this");print("is BTechGeeks python");print("Online Platform")

Output:

Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform

If you use a semicolon to separate a normal expression from a block statement, such as a loop, Python will throw an error.

print('hello') ; for i in range (10): print ('BTechGeeks')

Output:

  File "/home/36390fc9b8b053533f2165af206c5441.py", line 1
    print('hello') ; for i in range (10): print ('BTechGeeks')
                       ^
SyntaxError: invalid syntax

Conclusion on Python Program to Use Semicolon at the end of the Sentence

This takes us to the end of this little module where we learn how to use a semicolon at the end of multiple statements on the Python program. Let’s sum up the tutorial with two reminders:

  • In Python, a semicolon is commonly used to separate numerous statements written on a single line. So, you can use the python semicolon in a statement on the same line and attain the output that you wish.
  • Semicolons are used to write tiny statements and conserve some space, such as name = Vikram; age = 20; print (name, age)

The usage of semicolons is quite “non-pythonic” and should be avoided until absolutely necessary. But, Multiple statements on a single line should be avoided.

Though the language specification permits for the use of a semicolon to separate statements, doing so without cause makes one’s code more difficult to comprehend.

Related Programs:

Semicolon in Python | How & Why Python Semicolon is Used? Read More »

Replace Character in String by Index Position

Python: Replace Character in String by Index Position | How do you Replace Character at Index in String Python?

In this article, we have discussed how to replace a character in a string by Index Position. For your reference, we have outlined several methods for replacing characters in the string like slicing, replacing characters at multiple indexes, replacing multiple characters at multiple indexes, etc. Check out Sample Programs for Replacing Characters on String by Index Position for a better understanding of how to write code.

String – Definition

Strings are one of the most commonly used types in Python. We can easily make them by enclosing characters in quotes. Python considers single quotes to be the same as double quotes. String creation is as easy as assigning a value to a variable.

Examples:

Input:

string="Hello this is BTechGeeks" index=4 character='w'

Output:

Hellw this is BTechGeeks

Replace Character In String by Index Position in Python

There are several ways to replace characters in a string by index some of them are:

Method #1:Using Slicing to replace the character at index

Split a string in three sections in order to replace an index-position n character: characters before nth character, nth character and nth characters. Then add a new string and use the replacement character instead of using the nth character.

Below is the implementation:

Python Program using Slicing to Replace a Character in String by Index Position

# given string
string = "Hello this is BTechGeeks"
# given index
index = 4
# given character
character = 'w'
# using slicing to replace it
string = string[:index]+character+string[index+1:]
# print the string
print(string)

Output:

Hellw this is BTechGeeks

Method #2:Replace characters at multiple indexes

We have few index positions, and at these Index positions, we want to replace all characters. To achieve this, all index positions in the list will be iterated. And substitute the character on that index by cutting the string for each index

Below is the implementation:

Python Program to Replace characters at multiple indexes

# function which replaces the string
def replaceString(string, index, character):
    # replacing the string
    newString = string[:index]+character+string[index+1:]
    # return the string
    return newString


# given string
string = "Hello this is BTechGeeks"
# given index list
indexlist = [1, 4, 8]
# given character
character = 'w'
# Traversing the indexlist
for index in indexlist:
    string = replaceString(string, index, character)
# print the string
print(string)

Output:

Hwllw thws is BTechGeeks

Method #3: Replace multiple characters at multiple indexes

In the example above, we replace all characters with the same substitute characters in given positions. But we may want to have different replacement characters in certain scenarios.
If we have a dictionary with key-value pairs that contain the index positions and substitute characters. We want to substitute the corresponding replacement character in all characters at those index positions. This will be done through all of the dictionary’s key-value pairs. And replace each key with the character in the value field at that index position.

Below is the implementation:

# function which replaces the string
def replaceString(string, index, character):
    # replacing the string
    newString = string[:index]+character+string[index+1:]
    # return the string
    return newString


# given string
string = "Hello this is BTechGeeks"
# given index and characters
charsdict = {1: 'p', 4: 'q', 8: 's'}
# Traversing the charsdict
for index in charsdict:
    string = replaceString(string, index, charsdict[index])
# print the string
print(string)

Output:

Hpllq thss is BTechGeeks

Related Programs:

Python: Replace Character in String by Index Position | How do you Replace Character at Index in String Python? Read More »

Python Program To Remove all Duplicates Words from a Sentence

Counter() function in Python:

Python Counter is a container that keeps track of the count of each element in the container. The counter class is a subclass of the dictionary class.

The counter class is a subclass of the dictionary class. You can count the key-value pairs in an object, also known as a hash table object, using the Python Counter tool.

split() Method:

To extract the words from the string, we used the split() method with space as the separator, which returns a list of the words in the string.

key() method :

The key() method will be used to retrieve the keys of a dictionary. It returns all of the keys in a dictionary.

Given a string/sentence and the task is to remove all the duplicate words from a given sentence.

Examples:

Example1:

Input:

Given String =  'good morning btechgeeks good morning hello all all'

Output:

The given sentence after the removal of all duplicate words :
good morning btechgeeks hello all

Example2:

Input:

Given String = ' health is is wealth so protect it so so'

Output:

The given sentence after the removal of all duplicate words :
health is wealth so protect it

Program To Remove all Duplicates Words from a Sentence

Below are the ways to remove all the duplicate words from a given sentence.

Method #1: Using Counter() Function (Static Input)

Approach:

  • Import the Counter() function from the collections module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Split the given string into a list of words using the split() function and store it in another variable.
  • Apply Counter() function on the above-obtained list of words and store it in another variable.
  • Join all the keys of the above-obtained dictionary using the join() function and store it in another variable.
  • Print the given sentence after the removal of all duplicate words.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from the collections module using the import keyword.
from collections import Counter
# Give the string as static input and store it in a variable.
gvn_str = 'good morning btechgeeks good morning hello all all'
# Split the given string into a list of words using the split() function and
# store it in another variable.
splt_str = gvn_str.split(" ")
# Apply Counter() function on the above-obtained list of words and store it
# in another variable.
dictinry = Counter(splt_str)
# Join all the keys of the above-obtained dictionary using the join() function
# and store it in another variable.
reslt = " ".join(dictinry.keys())
# Print the given sentence after the removal of all duplicate words.
print("The given sentence after the removal of all duplicate words :")
print(reslt)

Output:

The given sentence after the removal of all duplicate words :
good morning btechgeeks hello all

Method #2: Using Counter() Function (User Input)

Approach:

  • Import the Counter() function from the collections module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Split the given string into a list of words using the split() function and store it in another variable.
  • Apply Counter() function on the above-obtained list of words and store it in another variable.
  • Join all the keys of the above-obtained dictionary using the join() function and store it in another variable.
  • Print the given sentence after the removal of all duplicate words.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from the collections module using the import keyword.
from collections import Counter
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string : ")
# Split the given string into a list of words using the split() function and
# store it in another variable.
splt_str = gvn_str.split(" ")
# Apply Counter() function on the above-obtained list of words and store it
# in another variable.
dictinry = Counter(splt_str)
# Join all the keys of the above-obtained dictionary using the join() function
# and store it in another variable.
reslt = " ".join(dictinry.keys())
# Print the given sentence after the removal of all duplicate words.
print("The given sentence after the removal of all duplicate words :")
print(reslt)

Output:

Enter some random string : health is is wealth so protect it so so
The given sentence after the removal of all duplicate words :
health is wealth so protect it

 

 

Python Program To Remove all Duplicates Words from a Sentence Read More »

Python Program to Remove the Last Word from String

Given a string and the task is to remove the last word from the given string.

split() method :

Splitting a string into a list is accomplished by the split() method.

join() function:

The join() method is a string method that returns a string containing the elements of a sequence that have been joined by a string separator.

Examples:

Example1:

Input:

Given string = "good morning this is btechgeeks hello all"

Output:

The given string after removal of last word from a string:
good morning this is btechgeeks hello

Example2:

Input:

Given string = "Hello this is btechgeeks "

Output:

The given string after removal of last word from a string: Hello this is

Program to Remove the Last Word from String

Below are the ways to remove the last word from the given string.

Method #1: Using Slicing (Static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the given string separated by spaces using the split function() and store it in another variable.
  • Remove the last word from a given string using the slicing and store it in another variable.
  • Convert the above-obtained list to string using the join() function and store it in a variable.
  • Print the given string after removal of the last word from a string.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "Hello this is btechgeeks "
# Split the given string separated by spaces using the split function()
# and store it in another variable.
splt_str = gvn_str.split()
# Remove the last word from a string using the slicing and store it in another variable.
rmove_lst_wrd = splt_str[:-1]
# Convert the above-obtained list to string using the join() function and
# store it in a variable.
fnl_str = ' '.join(rmove_lst_wrd)
print("The given string after removal of last word from a string:")
# Print the given string after removal of the last word from a string.
print(fnl_str)

Output:

The given string after removal of last word from a string:
Hello this is

Method #2: Using Slicing (User input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Split the given string separated by spaces using the split function() and store it in another variable.
  • Remove the last word from a given string using the slicing and store it in another variable.
  • Convert the above-obtained list to string using the join() function and store it in a variable.
  • Print the given string after removal of the last word from a string.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Split the given string separated by spaces using the split function()
# and store it in another variable.
splt_str = gvn_str.split()
# Remove the last word from a string using the slicing and store it in another variable.
rmove_lst_wrd = splt_str[:-1]
# Convert the above-obtained list to string using the join() function and
# store it in a variable.
fnl_str = ' '.join(rmove_lst_wrd)
print("The given string after removal of last word from a string:")
# Print the given string after removal of the last word from a string.
print(fnl_str)

Output:

Enter some random string = good morning this is btechgeeks hello all
The given string after removal of last word from a string:
good morning this is btechgeeks hello

Python Program to Remove the Last Word from String Read More »

Program to Print Items from a List with Specific Length

Python Program to Print Items from a List with Specific Length

In the previous article, we have discussed Python Program to Add Number to each Element in a List
Given a list of a string and some specific length and the task is to print items from a List with a given Specific Length.

len() function :

The len() function is a Python built-in function.

The length of a string is returned as an integer value by the len() function.

The length of a string can be obtained by passing a string value as a parameter to the len() function.

Examples:

Example1:

Input:

Given List = ['hello', 'btechgeeks', 'good', 'morning']
Given length = 5

Output:

The Items from a given List with given Specific Length : 
hello

Example 2:

Input:

Given List = ['abcd', 'efghigdh', 'kjfatr', 'ihg', 'dfth']
Given length = 4

Output:

The Items from a given List with given Specific Length : 
abcd
dfth

Program to Print Items from a List with Specific Length

Below are the ways to print items from a List with a given Specific Length.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the List of String as static input and store it in a variable.
  • Give the length as static input and store it in another variable.
  • Loop in the above-given list using for loop.
  • Inside the loop, check if the length of the iterator is equal to the given length using the len() function and if conditional statement.
  • If the statement is true, then print the iterator value(i.e. string).
  • The Exit of the program.

Below is the implementation:

# Give the List of String as static input and store it in a variable.
gvn_lst = ['hello', 'btechgeeks', 'good', 'morning']
# Given the length as static input and store it in another variable.
gvn_len = 5
# Loop in the above-given list using for loop.
print("The Items from a given List with given Specific Length : ")
for itr in gvn_lst:
  # Inside the loop, check if the length of the iterator is equal to the given length
  # using len() function and if conditional statement.
    if(len(itr)) == gvn_len:
     # If the statement is true, then print the iterator value(i.e. string).
        print(itr)

Output:

The Items from a given List with given Specific Length : 
hello

Method #2: Using For Loop (User Input)

Approach:

  • Give the List of Strings as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the length as user input using the int(input()) function and store it in another variable.
  • Loop in the above-given list using for loop.
  • Inside the loop, check if the length of the iterator is equal to the given length using len() function and if conditional statement.
  • If the statement is true, then print the iterator value(i.e. string).
  • The Exit of the program.

Below is the implementation:

# Give the List of String as user input using list(),map(),input(),and 
#split() functions and store it in a variable.
gvn_lst = list(map(str, input( 'Enter some random List Elements separated by spaces = ').split()))
# Give the length as user input using int(input())and store it in another variable.
gvn_len = int(input("Enter some random number = "))
# Loop in the above-given list using for loop.
print("The Items from a given List with given Specific Length : ")
for itr in gvn_lst:
  # Inside the loop, check if the length of the iterator is equal to the given length
  # using len() function and if conditional statement.
    if(len(itr)) == gvn_len:
     # If the statement is true, then print the iterator value(i.e. string).
        print(itr)

Output:

Enter some random List Elements separated by spaces = abcd efghigdh kjfatr ihg dfth
Enter some random number = 4
The Items from a given List with given Specific Length : 
abcd
dfth

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Print Items from a List with Specific Length Read More »

Program to Check a Binary Number is Divisible by a Number N

Python Program to Check a Binary Number is Divisible by a Number N

In the previous article, we have discussed Python Program to Pick a Random Card
Binary Number:

A binary number is a number expressed in the base 2 numeral system, which employs only the symbols 0 and 1.

Conversion from binary to decimal:

binary number = 1010

decimal number = int(str(binary number),2)

Given a binary number, and the task is to check if the binary number is divisible by a given number N.

Examples:

Example1:

Input:

Given binary number = 1100
Given number = 4

Output:

The given binary number is divisible by{ 4 }

Example2:

Input:

Given binary number = 1000
Given number = 2

Output:

The given binary number is divisible by{ 2 }

Program to Check a Binary Number is Divisible by a number N.

Below are the ways to check if the given binary number is divisible by a given number N.

Method #1: Using Built-in Functions (Static input)

Approach:

  • Give the binary number as static input and store it in a variable.
  • Given the number as static input and store it in another variable.
  • Convert the given binary number into a decimal number using int(str(binary number),2) function and store it in another variable say “deci”.
  • Check if the above-obtained decimal number modulus given number is equal to 0 using the if conditional statement.
  • If the statement is true, then print “The binary number is divisible by the given input number”.
  • Else print “The binary number is not divisible by the given input number”.
  • The Exit of the program.

Below is the implementation:

# Give the binary number as static input and store it in a variable.
binry = 1100
# Given the number as static input and store it in another variable.
num = 4
# Convert the given binary number into a decimal number using int(str(binary number),2)
# function and store it in another variable say "deci".
deci = int(str(binry), 2)
# Check if the above-obtained decimal number modulus given number is equal to 0 using the if
# conditional statement.
if deci % num == 0:
    # If the statement is true, then print "The binary number is divisible by the given
    # input number".
    print("The given binary number is divisible by{", num, "}")
else:
 # Else print ""The binary number is not divisible by the given input number".
    print("The given binary number is not divisible by{", num, "}")

Output:

The given binary number is divisible by{ 4 }

Method #2: Using Built-in Functions (User input)

Approach:

  • Give the binary number as user input using int(input()) and store it in a variable.
  • Given the number as user input using int(input()) and store it in another variable.
  • Convert the given binary number into a decimal number using int(str(binary number),2) function and store it in another variable say “deci”.
  • Check if the above-obtained decimal number modulus given number is equal to 0 using the if conditional statement.
  • If the statement is true, then print “The binary number is divisible by the given input number”.
  • Else print “The binary number is not divisible by the given input number”.
  • The Exit of the program.

Below is the implementation:

# Give the binary number as user input using int(input()) and store it in a variable.
binry = int(input("Enter some random number = "))
# Given the number as user input using int(input()) and store it in another variable.
num = int(input("Enter some random number = "))
# Convert the given binary number into a decimal number using int(str(binary number),2)
# function and store it in another variable say "deci".
deci = int(str(binry), 2)
# Check if the above-obtained decimal number modulus given number is equal to 0 using the if
# conditional statement.
if deci % num == 0:
    # If the statement is true, then print "The binary number is divisible by the given
    # input number".
    print("The given binary number is divisible by{", num, "}")
else:
 # Else print ""The binary number is not divisible by the given input number".
    print("The given binary number is not divisible by{", num, "}")

Output:

Enter some random number = 1000
Enter some random number = 2
The given binary number is divisible by{ 2 }

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Check a Binary Number is Divisible by a Number N Read More »

Program to Delete Random Item from a List

Python Program to Delete Random Item from a List

In the previous article, we have discussed Python Program to Print Items from a List with Specific Length
Random Module in python :

As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

The random module is extremely useful for creating a variety of entertaining games.

choice():  choice() is used to select an item at random from a list, tuple, or other collection.

Because the choice() method returns a single element, we will be using it in looping statements.

Examples:

Example1:

Input:

Given List = ['apple', 'mango', 'banana', 'orange']

Output:

The given list after deletion of random item = ['apple', 'banana', 'orange']

Example2:

Input:

Given List = ['good', 'morning', 'btechgeeks', 'hello', 'all']

Output:

The given list after deletion of random item = ['good', 'morning', 'hello', 'all']

Program to Delete Random Item from a List

Below are the ways to Delete Random items from a given List.

Method #1: Using random.choice Method (Static input)

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in another variable.
  • Apply random. choice() method for the above-given list to get the random item and store it in another variable.
  • Remove the above obtained random item from the given list.
  • Print the above-given list after deletion of random items from the list.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in another variable.
gvn_lst = ['apple', 'mango', 'banana', 'orange']
# Apply random.choice() method for the above-given list to get the random item and
# store it in another variable.
randm_item = random.choice(gvn_lst)
# Remove the above obtained random item from the given list.
gvn_lst.remove(randm_item)
# Print the above-given list after deletion of random item from the list.
print("The given list after deletion of random item =", gvn_lst)

Output:

The given list after deletion of random item = ['apple', 'banana', 'orange']

Method #2: Using random.choice Method (User input)

Approach:

  • Import random module using the import keyword.
  • Give the List as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Apply random. choice() method for the above-given list to get the random item and store it in another variable.
  • Remove the above obtained random item from the given list.
  • Print the above-given list after deletion of random items from the list.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the List as user input using list(),map(),input(),and split() functions and 
#store it in a variable.
gvn_lst = list(map(str, input( 'Enter some random List Elements separated by spaces = ').split()))
# Apply random.choice() method for the above-given list to get the random item and
# store it in another variable.
randm_item = random.choice(gvn_lst)
# Remove the above obtained random item from the given list.
gvn_lst.remove(randm_item)
# Print the above-given list after deletion of random item from the list.
print("The given list after deletion of random item =", gvn_lst)

Output:

Enter some random List Elements separated by spaces = good morning btechgeeks hello all
The given list after deletion of random item = ['good', 'morning', 'hello', 'all']

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Delete Random Item from a List Read More »

Program to Shuffle a List

Python Program to Shuffle a List

In the previous article, we have discussed Python Program to Print a Deck of Cards in Python
To shuffle the elements in a list means to arrange them in random order.

In Python, there are numerous ways to shuffle the elements of a list.

Like using random.shuffle() method , for loop etc.

Random Module in python :

As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

The random module is extremely useful for creating a variety of entertaining games.

random.shuffle(): To shuffle an object, use random. shuffle().

Given a list and the task is to shuffle the elements of a given list.

Examples:

Example1:

Input:

Given list = ['good', 'morning', 'btechgeeks', '651326', '12345', 'great', 'coding', 'platform']

Output:

The given list after shuffling the elements = ['good', '651326', 'coding', 'platform', 'morning', 'great', 'btechgeeks', '12345']

Example2:

Input:

Given list =['potato' ,'tomato', 'carrot', 'brinjal, 'beetroot']

Output:

The given list after shuffling the elements = ['tomato', 'potato', 'brinjal', 'carrot', 'beetroot']

Program to Shuffle a List

Below are the ways to shuffle a given list.

Method #1: Using random.shuffle() Method (Static input)

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in another variable.
  • Apply random. shuffle() method for the above-given list to shuffle the items of a given list.
  • Print the shuffled list of the given input list.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as static input and store it in another variable.
gvn_lst = ['hello', 'this', 'is', 'btechgeeks', '12345']
# Apply random. shuffle() method for the above-given list to shuffle the items
# of a given list.
random.shuffle(gvn_lst)
# Print the shuffled list of the given input list.
print("The given list after shuffling the elements =", gvn_lst)

Output:

The given list after shuffling the elements = ['this', 'hello', '12345', 'is', 'btechgeeks']

Method #2: Using random.shuffle() Method (User input)

Approach:

  • Import random module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions and store it in another variable. 
  • Apply random. shuffle() method for the above-given list to shuffle the items of a given list.
  • Print the shuffled list of the given input list.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the list as user input using list(),map(),input(),and split() functions 
#and store it in another variable.
gvn_lst = list(map(str, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Apply random. shuffle() method for the above-given list to shuffle the items
# of a given list.
random.shuffle(gvn_lst)
# Print the shuffled list of the given input list.
print("The given list after shuffling the elements =", gvn_lst)

Output:

Enter some random List Elements separated by spaces = potato tomato carrot brinjal beetroot
The given list after shuffling the elements = ['tomato', 'potato', 'brinjal', 'carrot', 'beetroot']

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Shuffle a List Read More »

Program to Calculate Age in Days from Date of Birth

Python Program to Calculate Age in Days from Date of Birth

In the previous article, we have discussed Python Program to Check Strontio Number or Not.
Given the Date of Birth and task is to calculate the corresponding age in days.

datetime module:

The datetime module contains numerous classes that can be used to manipulate date and time in both simple and complex ways.

In this, the date is formatted as the year month date (YY, MM, DD).

datetime.today() :The current date/system date is returned by datetime.today().

To calculate age from date of birth, subtract the date of birth from the current date.

timedelta() function in Python:

The Python timedelta() function is part of the datetime library and is commonly used for calculating date differences. It can also be used for date manipulation in Python. It is one of the simplest methods for manipulating dates.

Examples:

Example1:

Input:

Given Date of Birth = (2000, 3, 14)

Output:

The age in days and time for the Given DOB =  7823 days, 14:16:13.409557

Example2:

Input:

Given Date of Birth = (1999, 5, 16)

Output:

The age in days and time for the Given DOB = 8126 days, 14:14:30.074853

Program to Calculate Age in Days from Date of Birth

Below are the ways to calculate age in days from the given Date of Birth.

Method #1: Using the datetime Module (Static Input)

Approach:

  • Import datetime(), timedelta() functions from datetime module using import keyword.
  • Give the date of birth as static input in the format (YY, MM, DD) using datetime() function and store it in a variable.
  • Get the current/today date using datetime.today() function and store it in another variable.
  • Subtract the given date of birth from the current date to get the age in days and store it in another variable.
  • Print the age in days and time from the given date of birth.
  • The Exit of the Program.

Note: If we include the timedelta() function we get age in time including microseconds.

If you want age only in days then remove the timedelta() function import only datetime() function.

Below is the implementation:

# Import datetime(), timedelta() functions from datetime module using import keyword.
from datetime import datetime, timedelta
# Give the date of birth as static input in the format (YY, MM, DD) using datetime() function
# and store it in a variable.
gvn_DOB = datetime(1999, 5, 16)
# Get the current/today date using datetime.today() function and store it in
# another variable.
current_date = datetime.today()
# Subtract the given date of birth from the current date to get the age in days
# and store it in another variable.
age_in_days = current_date - gvn_DOB
# Print the age in days and time from the given date of birth.
print("The age in days and time for the Given DOB = ", age_in_days)

Output:

The age in days and time for the Given DOB =  8126 days, 14:14:30.074853

Method #2: Using the datetime Module (User Input)

Approach:

  • Import datetime(), timedelta() functions from datetime module using import keyword.
  • Give the year, month, day as user input using map (), int(), split() functions and store them separately in three different variables.
  • Convert the year, month, day to date of birth using datetime() module and store it in another variable.
  • Get the current/today date using datetime.today() function and store it in another variable.
  • Subtract the given date of birth from the current date to get the age in days and store it in another variable.
  • Print the age in days and time from the given date of birth.
  • The Exit of the Program.

Below is the implementation:

# Import datetime(), timedelta() functions from datetime module using import keyword.
from datetime import datetime, timedelta
# Give the year, month, day as user input using map (), int(), split() functions 
#and store them separately in three different variables.
yr,mont,dy= map(int,input("Enter year ,month ,day separated by spaces = ").split())
#Convert the year, month, day to date of birth using datetime() module and store it in another variable.
gvn_DOB=datetime(yr, mont, dy)
# Get the current/today date using datetime.today() function and store it in
# another variable.
current_date = datetime.today()
# Subtract the given date of birth from the current date to get the age in days
# and store it in another variable.
age_in_days = current_date - gvn_DOB
# Print the age in days and time from the given date of birth.
print("The age in days and time for the Given DOB = ", age_in_days)

Output:

Enter year ,month ,day separated by spaces = 2003 7 19
The age in days and time for the Given DOB = 6601 days, 14:47:41.427259

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Calculate Age in Days from Date of Birth Read More »