Author name: Vikram Chiluka

Python Itertools.starmap() 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.starmap() Function:

When an iterable is contained within another iterable and a function must be applied to both of them, starmap() is used. Each element of an iterable within another iterable is treated as a separate item by starmap(). It is comparable to a map (). This function belongs to the category of terminating iterators.

A built-in function, a user-defined function, or even a lambda function can be used.

Syntax:

starmap(function, iterable)

Parameters

function: This is Required. Procedures to be executed on iterable data.

iterable: This is Required. Elements that will be passed to the function.

Examples:

Example1:

Input:

Given List = [(6, 2), (5, 5), (2, 9), (7, 1), (0, 3)]
function: lambda a, b: a + b

Output:

[8, 10, 11, 8, 3]

Example2:

Input:

Given List = [(6, 2), (5, 5), (2, 9), (7, 1), (0, 3)]
function: lambda a, b: a * b

Output:

[12, 25, 18, 7, 0]

Itertools.starmap() Function with Examples in Python

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

1)Using Lambda Function

Approach:

  • Import starmap() function from itertools using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass lambda() function and given list as the arguments to the starmap() function where lambda() function adds the two numbers and store it in another 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 starmap() function from itertools using the import keyword.
from itertools import starmap
# Give the list as static input and store it in a variable.
gvn_lst = [(6, 2), (5, 5), (2, 9), (7, 1), (0, 3)]
# Pass lambda() function and given list as the arguments to the starmap() function
# where lambda() function adds the two numbers and store it in another variable.
rslt = starmap(lambda a, b: a + b, gvn_lst)
# 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(rslt_lst)

Output:

[8, 10, 11, 8, 3]
2)Function Using def

Approach:

  • Import starmap() function from itertools using the import keyword.
  • Create a function say Multiplication which accepts three numbers as arguments and returns the multiplication of three numbers.
  • Inside the function, Return multiplication of given three arguments.
  • Give the list as static input and store it in a variable.
  • Pass the above function(Multiplication) and given list as the arguments to the starmap() function where Multiplication() function multiplies the three numbers and store it in another 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 starmap() function from itertools using the import keyword.
from itertools import starmap
# Create a function say Multiplication which accepts three numbers as arguments and
# returns the multiplication of three numbers


def Multiplication(p, q, r):
    # Return multiplication of given three arguments
    return p*q*r


# Give the list as static input and store it in a variable.
gvn_lst = [(2, 5, 4), (1, 10, 2), (3, 5, 2)]
# Pass the above function(Multiplication) and given list as the arguments to the
# starmap() function where Multiplication() function multiplies the three numbers
# and store it in another variable.
rslt = starmap(Multiplication, gvn_lst)
# 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(rslt_lst)

Output:

[40, 20, 30]

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

Python Itertools.takewhile() 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.takewhile() Function:

This allows you to consider an iterable item until the specified predicate becomes false for the first time. In most cases, the iterable is a list or a string.

It “takes” the element from the sequence “while” the predicate is “true,” as the name implies. This function belongs to the category of “terminating iterators.” The output cannot be used directly and must be converted to another iterable form before it can be used. They are mostly converted into lists.

The predicate can be either a built-in or a user-defined function. Lambda functions can also be used.

General Implementation Format:

def takewhile_function(gvn_predicte, gvn_itrable):
for itr in gvn_itrable:
    if gvn_predicte(itr):
        return(itr)
    else:
        break

Syntax:

takewhile(predicate, iterable)

Parameters

predicate: This is Required. Iterable items are evaluated by the function.

iterable: This is Required. Elements that will be checked over a predicate.

Examples:

Example1:

Input:

Given List =  [3, 7, 6, 4, 5, 8]
function: num % 2 != 0

Output:

[3, 7]

Example2:

Input:

Given string =  "hello123all"
function: character.isalpha()

Output:

h
e
l
l
o

Itertools.takewhile() Function with Examples in Python

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

1)For Lists

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_oddnumbers which accepts the number as an argument and returns True if it is an odd number.
  • Inside the function, Return if the number is odd.
  • Give the list as static input and store it in a variable.
  • Pass the above function(check_oddnumbers) and given list as the arguments to the takewhile() function where check_oddnumbers()  function returns the odd numbers.
  • Store it in another 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 takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_oddnumbers which accepts the number as an argument and
# returns True if it is an odd number


def check_oddnumbers(num):
    # Return if the number is odd.
    return(num % 2 != 0)


# Give the list as static input and store it in a variable.
gvn_lst = [3, 7, 6, 4, 5, 8]
# Pass the above function(check_oddnumbers) and given list as the arguments to the
# takewhile() function where check_oddnumbers() function returns the odd numbers
# and store it in another variable.
rslt = takewhile(check_oddnumbers, gvn_lst)
# 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(rslt_lst)

Output:

[3, 7]
2)For Strings

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_isalpha which accepts the character as an argument and returns True if the character is an alphabet.
  • Inside the function, Return if the argument(character) is an alphabet.
  • Give the string as static input and store it in a variable.
  • Loop using the takewhile() function and for loop by passing the arguments as the above check_isalpha function and given string.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_isalpha which accepts the character as an argument
# and returns True if the character is an alphabet.


def check_isalpha(ch):
    # Return if the argument(character) is an alphabet.
    return(ch.isalpha())


# Give the string as static input and store it in a variable.
gvn_str = "hello1234all"
# Loop using the takewhile() function and for loop by passing the arguments as
# the above check_isalpha function and given string.

for itr in takewhile(check_isalpha, gvn_str):
    # Inside the loop, print the iterator value.
    print(itr)

Output:

h
e
l
l
o

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

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_oddnumbers which accepts the number as an argument and returns True if it is an odd number.
  • Inside the function, Return if the number is odd.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the above function(check_oddnumbers) and given list as the arguments to the takewhile() function where check_oddnumbers()  function returns the odd numbers.
  • Store it in another 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 takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_oddnumbers which accepts the number as an argument and
# returns True if it is an odd number


def check_oddnumbers(num):
    # Return if the number is odd.
    return(num % 2 != 0)


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

# Pass the above function(check_oddnumbers) and given list as the arguments to the
# takewhile() function where check_oddnumbers function returns the odd numbers.
# Store it in another variable.
rslt = takewhile(check_oddnumbers, gvn_lst)
# 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(rslt_lst)

Output:

Enter some random List Elements separated by spaces = 9 7 5 2 8 3
[9, 7, 5]
2)For Strings

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_isalpha which accepts the character as an argument and returns True if the character is an alphabet.
  • Inside the function, Return if the argument(character) is an alphabet.
  • Give the string as user input using the input() function and store it in a variable.
  • Loop using the takewhile() function and for loop by passing the arguments as the above check_isalpha function and given string.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_isalpha which accepts the character as an argument
# and returns True if the character is an alphabet.


def check_isalpha(ch):
    # Return if the character is an alphabet.
    return(ch.isalpha())


# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Loop using the takewhile function and for loop by passing the arguments as
# the above check_isalpha function and given string.

for itr in takewhile(check_isalpha, gvn_str):
    # Inside the loop, print the iterator value.
    print(itr)

Output:

Enter some random string = abc567yiu
a
b
c

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

Python Itertools.tee() 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.tee() Function:

This iterator divides the container into the iterators specified in the argument.

Syntax:

tee(iterator, count)

Parameters

iterator: It is an iterator.

count: It is an integer.

Return Value:

The number of iterators specified in the argument is returned by this method.

Examples:

Example1:

Input:

Given list =  [1, 3, 5, 2, 7]
Given count = 4

Output:

The following iterators : 
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]

Example2:

Input:

Given list = [2, 4,  8,  1,  3]
Given count = 2

Output:

The following iterators : 
[2, 4, 8, 1, 3]
[2, 4, 8, 1, 3]

Itertools.tee() Function with Examples in Python

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

Approach:

  • Import itertools module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Get the iterator of the given list using the iter() function.
  • Store it in a variable.
  • Pass the above iterator and some random count value as the arguments to the itertools.tee() function and store it in another variable.
  • Loop till the given count value using the for loop.
  • Inside the loop, print the list of iterator values of the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools

# Give the list as static input and store it in a variable.
gvn_lst = [1, 3, 5, 2, 7]

# Get the iterator of the given list using the iter() function.
# Store it in a variable.
itertr = iter(gvn_lst)

# Pass the above iterator and some random count value as the arguments to the
# itertools.tee() function and store it in another variable.

# Using tee() function to create a list of iterators results in a given list of
# 4 iterators with the same values.
rslt = itertools.tee(itertr, 4)

# Loop till the given count value using the for loop.
print("The following iterators : ")
for itr in range(0, 4):
    # Print the list of iterator values of the above rslt.
    print(list(rslt[itr]))

Output:

The following iterators : 
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]
[1, 3, 5, 2, 7]

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

Approach:

  • Import 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 count value as user input using the int(input()) function and store it in another variable.
  • Get the iterator of the given list using the iter() function.
  • Store it in a variable.
  • Pass the above iterator and the given count value as the arguments to the itertools.tee() function and store it in another variable.
  • Loop till the given count value using the for loop.
  • Inside the loop, print the list of iterator values of the above result.
  • The Exit of the Program.

Below is the implementation:

# Import itertools module using the import keyword.
import itertools

# 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 count value as user input using the int(input()) function 
# and store it in a variable.
gvn_cnt = int(input("Enter some random number = "))
# Get the iterator of the given list using the iter() function.
# Store it in a variable.
itertr = iter(gvn_lst)

# Pass the above iterator and the given count value as the arguments to the
# itertools.tee() function and store it in another variable.

# Using tee() function to create a list of iterators results in a given list of
# given count number of iterators with the same values.
rslt = itertools.tee(itertr, gvn_cnt)

# Loop till the given count value using the for loop.
print("The following iterators : ")
for itr in range(0, gvn_cnt):
    # Print the list of iterator values of the above rslt.
    print(list(rslt[itr]))

Output:

Enter some random List Elements separated by spaces = 2 4 8 1 3
Enter some random number = 2
The following iterators : 
[2, 4, 8, 1, 3]
[2, 4, 8, 1, 3]

 

 

 

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

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 »