Python

Python Itertools.permutations() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools in Python refers to a Python module that allows the creation of iterators, which aids in efficient looping, as well as time and space efficiency. Itertools enable us to solve complex problems quickly and easily. Iterators are classified into three types.

This module provides the following types of iterators:

  1. Combinatorics Generators
  2. Infinite Iterators
  3. Terminating Iterators

itertools.permutations() Function:

Itertools.permutations() function is part of the Combinatoric Generators class. Combinatoric iterators are recursive generators that are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products.

The term “permutation” refers to all of the possible ways in which a set or string can be ordered or arranged. Similarly, itertool. The permutations() method returns all possible arrangements for an iterator, and all elements are assumed to be unique based on their position rather than their value or category.

All of these permutations are listed in alphabetical order. The function itertools.permutations() accepts an iterator and ‘r’ (length of permutation required) as input and, if not specified, assumes ‘r’ as the default length of the iterator and returns all possible permutations of length ‘r’ each.

Syntax:

permutations(iterator, r)

Parameters

iterator: This is Required. Elements whose cartesian product must be calculated.

r: This is Optional. The length of the outputs (number of iterables by default).

Examples:

Example1:

Input:

Given string = "hello"
Given r value(length)= 3

Output:

('h', 'e', 'l')
('h', 'e', 'l')
('h', 'e', 'o')
('h', 'l', 'e')
('h', 'l', 'l')
('h', 'l', 'o')
('h', 'l', 'e')
('h', 'l', 'l')
('h', 'l', 'o')
('h', 'o', 'e')
('h', 'o', 'l')
('h', 'o', 'l')
('e', 'h', 'l')
('e', 'h', 'l')
('e', 'h', 'o')
('e', 'l', 'h')
('e', 'l', 'l')
('e', 'l', 'o')
('e', 'l', 'h')
('e', 'l', 'l')
('e', 'l', 'o')
('e', 'o', 'h')
('e', 'o', 'l')
('e', 'o', 'l')
('l', 'h', 'e')
('l', 'h', 'l')
('l', 'h', 'o')
('l', 'e', 'h')
('l', 'e', 'l')
('l', 'e', 'o')
('l', 'l', 'h')
('l', 'l', 'e')
('l', 'l', 'o')
('l', 'o', 'h')
('l', 'o', 'e')
('l', 'o', 'l')
('l', 'h', 'e')
('l', 'h', 'l')
('l', 'h', 'o')
('l', 'e', 'h')
('l', 'e', 'l')
('l', 'e', 'o')
('l', 'l', 'h')
('l', 'l', 'e')
('l', 'l', 'o')
('l', 'o', 'h')
('l', 'o', 'e')
('l', 'o', 'l')
('o', 'h', 'e')
('o', 'h', 'l')
('o', 'h', 'l')
('o', 'e', 'h')
('o', 'e', 'l')
('o', 'e', 'l')
('o', 'l', 'h')
('o', 'l', 'e')
('o', 'l', 'l')
('o', 'l', 'h')
('o', 'l', 'e')
('o', 'l', 'l')

Example2:

Input:

Given list = [123, 'hello', 'all']
Given r value(length)= 3

Output:

The all given list's permutations are :
[(123, 'hello', 'all'), (123, 'all', 'hello'), ('hello', 123, 'all'), ('hello', 'all', 123), ('all', 123, 'hello'), ('all', 'hello', 123)]

itertools.permutations() Function with Examples in Python

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

Approach:

  • Import permutations() function from itertools module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Give the r value as static input and store it in another variable.
  • Pass the given string and ‘r’ value as the arguments to the permutations() function and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Loop in the above result list using the for loop.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import permutations() function from itertools module using the
# import keyword.
from itertools import permutations
# Give the string as static input and store it in a variable.
gvn_str = "hello"
# Give the r value as static input and store it in another variable.
gvn_r_valu = 3
# Pass the given string and 'r' value as the arguments to the
# permutations() function and store it in a variable.
rslt = permutations(gvn_str, gvn_r_valu)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Loop in the above result list using the for loop
for itr in rslt_lst:
    # Inside the loop, print the iterator value
    print(itr)

Output:

('h', 'e', 'l')
('h', 'e', 'l')
('h', 'e', 'o')
('h', 'l', 'e')
('h', 'l', 'l')
('h', 'l', 'o')
('h', 'l', 'e')
('h', 'l', 'l')
('h', 'l', 'o')
('h', 'o', 'e')
('h', 'o', 'l')
('h', 'o', 'l')
('e', 'h', 'l')
('e', 'h', 'l')
('e', 'h', 'o')
('e', 'l', 'h')
('e', 'l', 'l')
('e', 'l', 'o')
('e', 'l', 'h')
('e', 'l', 'l')
('e', 'l', 'o')
('e', 'o', 'h')
('e', 'o', 'l')
('e', 'o', 'l')
('l', 'h', 'e')
('l', 'h', 'l')
('l', 'h', 'o')
('l', 'e', 'h')
('l', 'e', 'l')
('l', 'e', 'o')
('l', 'l', 'h')
('l', 'l', 'e')
('l', 'l', 'o')
('l', 'o', 'h')
('l', 'o', 'e')
('l', 'o', 'l')
('l', 'h', 'e')
('l', 'h', 'l')
('l', 'h', 'o')
('l', 'e', 'h')
('l', 'e', 'l')
('l', 'e', 'o')
('l', 'l', 'h')
('l', 'l', 'e')
('l', 'l', 'o')
('l', 'o', 'h')
('l', 'o', 'e')
('l', 'o', 'l')
('o', 'h', 'e')
('o', 'h', 'l')
('o', 'h', 'l')
('o', 'e', 'h')
('o', 'e', 'l')
('o', 'e', 'l')
('o', 'l', 'h')
('o', 'l', 'e')
('o', 'l', 'l')
('o', 'l', 'h')
('o', 'l', 'e')
('o', 'l', 'l')

Note:

If no length(r value) is specified, the default value will be taken as 
string length

Similarly, try for the list, string, and range as shown below

from itertools import permutations

print("The all given list's permutations are :")
print(list(permutations([123, 'hello', 'all'], 3)))
print()

print("The all given strings's permutations are :")
print(list(permutations('hi')))
print()

print("The all given container's permutations are :")
print(list(permutations(range(4), 3)))

Output:

The all given list's permutations are :
[(123, 'hello', 'all'), (123, 'all', 'hello'), ('hello', 123, 'all'), ('hello', 'all', 123), ('all', 123, 'hello'), ('all', 'hello', 123)]

The all given strings's permutations are :
[('h', 'i'), ('i', 'h')]

The all given container's permutations are :
[(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)]

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

Approach:

  • Import permutations() function from itertools module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Give the r value as user input using the int(input()) function and store it in another variable.
  • Pass the given string and ‘r’ value as the arguments to the permutations() function and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Loop in the above result list using the for loop.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import permutations() function from itertools module using the
# import keyword.
from itertools import permutations
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Give the r value as user input using the int(input()) function and
# store it in another variable.
gvn_r_valu = int(input("Enter some random number = "))
# Pass the given string and 'r' value as the arguments to the
# permutations() function and store it in a variable.
rslt = permutations(gvn_str, gvn_r_valu)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Loop in the above result list using the for loop
for itr in rslt_lst:
    # Inside the loop, print the iterator value
    print(itr)

Output:

Enter some random string = good
Enter some random number = 3
('g', 'o', 'o')
('g', 'o', 'd')
('g', 'o', 'o')
('g', 'o', 'd')
('g', 'd', 'o')
('g', 'd', 'o')
('o', 'g', 'o')
('o', 'g', 'd')
('o', 'o', 'g')
('o', 'o', 'd')
('o', 'd', 'g')
('o', 'd', 'o')
('o', 'g', 'o')
('o', 'g', 'd')
('o', 'o', 'g')
('o', 'o', 'd')
('o', 'd', 'g')
('o', 'd', 'o')
('d', 'g', 'o')
('d', 'g', 'o')
('d', 'o', 'g')
('d', 'o', 'o')
('d', 'o', 'g')
('d', 'o', 'o')

 

Python Itertools.permutations() Function with Examples Read More »

Python Itertools.combinations() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools in Python refers to a Python module that allows the creation of iterators, which aids in efficient looping, as well as time and space efficiency. itertools enable us to solve complex problems quickly and easily. Iterators are classified into three types.

This module provides the following types of iterators:

  1. Combinatorics Generators
  2. Infinite Iterators
  3. Terminating Iterators

itertools.combinations() Function:

Generate and print all possible combinations of r elements in an array of size n.

It returns r length subsequences of the input iterable’s elements. Combinations are emitted in alphabetical order. As a result, if the input iterable is sorted, the combination tuples will be generated in the same order.

Syntax:

itertools.combinations(iterable, r)

Parameters

iterable: This is Required. Elements whose combinations must be performed out.

r: This is Required. It is the length of the outputs.

Using itertools.combinations(iterable, r):
It returns sorted r-length tuples with no repeated elements.

for example:

combinations(‘ABCD’, 2) = [AB, AC, AD, BC, BD, CD].

Using combinations_with_replacement(iterable, r):
It returns sorted r-length tuples with repeated elements.

for example:

combinations_with_replacement(‘ABCD’, 2),  = [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD].

Examples:

Example1:

Input:

Given list  = [5, 6, 7, 8]
Given r value =  2

Output:

The possible combinations are : 
[(5, 6), (5, 7), (5, 8), (6, 7), (6, 8), (7, 8)]

Example2:

Input:

Given list  = [10, 50, 100, 40]
Given r value =  3

Output:

The possible combinations are : 
[(10, 50, 100), (10, 50, 40), (10, 100, 40), (50, 100, 40)]

itertools.combinations() Function with Examples in Python

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

Approach:

  • Import combinations() function from itertools module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Give the r value as static input and store it in another variable.
  • Pass the given list and ‘r’ value as the arguments to the combinations() function to get all the possible combinations of list elements for the given r value and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import combinations() function from itertools module using the
# import keyword.
from itertools import combinations
# Give the list as static input and store it in a variable.
gvn_lst = [5, 6, 7, 8]
# Give the r value as static input and store it in another variable.
gvn_r_valu = 2
# Pass the given list and 'r' value as the arguments to the combinations()
# function to get all the possible combinations of list elements for the given
# r value and store it in a variable.
rslt = combinations(gvn_lst, gvn_r_valu)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The possible combinations are : ")
print(rslt_lst)

Output:

The possible combinations are : 
[(5, 6), (5, 7), (5, 8), (6, 7), (6, 8), (7, 8)]

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

Approach:

  • Import combinations() function from itertools module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the r value as user input using the int(input()) function and store it in another variable.
  • Pass the given list and ‘r’ value as the arguments to the combinations() function to get all the possible combinations of list elements for the given r value and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import combinations() function from itertools module using the
# import keyword.
from itertools import combinations
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
   
# Give the r value as user input using the int(input()) function and
# store it in another variable.
gvn_r_valu = int(input("Enter some random number = "))
# Pass the given list and 'r' value as the arguments to the combinations()
# function to get all the possible combinations of list elements for the given
# r value and store it in a variable.
rslt = combinations(gvn_lst, gvn_r_valu)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The possible combinations are : ")
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = 10 50 100 40
Enter some random number = 3
The possible combinations are : 
[(10, 50, 100), (10, 50, 40), (10, 100, 40), (50, 100, 40)]

 

Python Itertools.combinations() Function with Examples Read More »

Python Itertools.combinations_with_replacement() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools in Python refers to a Python module that allows the creation of iterators, which aids in efficient looping, as well as time and space efficiency. Itertools enables us to solve complex problems quickly and easily. Iterators are classified into three types.

This module provides the following types of iterators:

  1. Combinatorics Generators
  2. Infinite Iterators
  3. Terminating Iterators

itertools.combinations_with_replacement() Function:

itertools.combinations_with_replacement() function belongs to the itertools Combinatoric Generator subtype. Combinatoric generators are iterators that deal with the various arrangements that an iterator can take. The elements are referred to here by their index value rather than their value or type.

Usage of this function

The term “combinations” refers to all of the possible subsets or arrangements of the iterator, whereas “combinations with replacement” refers to all of the possible arrangements or subsets that allow an element to repeat in a subset.

This function accepts ‘r’ as an input, where ‘r’ represents the number of possible combinations. All combinations with element repetition are emitted and have a length of ‘r,’ and ‘r’ is a necessary argument here.

Syntax:

itertools.combinations_with_replacement(iterable, r)

Parameters

iterable: This is Required. Elements whose combinations must be performed out.

r: This is Required. It is the length of the outputs.

Examples:

Example1:

Input:

Given string  = "hello"
Given r value =  2

Output:

The possible combinations with replacemenet are : 
[('h', 'h'), ('h', 'e'), ('h', 'l'), ('h', 'l'), ('h', 'o'), ('e', 'e'), ('e', 'l'), ('e', 'l'), ('e', 'o'), ('l', 'l'), ('l', 'l'), ('l', 'o'), ('l', 'l'), ('l', 'o'), ('o', 'o')]

Example2:

Input:

Given string  = "good"
Given r value = 3

Output:

The possible combinations with replacemenet are : 
[('g', 'g', 'g'), ('g', 'g', 'o'), ('g', 'g', 'o'), ('g', 'g', 'd'), ('g', 'o', 'o'), ('g', 'o', 'o'), ('g', 'o', 'd'), ('g', 'o', 'o'), ('g', 'o', 'd'), ('g', 'd', 'd'), ('o', 'o', 'o'), ('o', 'o', 'o'), ('o', 'o', 'd'), ('o', 'o', 'o'), ('o', 'o', 'd'), ('o', 'd', 'd'), ('o', 'o', 'o'), ('o', 'o', 'd'), ('o', 'd', 'd'), ('d', 'd', 'd')]

itertools.combinations_with_replacement() Function with Examples in Python

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

Approach:

  • Import combinations_with_replacement() function from itertools module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Give the r value as static input and store it in another variable.
  • Pass the given string and ‘r’ value as the arguments to the combinations_with_replacement() function and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import combinations_with_replacement() function from itertools module using the
# import keyword.
from itertools import combinations_with_replacement
# Give the string as static input and store it in a variable.
gvn_str = "hello"
# Give the r value as static input and store it in another variable.
gvn_r_valu = 2
# Pass the given string and 'r' value as the arguments to the
# combinations_with_replacement() function and store it in a variable.
rslt = combinations_with_replacement(gvn_str, gvn_r_valu)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The possible combinations with repalcement are : ")
print(rslt_lst)

Output:

The possible combinations with repalcement are : 
[('h', 'h'), ('h', 'e'), ('h', 'l'), ('h', 'l'), ('h', 'o'), ('e', 'e'), ('e', 'l'), ('e', 'l'), ('e', 'o'), ('l', 'l'), ('l', 'l'), ('l', 'o'), ('l', 'l'), ('l', 'o'), ('o', 'o')]

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

Approach:

  • Import combinations_with_replacement() function from itertools module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Give the r value as user input using the int(input()) function and store it in another variable.
  • Pass the given string and ‘r’ value as the arguments to the combinations_with_replacement() function and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import combinations_with_replacement() function from itertools module using the
# import keyword.
from itertools import combinations_with_replacement
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Give the r value as user input using the int(input()) function and
# store it in another variable.
gvn_r_valu = int(input("Enter some random number = "))
# Pass the given string and 'r' value as the arguments to the
# combinations_with_replacement() function and store it in a variable.
rslt = combinations_with_replacement(gvn_str, gvn_r_valu)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The possible combinations are : ")
print(rslt_lst)

Output:

Enter some random string = good
Enter some random number = 3
The possible combinations are : 
[('g', 'g', 'g'), ('g', 'g', 'o'), ('g', 'g', 'o'), ('g', 'g', 'd'), ('g', 'o', 'o'), ('g', 'o', 'o'), ('g', 'o', 'd'), ('g', 'o', 'o'), ('g', 'o', 'd'), ('g', 'd', 'd'), ('o', 'o', 'o'), ('o', 'o', 'o'), ('o', 'o', 'd'), ('o', 'o', 'o'), ('o', 'o', 'd'), ('o', 'd', 'd'), ('o', 'o', 'o'), ('o', 'o', 'd'), ('o', 'd', 'd'), ('d', 'd', 'd')]

 

Python Itertools.combinations_with_replacement() Function with Examples Read More »

Python callable() Function with Examples

callable() Function in Python:

If the specified object is callable, the callable() function returns true; otherwise, it returns False.

Syntax:

callable(object)

Parameters

object: It is an object that you want to see if an object is callable or not.

Return Value:

The callable() method yields:

  • True if the object appears to be callable.
  • False if the object cannot be called.

Note: It is important to remember that even if callable() is True, a call to the object may fail.

If callable() returns False, the call to the object will almost certainly fail.

Examples:

Example1:

Input:

Given Number = 10

Output:

Checking if the given number is callable or Not =  False

Explanation:

A normal variable cannot be called(not callable)

Example2:

Input:

Given Number = 25

Output:

Checking if the given number is callable or Not =  False

callable() Function with Examples in Python

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

Approach:

  • Give the number as static input and store it in a variable.
  • Pass the given number as an argument to the callable() method that returns True if the given number is callable. Otherwise, it returns False.
  • Store it in another variable.
  • Print the result after checking if the given number is callable or Not.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 10
# Pass the given number as an argument to the callable() method that returns True if
# the given number is callable. Otherwise, it returns False.
# Store it in another variable.
rslt = callable(gvn_numb)
# Print the result after checking if the given number is callable or Not.
print("Checking if the given number is callable or Not = ", rslt)

Output:

Checking if the given number is callable or Not =  False
For Functions

Approach:

  • Create a function say num.
  • Inside the function, take a variable and initialize it with some random variable.
  • Inside the main function, pass the above variable function attribute to the callable() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function say num.
def num():
    # Inside the function, take a variable and initialize it with some random variable.
    y = 10


# Inside the main function, pass the above variable function attribute to
# the callable() function and print it.
print(callable(num))

Output:

True

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

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Pass the given number as an argument to the callable() method that returns True if the given number is callable. Otherwise, it returns False.
  • Store it in another variable.
  • Print the result after checking if the given number is callable or Not.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Pass the given number as an argument to the callable() method that returns True if
# the given number is callable. Otherwise, it returns False.
# Store it in another variable.
rslt = callable(gvn_numb)
# Print the result after checking if the given number is callable or Not.
print("Checking if the given number is callable or Not = ", rslt)

Output:

Enter some random number = 25
Checking if the given number is callable or Not = False

Python callable() Function with Examples Read More »

Python Random uniform() Method with Examples

Random uniform() Method in Python:

The uniform() method generates a random floating-point number between the two input values (both included).

Syntax:

random.uniform(a, b)

Parameters

a: This is Required. A number indicating the lowest possible outcome.

b: This is Required. A number indicating the highest possible outcome.

Examples:

Example1:

Input:

Given first number = 10
Given second number = 20

Output:

The random floating-point number between 10 and 20 = 17.597119991005258
(both 10 and 20 included)

Example2:

Input:

Given first number = 80
Given second number = 90

Output:

The random floating-point number between 80 and 90 = 81.63985884463067
(both 80 and 90 included)

Random uniform() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Give the other number as static input and store it in another variable.
  • Pass the given two numbers as the arguments to the random.uniform() method that generates a random floating-point number between the given two numbers (both included).
  • Store it in another variable.
  • Print a random floating-point number between the given two numbers (both included).
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as static input and store it in a variable.
gvn_fstnum = 10
# Give the other number as static input and store it in another variable.
gvn_scndnum = 20
# Pass the given two numbers as the arguments to the random.uniform() method
# that generates a random floating-point number between the given two numbers
# (both included).
# Store it in another variable.
rslt = random.uniform(gvn_fstnum, gvn_scndnum)
# Print a random floating-point number between the two numbers (both included).
print("The random floating-point number between",
      gvn_fstnum, "and", gvn_scndnum, "=", rslt)

Output:

The random floating-point number between 10 and 20 = 17.597119991005258

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

Approach:

  • Import random module using the import keyword.
  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the other number as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to the random.uniform() method that generates a random floating-point number between the given two numbers (both included).
  • Store it in another variable.
  • Print a random floating-point number between the given two numbers (both included).
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as user input using the int(input()) function and store it in a variable.
gvn_fstnum = int(input("Enter some random number = "))
# Give the other number as user input using the int(input()) function 
# and store it in another variable.
gvn_scndnum = int(input("Enter some random number = "))

# Pass the given two numbers as the arguments to the random.uniform() method
# that generates a random floating-point number between the given two numbers
# (both included).
# Store it in another variable.
rslt = random.uniform(gvn_fstnum, gvn_scndnum)
# Print a random floating-point number between the two numbers (both included).
print("The random floating-point number between",
      gvn_fstnum, "and", gvn_scndnum, "=", rslt)

Output:

Enter some random number = 80
Enter some random number = 90
The random floating-point number between 80 and 90 = 81.63985884463067

Python Random uniform() Method with Examples Read More »

Python Random choices() Method with Examples

Random choices() Method in Python:

The choices() method returns a list containing the element from the specified sequence that was chosen at random.

You can use the weights or cum weights parameters to weigh the likelihood of each result.

The sequence could be a string, a range, a list, a tuple, or anything else.

Syntax:

random.choices(sequence, weights=None, cum_weights=None, k=1)

Parameters

sequence: This is Required. It could be a list, a tuple, a range of numbers, and so on.

weights: This is Optional. A list where you can weigh the pros and cons of each value.
None is the default.

cum_weights: Optional. A list in which you can weigh the possibility for each value, except that this time the possibility is accumulated.
For instance, the normal weights list [2, 1, 1] is the same as the cum weights list [2, 3, 4].
None is the default.

k: This is Optional. An integer that specifies the length of the returned list.

Examples:

Example1:

Input:

Given List = ["good", "morning", "all"]
Given weights = [5, 1, 1]
Given k value = 10

Output:

['good', 'all', 'good', 'good', 'good', 'morning', 'good', 'good', 'good', 'good']

Explanation:

Return a list containing 10 items.
The list should contain a random selection of values from a given list, with
the possibility of selecting "good" being 5 times greater than the other two

Example2:

Input:

Given List = [1,2,3]
Given weights = [1,1,3]
Given k value = 12

Output:

[2, 1, 3, 3, 3, 2, 3, 3, 3, 2, 2, 3]

Explanation:

Return a list containing 12 items.
The list should contain a random selection of values from a given list, with 
the possibility of selecting "3" being 3 times greater than the other two

Random choices() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Give the weights as a list as static input and store it in another variable.
  • Give the k value as static input and store it in another variable.
  • Pass the given list, weights, k value as the arguments to the random.choices() method that returns a list containing the element from the given list that was chosen at random.
  • Store it in another variable.
  • Print a list containing the element from the given list that was chosen at random.
  • 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 a variable.
gvn_lst = ["good", "morning", "all"]
# Give the weights as a list as static input and store it in another variable.
gvn_weightss = [5, 1, 1]
# Give the k value as static input and store it in another variable.
gvn_k_val = 10
# Pass the given list, weights, k value as the arguments to the random.choices()
# method that returns a list containing the element from the given list that was
# chosen at random.
# Store it in another variable.
rslt = random.choices(gvn_lst, weights=gvn_weightss, k=gvn_k_val)
# Print a list containing the element from the given list that was chosen at random.
print(rslt)

Output:

['good', 'all', 'good', 'good', 'good', 'morning', 'good', 'good', 'good', 'good']

Explanation:

Return a list containing 10 items.
The list should contain a random selection of values from a given list, with
the possibility of selecting "good" being 5 times greater than the other two

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

Approach:

  • Import random module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the weights as a list as user input using list(),map(),input(),and split() functions and store it in another variable.
  • Give the k value as user input using the int(input()) function and store it in another variable.
  • Pass the given list, weights, k value as the arguments to the random.choices() method that returns a list containing the element from the given list that was chosen at random.
  • Store it in another variable.
  • Print a list containing the element from the given list that was chosen at random.
  • 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.
# Store it in a variable.
gvn_lst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the weights as a list as user input using list(),map(),input(),and split() 
# functions and store it in another variable.
gvn_weightss =  list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the k value user input using the int(input()) function and store it in another variable.
gvn_k_val = int(input("Enter some random number = "))
# Pass the given list, weights, k value as the arguments to the random.choices()
# method that returns a list containing the element from the given list that was
# chosen at random.
# Store it in another variable.
rslt = random.choices(gvn_lst, weights=gvn_weightss, k=gvn_k_val)
# Print a list containing the element from the given list that was chosen at random.
print(rslt)

Output:

Enter some random List Elements separated by spaces = 1 2 3
Enter some random List Elements separated by spaces = 1 1 3
Enter some random number = 12
[2, 1, 3, 3, 3, 2, 3, 3, 3, 2, 2, 3]

Explanation:

Return a list containing 12 items.
The list should contain a random selection of values from a given list, with 
the possibility of selecting "3" being 3 times greater than the other two

Python Random choices() Method with Examples Read More »

Python Random triangular() Method with Examples

Random triangular() Method in Python:

The triangular() method returns a random floating number between the two specified numbers (both included), but a third parameter, the mode parameter, can also be specified.

The mode parameter allows you to weigh the possible outcomes in relation to one of the other two parameter values.

The mode parameter is set to the midpoint between the other two parameter values, and it does not weigh the possible outcomes in any direction.

Syntax:

random.triangular(low, high, mode)

Parameters

low: This is Optional. A number indicating the lowest possible outcome.
0 is the default.

high: This is Optional. A number indicating the highest possible outcome.
1 is the default.

mode: This is Optional. A number that is used to weigh the outcome in any direction.
Set the default value to the midpoint between the low and high values.

Examples:

Example1:

Input:

Given first number = 10
Given second number = 40
Given mode = 15

Output:

The random floating-point number between 10 and 40 = 16.45838431286139

Example2:

Input:

Given first number = 5
Given second number = 15
Given mode = 8

Output:

Enter some random number = 5
Enter some random number = 15
Enter some random number = 8
The random floating-point number between 5 and 15 = 6.479018408138248

Random triangular() Method with Examples in Python

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

Approach:

  • Import random module using the import keyword.
  • Give the number(low value) as static input and store it in a variable.
  • Give the other number(high value) as static input and store it in another variable.
  • Give the mode value as static input and store it in another variable.
  • Pass the given low, high, mode values as the arguments to the random.triangular() method that returns a random floating number between the given two specified numbers (both included).
  • Store it in another variable.
  • Print a random floating-point number between the given two numbers (both included).
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(low value) as static input and store it in a variable.
gvn_fstnum = 10
# Give the other number(high value) as static input and store it in
# another variable.
gvn_scndnum = 40
# Give the mode value as static input and store it in another variable.
gvn_mode = 15
# Pass the given low, high, mode values as the arguments to the random.triangular()
# method that returns a random floating number between the given two specified
# numbers (both included).
# Store it in another variable.
rslt = random.triangular(gvn_fstnum, gvn_scndnum, gvn_mode)
# Print a random floating-point number between the two numbers (both included).
print("The random floating-point number between",
      gvn_fstnum, "and", gvn_scndnum, "=", rslt)

Output:

The random floating-point number between 10 and 40 = 16.45838431286139

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

Approach:

  • Import random module using the import keyword.
  • Give the number(low value) as user input using the int(input()) function and store it in a variable.
  • Give the other number(high value) as user input using the int(input()) function and store it in another variable.
  • Give the mode value as user input using the int(input()) function and store it in another variable.
  • Pass the given low, high, mode values as the arguments to the random.triangular() method that returns a random floating number between the given two specified numbers (both included).
  • Store it in another variable.
  • Print a random floating-point number between the given two numbers (both included).
  • The Exit of the Program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number(low value) as user input using the int(input()) function 
# and store it in a variable.
gvn_fstnum = int(input("Enter some random number = "))
# Give the other number(high value) as user input using the int(input()) function
# and store it in another variable.
gvn_scndnum = int(input("Enter some random number = "))
# Give the mode value as user input using the int(input()) function and 
# store it in another variable.
gvn_mode = int(input("Enter some random number = "))
# Pass the given low, high, mode values as the arguments to the random.triangular()
# method that returns a random floating number between the given two specified
# numbers (both included).
# Store it in another variable.
rslt = random.triangular(gvn_fstnum, gvn_scndnum, gvn_mode)
# Print a random floating-point number between the two numbers (both included).
print("The random floating-point number between",
      gvn_fstnum, "and", gvn_scndnum, "=", rslt)

Output:

Enter some random number = 5
Enter some random number = 15
Enter some random number = 8
The random floating-point number between 5 and 15 = 6.479018408138248

Python Random triangular() Method with Examples Read More »

Python delattr() Function with Examples

delattr() Function in Python:

The delattr() function removes the specified attribute from the given object.

In Python, there is another operator that performs the same function as the delattr() method and that is the

del operator.

del operator versus delattr () function:

Dynamic deletion: The del function is more explicit and efficient, and the delattr() function allows for dynamic attribute deletion.

Speed: When the programs are considered and executed, there is a slight difference in execution speed. Depending on the machine, del is slightly faster than delattr().

byte-code Instructions: del uses fewer byte-code instructions than delattr ().

So we conclude the comparison by saying that del is slightly faster than delattr, but delattr() has an advantage when it comes to dynamic deletion of attributes, which the del operator does not support.

Syntax:

delattr(object, attribute)

Parameters

object: This is Required. It is an object.

attribute: This is Required. The name of the attribute to be removed

Return Value:

delattr() does not return any outcome (returns None). It only deletes one attribute (if the object allows it).

delattr() Function with Examples in Python

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

Approach:

  • Create a class to say Employdetails.
  • Take a variable and initialize it with some random number(id).
  • Take another variable and initialize it with some random name(ename).
  • Take another variable and initialize it with some random job role(jobrole).
  • Create an object for the given class and store it in a variable.
  • Print the value of the attribute by using the above-declared object.
  • Pass the above class name and attribute name to the delattr() function to delete a given attribute from the class.
  • Print the value of the attribute by using the above-declared object after deleting.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employdetails.
class Employdetails:
    # Take a variable and initialize it with some random number(id).
    id = 10
    # Take another variable and initialize it with some random name(ename).
    ename = 'virat'
    # Take another variable and initialize it with some random jobrole(jobrole).
    jobrole = 'developer'


# Create an object for the given class and store it in a variable.
classobj = Employdetails()
# Print the value of the attribute by using the above declared object.
print("The attribute is :",classobj.ename)
# Pass the above class name and attribute name to the delattr() function to delete
# given attribute from the class.
delattr(Employdetails, 'ename')
# Print the value of the attribute by using the above declared object after deleting.
print("The given attribute after deleting from class = ",classobj.ename)

Output:

The attribute is : virat
Traceback (most recent call last):
File "jdoodle.py", line 19, in <module>
print("The given attribute after deleting from class = ",classobj.ename)
AttributeError: 'Employdetails' object has no attribute 'ename'

Explanation:

Here first it prints the given attribute 'ename'.
Then delete that attribute from the class 'Employdetails'.
Again try to print the given attribute 'ename'.
Now, it raises an error since the attribute 'ename' got deleted from it.

 

Python delattr() Function with Examples Read More »

Python bytearray() Function with Examples

bytearray() Function in Python:

The function bytearray() returns a bytearray object.

It can either convert objects to bytearray objects or create an empty bytearray object of the specified size.

The source parameter can be used to initialize the byte array in a variety of ways, including:

String: str. encode() is used to convert the string to bytes () Encoding and, optionally, errors must also be provided.

Integer: Creates an array of the specified size, with all elements set to null.

Object: The object’s read-only buffer will be used to initialize the byte array.

Iterable: Creates an array with the same size as the iterable count and initialized with the iterable elements. It must be iterable over integers between 0 <= x < 256

No source(arguments): Makes a 0-dimensional array.

Syntax:

bytearray(x, encoding, error)

Parameters

x: When creating the bytearray object, this is the source that will be used. If it is an integer, it will create an empty bytearray object of the specified size.

If it’s a String, make sure to specify the source’s encoding.

encoding: It is the string’s encoding

error: Specifies what should happen if the encoding fails.

Return Value: 

The bytearray() method returns a bytearray of the specified size and initialization values.

Examples:

Example1:

Input:

Given Number = 5

Output:

The bytearray object of the given number 5 = bytearray(b'\x00\x00\x00\x00\x00')

Example2:

Input:

Given String = "good morning btechgeeks"
# string with 'utf-8' encoding

Output:

The bytearray object of the given string =  bytearray(b'good morning btechgeeks')

bytearray() Function with Examples in Python

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

Approach:

  • Give the number as static input and store it in a variable.
  • Pass the given number as an argument to the bytearray() method that returns a bytearray object of the given number.
  • Store it in another variable.
  • Print the bytearray object of the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 5
# Pass the given number as an argument to the bytearray() method that returns
# a bytearray object of the given number.
# Store it in another variable.
rslt = bytearray(gvn_numb)
# Print the bytearray object of the given number. 
print("The bytearray object of the given number", gvn_numb, "=", rslt)

Output:

The bytearray object of the given number 5 = bytearray(b'\x00\x00\x00\x00\x00')
For Strings

Approach:

  • Give the string as static input and store it in a variable.
  • Pass the given string, ‘utf-8’ as the arguments to the bytearray() method that returns a bytearray object of the given string.
  • Store it in another variable.
  • Print the bytearray object of the given string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "good morning btechgeeks"
# Pass the given string, 'utf-8' as the arguments to the bytearray() method
# that returns a bytearray object of the given string.
# string with 'utf-8' encoding
# Store it in another variable.
rslt = bytearray(gvn_str, 'utf-8')
# Print the bytearray object of the given string. 
print("The bytearray object of the given string = ", rslt)

Output:

The bytearray object of the given string =  bytearray(b'good morning btechgeeks')
For Lists

Similarly, do the same for the list

gvn_lst = [1, 4, 7, 6]
rslt = bytearray(gvn_lst)
print("The bytearray object of the given gvn_lst = ", rslt)

Output:

The bytearray object of the given gvn_lst =  bytearray(b'\x01\x04\x07\x06')

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

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Pass the given number as an argument to the bytearray() method that returns a bytearray object of the given number.
  • Store it in another variable.
  • Print the bytearray object of the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Pass the given number as an argument to the bytearray() method that returns
# a bytearray object of the given number.
# Store it in another variable.
rslt = bytearray(gvn_numb)
# Print the bytearray object of the given number. 
print("The bytearray object of the given number", gvn_numb, "=", rslt)

Output:

Enter some random number = 3
The bytearray object of the given number 3 = bytearray(b'\x00\x00\x00')
For Strings

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Pass the given string, ‘utf-8’ as the arguments to the bytearray() method that returns a bytearray object of the given string.
  • Store it in another variable.
  • Print the bytearray object of the given string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str =input("Enter some random string = ")
# Pass the given string, 'utf-8' as the arguments to the bytearray() method
# that returns a bytearray object of the given string.
# string with 'utf-8' encoding
# Store it in another variable.
rslt = bytearray(gvn_str, 'utf-8')
# Print the bytearray object of the given string. 
print("The bytearray object of the given string = ", rslt)

Output:

Enter some random string = hello all
The bytearray object of the given string = bytearray(b'hello all')

Python bytearray() Function with Examples Read More »

Python dict() Function with Examples

dict() Function in Python:

The dict() function is used to create a dictionary.

A dictionary is an unordered, changeable, and indexed collection.

Syntax:

dict(keyword arguments)

Parameters

keyword arguments: This is Required. You can use as many keyword arguments as you want, separated by a comma: key = value, key = value…

Return Value:

dict() does not return any results (returns None).

Examples:

Example1:

Input:

Given key-value pairs = (emp_name="sunny", emp_id=2122, jobrole="software developer")

Output:

The result dictionary is :
{'emp_name': 'sunny', 'emp_id': 2122, 'jobrole': 'software developer'}

Example2:

Input:

Given key-value pairs = (one="hello", two="good", three="morning")

Output:

The result dictionary is :
{'one': 'hello', 'two': 'good', 'three': 'morning'}

dict() Function with Examples in Python

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

Approach:

  • Pass some random key-value pairs as the arguments to the dict() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Pass some random key-value pairs as the arguments to the dict() function
# and store it in a variable.
rslt = dict(emp_name="sunny", emp_id=2122,  jobrole="software developer")
# Print the above result
print("The result dictionary is :")
print(rslt)

Output:

The result dictionary is :
{'emp_name': 'sunny', 'emp_id': 2122, 'jobrole': 'software developer'}

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

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Print the above-given dictionary.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = dict()
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee
print("The result dictionary is :")
print(gvn_dict)

Output:

Enter some random number of keys of the dictionary = 3
Enter key and value separated by spaces = one hello
Enter key and value separated by spaces = two good
Enter key and value separated by spaces = three morning
The result dictionary is :
{'one': 'hello', 'two': 'good', 'three': 'morning'}

Python dict() Function with Examples Read More »