Author name: Vikram Chiluka

Program to Find Common Divisors of Two Numbers

Python Program to Find Common Divisors of Two Numbers

Given two numbers the task is to find the common divisors of the given two numbers in Python.

Using a Python program, we will find the common divisors of two numbers. Integers that divide both numbers correctly are known as common divisors. Here, we will learn what common divisors are, how to find them, and how to use Python to find the common divisors of two numbers.

Examples:

Example1:

Input:

Given First Number =56
Given Second Number =88

Output:

The common divisors of the two numbers { 56 88 } are :
1
2
4
8

Example2:

Input:

Given First Number =105
Given Second Number =85

Output:

Enter some random first number =105
Enter some random second number =85
The common divisors of the two numbers { 105 85 } are :
1
5

Program to Find Common Divisors of Two Numbers in Python

Below are the ways to find the common divisors of the given two numbers in Python.

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Calculate the minimum number among the two numbers using the min() function and store it in a variable.
  • Loop from 1 to minimum number using the For loop.
  • Inside the For loop.
  • Check if the iterator value divides the given two numbers using the If conditional Statement.
  • If it is true then print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
firstnumbe = 56
# Give the second number as static input and store it in another variable.
secondnumbe = 88
# Calculate the minimum number among the two numbers using the min()
# function and store it in a variable.
mininumb = min(firstnumbe, secondnumbe)
print(
    'The common divisors of the two numbers {', firstnumbe, secondnumbe, '} are :')
# Loop from 1 to minimum number using the For loop.
for itrnumb in range(1, mininumb+1):
    # Inside the For loop.
    # Check if the iterator value divides the given two numbers
    # using the If conditional Statement.
    if(firstnumbe % itrnumb == 0 and secondnumbe % itrnumb == 0):
          # If it is true then print the iterator value.
        print(itrnumb)

Output:

The common divisors of the two numbers { 56 88 } are :
1
2
4
8

Method #2: Using For Loop (User Input)

Approach:

  • Give the first number as the user input using the int(input()) function and store it in a variable.
  • Give the second number as the user input using the int(input()) function and store it in another variable.
  • Calculate the minimum number among the two numbers using the min() function and store it in a variable.
  • Loop from 1 to minimum number using the For loop.
  • Inside the For loop.
  • Check if the iterator value divides the given two numbers using the If conditional Statement.
  • If it is true then print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as the user input using the int(input())
# function and store it in a variable.
firstnumbe = int(input('Enter some random first number ='))
# Give the second number as the user input using the int(input())
# function and store it in another variable.
secondnumbe = int(input('Enter some random second number ='))
# Calculate the minimum number among the two numbers using the min()
# function and store it in a variable.
mininumb = min(firstnumbe, secondnumbe)
print(
    'The common divisors of the two numbers {', firstnumbe, secondnumbe, '} are :')
# Loop from 1 to minimum number using the For loop.
for itrnumb in range(1, mininumb+1):
    # Inside the For loop.
    # Check if the iterator value divides the given two numbers
    # using the If conditional Statement.
    if(firstnumbe % itrnumb == 0 and secondnumbe % itrnumb == 0):
          # If it is true then print the iterator value.
        print(itrnumb)

Output:

Enter some random first number =105
Enter some random second number =85
The common divisors of the two numbers { 105 85 } are :
1
5

Related Programs:

Python Program to Find Common Divisors of Two Numbers Read More »

design a program to count numbers that dont contain 3

Design a Program to Count Numbers that don’t Contain 3 in Python

Given the list of numbers, the task is to count the Numbers which doesn’t contain Digit 3 in them.

Examples:

Example1:

Input:

Given list =[125, 94, 32, 138, 349, 5783, 12394297, 975686138, 3589295]

Output:

The Count of numbers that doesnt contain three in the given list [125, 94, 32, 138, 349, 5783, 12394297, 
975686138, 3589295] is [ 2 ]

Example2:

Input:

Given list =[2949, 1358, 927482, 6582913, 19, 24, 123, 56723, 194]

Output:

The Count of numbers that doesnt contain three in the given list [2949, 1358, 927482, 6582913, 19, 24, 123, 
56723, 194] is [ 5 ]

Design a Program to Count Numbers that don’t Contain 3 in Python

Below are the ways to count the Numbers which doesn’t contain Digit 3 in them.

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Take a variable that stores the count of numbers that doesn’t contain digit 3 in them(say cunt)
  • Traverse the given list using For loop.
  • Convert the list element to a string and store it in a variable.
  • Check if this string contains digit 3 in it using not in operator and If statement.
  • If it is true then increment the cunt by 1.
  • Print the cunt value.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
lstnmbs = [2949, 1358, 927482, 6582913, 19, 24, 123, 56723, 194]
# Take a variable that stores the count of numbers
# that doesn't contain digit 3 in them(say cunt)
cunt = 0
# Traverse the given list using For loop.
for numbr in lstnmbs:
    # Convert the list element to a string and store it in a variable.
    strnumbr = str(numbr)
    # Check if this string contains digit 3 in it using not in operator and If statement.
    if '3' not in strnumbr:
        # If it is true then increment the cunt by 1.
        cunt = cunt+1
# Print the cunt value.
print('The Count of numbers that doesnt contain three in the given list',
      lstnmbs, 'is [', cunt, ']')

Output:

The Count of numbers that doesnt contain three in the given list [2949, 1358, 927482, 6582913, 19, 24, 123, 
56723, 194] is [ 5 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Take a variable that stores the count of numbers that doesn’t contain digit 3 in them(say cunt)
  • Traverse the given list using For loop.
  • Convert the list element to a string and store it in a variable.
  • Check if this string contains digit 3 in it using not in operator and If statement.
  • If it is true then increment the cunt by 1.
  • Print the cunt value.
  • The Exit of the program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
lstnmbs = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Take a variable that stores the count of numbers
# that doesn't contain digit 3 in them(say cunt)
cunt = 0
# Traverse the given list using For loop.
for numbr in lstnmbs:
    # Convert the list element to a string and store it in a variable.
    strnumbr = str(numbr)
    # Check if this string contains digit 3 in it using not in operator and If statement.
    if '3' not in strnumbr:
        # If it is true then increment the cunt by 1.
        cunt = cunt+1
# Print the cunt value.
print('The Count of numbers that doesnt contain three in the given list',
      lstnmbs, 'is [', cunt, ']')

Output:

Enter some random List Elements separated by spaces = 125 94 32 138 349 5783 12394297 975686138 3589295
The Count of numbers that doesnt contain three in the given list [125, 94, 32, 138, 349, 5783, 12394297, 975686138, 3589295] is [ 2 ]

Related Programs:

Design a Program to Count Numbers that don’t Contain 3 in Python Read More »

Program to Check whether all Digits of a Number Divide it

Python Program to Check whether all Digits of a Number Divide it

Using a Python program, we will learn how to check whether all of the digits in a number divide it. We’ll divide the given number by each digit to see if it’s divisible. So you’ll learn how to retrieve a number’s individual digits, a method to check whether the number is divisible by its digits, and a Python program to do so.

Examples:

Example1:

Input:

Given Number =144

Output:

The given number [ 144 ] all the digits of the given number divides the given number

Example2:

Input:

Given Number =369

Output:

The given number [ 369 ] all the digits of the given number do not divide the given number

Program to Check whether all Digits of a Number Divide it in Python

Below are the ways to check whether all the digits of the given number divide it using Python

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Create a function checkdivide() which takes the given number as an argument and returns true if all the digits of the given number divide it else it returns false.
  • Pass the given number as an argument to checkdivide() function.
  • Inside the checkdivide() function.
  • Convert the given number into list of digits using list(),map(),int() and split() functions.
  • Loop in this digits list using For loop.
  • Inside the For loop check whether the given number is divisible by the iterator(digit).
  • If it is false then return False.
  • After the end of for loop return True.
  • Check if the functions return true or false using the If conditional Statement.
  • If it is true then print all the digits of the given number divides the given number.
  • Else print all the digits of the given number do not divide the given number.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkdivide() which takes the given number
# as an argument and returns true if all the digits of the given number
# divide it else it returns false.


def checkdivide(gvnnumb):
    # Inside the checkdivide() function.
    # Convert the given number into list of digits
    # using list(),map(),int() and split() functions.
    digitslstt = list(map(int, str(gvnnumb)))
    # Loop in this digits list using For loop.
    for digt in digitslstt:
        # Inside the For loop check whether the given number
        # is divisible by the iterator(digit).
        # If it is false then return False.
        if(gvnnumb % digt != 0):
            return False
    # After the end of for loop return True.
    return True


# Give the number as static input and store it in a variable.
numb = 144

# Pass the given number as an argument to checkdivide() function.
# Check if the functions return true or false using the If conditional Statement.
if(checkdivide(numb)):
        # If it is true then print all the digits of
        # the given number divides the given number.
    print('The given number [', numb,
          '] all the digits of the given number divides the given number')
# Else print all the digits of the given number do not divide the given number.
else:
    print('The given number [', numb,
          '] all the digits of the given number do not divide the given number')

Output:

The given number [ 144 ] all the digits of the given number divides the given number

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Create a function checkdivide() which takes the given number as an argument and returns true if all the digits of the given number divide it else it returns false.
  • Pass the given number as an argument to checkdivide() function.
  • Inside the checkdivide() function.
  • Convert the given number into list of digits using list(),map(),int() and split() functions.
  • Loop in this digits list using For loop.
  • Inside the For loop check whether the given number is divisible by the iterator(digit).
  • If it is false then return False.
  • After the end of for loop return True.
  • Check if the functions return true or false using the If conditional Statement.
  • If it is true then print all the digits of the given number divides the given number.
  • Else print all the digits of the given number do not divide the given number.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkdivide() which takes the given number
# as an argument and returns true if all the digits of the given number
# divide it else it returns false.


def checkdivide(gvnnumb):
    # Inside the checkdivide() function.
    # Convert the given number into list of digits
    # using list(),map(),int() and split() functions.
    digitslstt = list(map(int, str(gvnnumb)))
    # Loop in this digits list using For loop.
    for digt in digitslstt:
        # Inside the For loop check whether the given number
        # is divisible by the iterator(digit).
        # If it is false then return False.
        if(gvnnumb % digt != 0):
            return False
    # After the end of for loop return True.
    return True


# Give the number as user input using the int(input()) function
# and store it in a variable.
numb = int(input('Enter some random number = '))

# Pass the given number as an argument to checkdivide() function.
# Check if the functions return true or false using the If conditional Statement.
if(checkdivide(numb)):
        # If it is true then print all the digits of
        # the given number divides the given number.
    print('The given number [', numb,
          '] all the digits of the given number divides the given number')
# Else print all the digits of the given number do not divide the given number.
else:
    print('The given number [', numb,
          '] all the digits of the given number do not divide the given number')

Output:

Enter some random number = 369
The given number [ 369 ] all the digits of the given number do not divide the given number

The digit 6 does not divide the given number so it returns False.
Related Programs:

Python Program to Check whether all Digits of a Number Divide it Read More »

Program to Find the Least Frequent Character in a String

Python Program to Find the Least Frequent Character in a String

Give the string the task is to print the least frequent character in a string in Python.

Examples:

Example1:

Input:

Given string =zzzyyddddeeeee

Output:

The least frequency character in the given string zzzyyddddeeeee is [ y ]

Example2:

Input:

Given string =btechgeeks

Output:

The least frequency character in the given string btechgeeks is [ b ]

Program to Find the Least Frequent Character in a String in Python

Below are the ways to print the least frequent character in a string in Python.

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Method #1: Using Counter() (Hashing , Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string a static input and store it in a variable.
  • Calculate the frequency of all the given string elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say elementsfrequency)
  • Calculate the minimum frequency character in the given string using the min() and “get” function and store it in a variable.
  • Print the least frequency character in the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the string a static input and store it in a variable.
gvnstrng = 'zzzyyddddeeeee'
# Calculate the frequency of all the given string elements
# using the Counter() function which returns the element
# and its frequency as key-value pair and store this
# dictionary in a variable(say elementsfrequency)
elementsfrequency = Counter(gvnstrng)
# Calculate the minimum frequency character in the given string
# using the min() and "get" function and store it in a variable.
minfreqchar = str(min(elementsfrequency, key=elementsfrequency.get))
# Print the least frequency character in the given string
# by printing the above variable.
print('The least frequency character in the given string',
      gvnstrng, 'is [', minfreqchar, ']')

Output:

The least frequency character in the given string zzzyyddddeeeee is [ y ]

Method #2: Using Counter() (Hashing , User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string a user input using the input() function and store it in a variable.
  • Calculate the frequency of all the given string elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say elementsfrequency)
  • Calculate the minimum frequency character in the given string using the min() and “get” function and store it in a variable.
  • Print the least frequency character in the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the string a static input and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Calculate the frequency of all the given string elements
# using the Counter() function which returns the element
# and its frequency as key-value pair and store this
# dictionary in a variable(say elementsfrequency)
elementsfrequency = Counter(gvnstrng)
# Calculate the minimum frequency character in the given string
# using the min() and "get" function and store it in a variable.
minfreqchar = str(min(elementsfrequency, key=elementsfrequency.get))
# Print the least frequency character in the given string
# by printing the above variable.
print('The least frequency character in the given string',
      gvnstrng, 'is [', minfreqchar, ']')

Output:

Enter some random string = btechgeeks
The least frequency character in the given string btechgeeks is [ b ]

Related Programs:

Python Program to Find the Least Frequent Character in a String Read More »

Program to Find Smallest Prime Divisor of a Number

Python Program to Find Smallest Prime Divisor of a Number

Prime Divisor:

The prime divisor of a polynomial is a non-constant integer that is divisible by the prime and is known as the prime divisor.

Some prime divisors are 2 , 3 , 5 ,7 , 11 ,13 ,17 ,19 and 23 etc.

Divisors can be both positive and negative in character. A divisor is an integer and its negation.

Given a number, the task is to print the smallest divisor of the given number in Python.

Examples:

Example1:

Input:

Given number =91

Output:

The smallest prime divisor the number [ 91 ] is [ 7 ]

Example2:

Input:

Given number =240

Output:

The smallest prime divisor the number [ 240 ] is [ 2 ]

Program to Find Smallest Prime Divisor of a Number in Python

Below are the ways to print the smallest divisor of the given number in Python.

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take an empty list and initialize it’s with an empty list using list() and [].
  • Loop from 2 to the given number using the For loop.
  • Check if the iterator value divides the given number using the % operator and the If statement.
  • If It is true then append it to the list.
  • Print the first element of the list using the index 0.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 91
# Take an empty list and initialize it's with an empty list using list() and [].
nwlist = []
# Loop from 2 to the given number using the For loop.
for m in range(2, numb+1):
        # Check if the iterator value divides the given number
    # using the % operator and the If statement.
    if(numb % m == 0):
        # If It is true then append it to the list.
        nwlist.append(m)
smalldivisor = nwlist[0]
# Print the first element of the list using the index 0.
print(
    'The smallest prime divisor the number [', numb, '] is [', smalldivisor, ']')

Output:

The smallest prime divisor the number [ 91 ] is [ 7 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take an empty list and initialize it’s with an empty list using list() and [].
  • Loop from 2 to the given number using the For loop.
  • Check if the iterator value divides the given number using the % operator and the If statement.
  • If It is true then append it to the list.
  • Print the first element of the list using the index 0.
  • 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.
numb = int(input('Enter some random number ='))
# Take an empty list and initialize it's with an empty list using list() and [].
nwlist = []
# Loop from 2 to the given number using the For loop.
for m in range(2, numb+1):
        # Check if the iterator value divides the given number
    # using the % operator and the If statement.
    if(numb % m == 0):
        # If It is true then append it to the list.
        nwlist.append(m)
smalldivisor = nwlist[0]
# Print the first element of the list using the index 0.
print(
    'The smallest prime divisor the number [', numb, '] is [', smalldivisor, ']')

Output:

Enter some random number =240
The smallest prime divisor the number [ 240 ] is [ 2 ]

Related Programs:

Python Program to Find Smallest Prime Divisor of a Number Read More »

Program to Print First k Digits of 1N where N is a Positive Integer

Python Program to Print First k Digits of 1/N where N is a Positive Integer

Given the numbers N and K, the task is to print the first K Digits of 1/N in Python.

Examples:

Example1:

Input:

Given numb=9
Given k=3

Output:

The first [3] digits in the given number [ 9 ] is :111

Example2:

Input:

Given numb=1
Given k=7

Output:

The first [7] digits in the given number [ 1 ] is :00000001

Program to Print First k Digits of 1/N where N is a Positive Integer in Python

Below are the ways to print the first K Digits of 1/N in Python.

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Algorithm:

Initially, enter the user’s n-th number. Then enter the number k, which represents the number of digits. You will now know how to develop the code so that it writes the first k digits to the output after receiving inputs. So we use to divide and multiply in the code. We divide 1 by n and get a floating number less than 1. Then we multiply k by 10 and then multiply by that floating number before converting the complete result to an integer and printing that integer to get the first k digits of 1/n.

If n is equal to 1, this will not work since 1/1 is no longer a floating number, and we are not going to convert y into an integer because it is already an integer, but we are going to convert it into a string and reverse that string. That string should be printed.

Method #1: Using If Statement (Static Input)

Approach:

  • GIve the numbers n and k as static input and store them in two separate variables.
  • Calculate the value of 1/n and store it in a variable say divval.
  • Calculate the value of 10 power k using the ** operator and store it in a variable say powerval.
  • Calculate the integer value of the product of divval and powerval and store it in another variable say resval.
  • Check if the value of n is equal to 1 or not using the If conditional Statement.
  • Convert the resval to string using the str() function and store it in the same variable.
  • Print the resval in reverse order using slicing.
  • If the “IF” conditional statement is false then print the value of resval.
  • The Exit of the Program.

Below is the implementation:

# GIve the numbers n and k as static input and store them in two separate variables.
numb = 9
k = 3
# Calculate the value of 1/n and store it in a variable say divval.
divval = 1/numb
# Calculate the value of 10 power k using the ** operator
# and store it in a variable say powerval.
powerval = 10**k
# Calculate the integer value of the product of divval and powerval
# and store it in another variable say resval.
resval = int(divval*powerval)
# Check if the value of n is equal to 1 or not
# using the If conditional Statement.
if(numb == 1):
        # Convert the resval to string using the str() function
    # and store it in the same variable.
    resval = str(resval)
    # Print the resval in reverse order using slicing.
    print("The first ["+str(k)+"] digits in the given number [ " +
          str(numb)+" ] is :"+str(resval[::-1]))
# If the "IF" conditional statement is false then print the value of resval.
else:
    print("The first ["+str(k)+"] digits in the given number [ " +
          str(numb)+" ] is :"+str(resval))

Output:

The first [3] digits in the given number [ 9 ] is :111

Method #2: Using If Statement (User Input)

Approach:

  • GIve the numbers n and k as user input using map(),int(),split() functions.
  • Store them in two separate variables.
  • Calculate the value of 1/n and store it in a variable say divval.
  • Calculate the value of 10 power k using the ** operator and store it in a variable say powerval.
  • Calculate the integer value of the product of divval and powerval and store it in another variable say resval.
  • Check if the value of n is equal to 1 or not using the If conditional Statement.
  • Convert the resval to string using the str() function and store it in the same variable.
  • Print the resval in reverse order using slicing.
  • If the “IF” conditional statement is false then print the value of resval.
  • The Exit of the Program.

Below is the implementation:

# GIve the numbers n and k as user input using map(),int(),split() functions.
# Store them in two separate variables.
numb, k = map(int, input(
    'Enter some random values of numb and k separated by spaces = ').split())
# Calculate the value of 1/n and store it in a variable say divval.
divval = 1/numb
# Calculate the value of 10 power k using the ** operator
# and store it in a variable say powerval.
powerval = 10**k
# Calculate the integer value of the product of divval and powerval
# and store it in another variable say resval.
resval = int(divval*powerval)
# Check if the value of n is equal to 1 or not
# using the If conditional Statement.
if(numb == 1):
        # Convert the resval to string using the str() function
    # and store it in the same variable.
    resval = str(resval)
    # Print the resval in reverse order using slicing.
    print("The first ["+str(k)+"] digits in the given number [ " +
          str(numb)+" ] is :"+str(resval[::-1]))
# If the "IF" conditional statement is false then print the value of resval.
else:
    print("The first ["+str(k)+"] digits in the given number [ " +
          str(numb)+" ] is :"+str(resval))

Output:

Enter some random values of numb and k separated by spaces = 1 7
The first [7] digits in the given number [ 1 ] is :00000001

Related Programs:

Python Program to Print First k Digits of 1/N where N is a Positive Integer Read More »

Program to Rearrange the given Number to form the Smallest Number

Python Program to Rearrange the given Number to form the Smallest Number

In Python, we will write a program that will rearrange the digits of a given number to produce the smallest possible number. We will rearrange the number so that it creates the smallest possible number with the number and the number digits being the same as the given number.

Examples:

Example1:

Input:

Given number =17831047264891

Output:

The smallest number that can be formed from 17831047264891 is [ 10112344677889 ]

Example2:

Input:

Given number =4851381128859729830005768

Output:

The smallest number that can be formed from 4851381128859729830005768 is [ 1000112233455567788888899 ]

Program to Rearrange the given Number to form the Smallest Number

Below are the ways to rearrange the given Number to form the smallest Number in Python.

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Method #1: Using Sorting (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number to a string and sort it.
  • After sorting join it using the join() function.
  • Count the number of 0’s present in this number using the count() function and store it in a variable say m.
  • Convert the given number to a list of digits using the list() function.
  • Swap the first index digit and mth index digit in the list using ‘,’ operator.
  • Join the list into the string using the join() function.
  • Print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 17831047264891
# Convert the given number to a string and sort it.
strnumb = str(numb)
strnumb = sorted(strnumb)
# After sorting join it using the join() function.
sortednumb = ''.join(strnumb)
# Count the number of 0's present in this number
# using the count() function and store it in a variable say m.
m = sortednumb.count('0')
# Convert the given number to a list of digits using the list() function.
numbdigi = list(sortednumb)
# Swap the first index digit and mth index digit in the list using ',' operator.
numbdigi[0], numbdigi[m] = numbdigi[m], numbdigi[0]
# Join the list into the string using the join() function.
finalres = ''.join(numbdigi)
# Print the result
print('The smallest number that can be formed from',
      numb, 'is [', finalres, ']')

Output:

The smallest number that can be formed from 17831047264891 is [ 10112344677889 ]

Method #2: Using Sorting (User Input)

Approach:

  • Give the number as user input using int(input()) and store it in a variable.
  • Convert the given number to a string and sort it.
  • After sorting join it using the join() function.
  • Count the number of 0’s present in this number using the count() function and store it in a variable say m.
  • Convert the given number to a list of digits using the list() function.
  • Swap the first index digit and mth index digit in the list using ‘,’ operator.
  • Join the list into the string using the join() function.
  • Print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using int(input()) and store it in a variable.
numb = int(input('Enter some random number = '))
# Convert the given number to a string and sort it.
strnumb = str(numb)
strnumb = sorted(strnumb)
# After sorting join it using the join() function.
sortednumb = ''.join(strnumb)
# Count the number of 0's present in this number
# using the count() function and store it in a variable say m.
m = sortednumb.count('0')
# Convert the given number to a list of digits using the list() function.
numbdigi = list(sortednumb)
# Swap the first index digit and mth index digit in the list using ',' operator.
numbdigi[0], numbdigi[m] = numbdigi[m], numbdigi[0]
# Join the list into the string using the join() function.
finalres = ''.join(numbdigi)
# Print the result
print('The smallest number that can be formed from',
      numb, 'is [', finalres, ']')

Output:

Enter some random number = 4851381128859729830005768
The smallest number that can be formed from 4851381128859729830005768 is [ 1000112233455567788888899 ]

Time Complexity: O(N log N) where N is the number len of the number.
Related Programs:

Python Program to Rearrange the given Number to form the Smallest Number Read More »

Program to Merge Two Lists and Sort it

Python Program to Merge Two Lists and Sort it | How to Create a Sorted Merged List of Two Unsorted Lists in Python?

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

There are many instances in our programming where we need to merge two unsorted lists and we might feel it difficult to write a program. If so, you need not worry anymore as we have discussed all on how to create a sorted merged list from two unsorted lists in python, methods for merging two lists and sorting them. In this Tutorial covers Each and every method for combining two unsorted lists and then how to obtain the sorted list considering enough examples.

Lists in Python

A list is exactly what it sounds like: a container for various Python objects such as integers, words, values, and so on. In other programming languages, it is equal to an array. It is denoted with square brackets (and this is one of the attributes that differentiates it from tuples, which are separated by parentheses). It is also mutable, which means it can be changed or altered, as opposed to tuples, which are immutable.

Given two lists the task is to merge the two given lists and sort them in Python

Combining Two Unsorted Lists and then Sort them Examples

String List:

Example 1:

Input:

given list one = ['hello', 'this', 'is', 'BTechGeeks']
given list two = ['online', 'platform', 'for', 'coding', 'students']

Output:

printing the merged list after sorting them = 
['BTechGeeks', 'coding', 'for', 'hello', 'is', 'online', 'platform', 'students', 'this']

Integer List:

Example 2

Input:

given list one = [17, 11, 13, 9, 8, 22, 29]
given list two = [3, 23, 29, 11, 98, 23, 15, 34, 37, 43, 47]

Output:

printing the merged list after sorting them = 
[3, 8, 9, 11, 11, 13, 15, 17, 22, 23, 23, 29, 29, 34, 37, 43, 47, 98]

How to Merge Two Lists in Python and Sort it?

There are several ways to merge the two given lists and sort them some of them are. This tutorial can be helpful while you are dealing with multiple lists. + Operator is used to merge and then sort them by defining a method called the sort method. You can check the examples for python programs in both cases be it static input or user input and how it gets the sorted list.

  • Using + operator and sort() function (Static Input)
  • Using + operator and sort() function (User Input)

Method #1: Using + operator and sort() function(Static Input)

Approach:

  • Give two lists input as static and store them in two separate variables.
  • Using the ‘+’ operator, merge both the first list and the second list, store it in a variable.
  • Sort the lists using the sort() function.
  • Print the list after sorting them.
  • The exit of Program.

i)String List

Write a Program to Merge Two Lists and Sort them on giving Static Input in Python?

# given first list
given_list1 = ['hello', 'this', 'is', 'BTechGeeks']
# given second list
given_list2 = ['online', 'platform', 'for', 'coding', 'students']
# merging both lists and storing it in a variable
mergedList = given_list1+given_list2
# sorting the merged list using sort() function
mergedList.sort()

# printing the merged list after sorting them
print('printing the merged list after sorting them = ')
print(mergedList)

Python Program to Merge Two Lists and Sort them(Static Input)

Output:

printing the merged list after sorting them = 
['BTechGeeks', 'coding', 'for', 'hello', 'is', 'online', 'platform', 'students', 'this']

ii)Integer List

Below is the implementation:

# given first list
given_list1 = [17, 11, 13, 9, 8, 22, 29]
# given second list
given_list2 = [3, 23, 29, 11, 98, 23, 15, 34, 37, 43, 47]
# merging both lists and storing it in a variable
mergedList = given_list1+given_list2
# sorting the merged list using sort() function
mergedList.sort()

# printing the merged list after sorting them
print('printing the merged list after sorting them = ')
print(mergedList)

Output:

printing the merged list after sorting them = 
[3, 8, 9, 11, 11, 13, 15, 17, 22, 23, 23, 29, 29, 34, 37, 43, 47, 98]

Method #2: Using + operator and sort() function (User Input)

Approach:

  • Scan the two lists using user input functions.
  • Using ‘+’ operator, merge both the first list, the second list and store them in a variable.
  • Sort the lists using the sort() function.
  • Print the sorted list.
  • The exit of Program.

i)String List

Scan the list using split() ,input() and list() functions.

Write a python program to merge two lists and sort it take input from the user and display the sorted merged list?

Below is the implementation to merge two lists and sort them

# scanning the first string list using split() and input() functions
given_list1 = list(input(
    'Enter some random string elements in list one separated by spaces = ').split())
# scanning the second string list using split() and input() functions
given_list2 = list(input(
    'Enter some random string elements in list one separated by spaces = ').split())
# merging both lists and storing it in a variable
mergedList = given_list1+given_list2
# sortin the merged list using sort() function
mergedList.sort()

# printing the merged list after sorting them
print('printing the merged list after sorting them = ')
print(mergedList)

Python Program to Merge Two Lists and Sort them(User Input)

Output:

Enter some random string elements in list one separated by spaces = hello this is btechgeeks
Enter some random string elements in list one separated by spaces = online coding platoform for coding students
printing the merged list after sorting them = 
['btechgeeks', 'coding', 'coding', 'for', 'hello', 'is', 'online', 'platoform', 'students', 'this']

ii)Integer List

Scan the list using split() ,map(),input() and list() functions.

map() function converts the every string element in the given list to integer.

Below is the implementation:

# scanning the first string list using split() and input() functions
given_list1 = list(map(int,input(
    'Enter some random string elements in list one separated by spaces = ').split()))
# scanning the second string list using split() and input() functions
given_list2 = list(map(int,input(
    'Enter some random string elements in list one separated by spaces = ').split()))
# merging both lists and storing it in a variable
mergedList = given_list1+given_list2
# sorting the merged list using sort() function
mergedList.sort()

# printing the merged list after sorting them
print('printing the merged list after sorting them = ')
print(mergedList)

Output:

Enter some random string elements in list one separated by spaces = 48 79 23 15 48 19 7 3 5 4 2 98 75 123 456 81 8 5
Enter some random string elements in list one separated by spaces = 1 3 5 11 58 23 97 17 19 23 29 75 36 43
printing the merged list after sorting them = 
[1, 2, 3, 3, 4, 5, 5, 5, 7, 8, 11, 15, 17, 19, 19, 23, 23, 23, 29, 36, 43, 48, 48, 58, 75, 75, 79, 81, 97, 98, 123, 456]

Similar Tutorials:

Python Program to Merge Two Lists and Sort it | How to Create a Sorted Merged List of Two Unsorted Lists in Python? Read More »

Program to Find Digital Root of Large Integers using Recursion.

Python Program to Find Digital Root of Large Integers using Recursion

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Given a very large number N, the task is to find the Digital Root of large Integers using Recursion in Python.

Examples:

Example1:

Input:

Given Large Number =64829048194591378492648546725

Output:

The Digital root of the given number 64829048194591378492648546725 is [ 6 ]

Example2:

Input:

Given Large Number =587199248368256143942

Output:

The Digital root of the given number 587199248368256143942 is [ 7 ]

Program to Find Digital Root of Large Integers using Recursion in Python

Below are the ways to find the Digital root of large Integers using Recursion in Python.

The digital root of an integer can be determined by adding all of the digits of a given integer until only one digit remains. The digital root of the provided number is this single-digit integer. If the sum of all the digits of a given integer yields a two or three-digit integer, repeat the sum until only a single-digit integer remains.

Method #1: Using Recursion (Static Input)

Approach:

Give the number(Very Large) as static input and store it in a variable.

Create a function digitalRootRecursion which accepts the given number as an argument and returns the digital root of the given number.

Pass the given number as an argument to digitalRootRecursion() function.

Then determine whether the integer is greater than or less than 10. If the integer is less than 10, return the number immediately and terminate the function. If the number is higher than 10, use the above function to recursively compute the sum of the digits of the given integer.

The method will be repeated until we obtain the sum of all the digits of the specified integer. Then, by comparing our final number to 10, we may determine if it is a single digit or not. If the number is a single digit, it should be returned. The number returned is our digital root. If the number is not a single digit, repeat the operation until only a single digit remains.

So, using Recursion in Python, we can get the digital root of huge integers using this approach.

Print the Digital Root.

The Exit of the Program.

Below is the implementation:

# Create a function digitalRootRecursion which accepts the given number as an argument
# and returns the digital root of the given number.


def digitalRootRecursion(largenumbr):
    # Then determine whether the integer is greater than or less than 10.
    # If the integer is less than 10, return the number immediately
    # and terminate the function
    if(largenumbr < 10):
        return largenumbr
    # If the number is higher than 10, use the above function to recursively
    # compute the sum of the digits of the given integer.
    largenumbr = largenumbr % 10+digitalRootRecursion(largenumbr//10)
    return digitalRootRecursion(largenumbr)


# Give the number(Very Large) as static input and store it in a variable.
lrgenumbr = 64829048194591378492648546725
# Pass the given number as an argument to digitalRootRecursion() function.
rsdigitalroot = digitalRootRecursion(lrgenumbr)
# print the result digital root
print('The Digital root of the given number',
      lrgenumbr, 'is [', rsdigitalroot, ']')

Output:

The Digital root of the given number 64829048194591378492648546725 is [ 6 ]

Method #2: Using Recursion (User Input)

Approach:

Give the number(Very Large) as user input using int(input()) function and store it in a variable.

Create a function digitalRootRecursion which accepts the given number as an argument and returns the digital root of the given number.

Pass the given number as an argument to digitalRootRecursion() function.

Then determine whether the integer is greater than or less than 10. If the integer is less than 10, return the number immediately and terminate the function. If the number is higher than 10, use the above function to recursively compute the sum of the digits of the given integer.

The method will be repeated until we obtain the sum of all the digits of the specified integer. Then, by comparing our final number to 10, we may determine if it is a single digit or not. If the number is a single digit, it should be returned. The number returned is our digital root. If the number is not a single digit, repeat the operation until only a single digit remains.

So, using Recursion in Python, we can get the digital root of huge integers using this approach.

Print the Digital Root.

The Exit of the Program.

Below is the implementation:

# Create a function digitalRootRecursion which accepts the given number as an argument
# and returns the digital root of the given number.


def digitalRootRecursion(largenumbr):
    # Then determine whether the integer is greater than or less than 10.
    # If the integer is less than 10, return the number immediately
    # and terminate the function
    if(largenumbr < 10):
        return largenumbr
    # If the number is higher than 10, use the above function to recursively
    # compute the sum of the digits of the given integer.
    largenumbr = largenumbr % 10+digitalRootRecursion(largenumbr//10)
    return digitalRootRecursion(largenumbr)


# Give the number(Very Large) as user input using int(input())
# function and store it in a variable.
lrgenumbr = int(input('Enter some random large number = '))
# Pass the given number as an argument to digitalRootRecursion() function.
rsdigitalroot = digitalRootRecursion(lrgenumbr)
# print the result digital root
print('The Digital root of the given number',
      lrgenumbr, 'is [', rsdigitalroot, ']')

Output:

The Digital root of the given number 9956782345098712347865490832469987 is [ 7 ]

Related Programs:

Python Program to Find Digital Root of Large Integers using Recursion Read More »

Program to Find the Product of two Numbers Using Recursion

Python Program to Find the Product of two Numbers Using Recursion

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Recursion in Python:

When a function calls itself and loops until it reaches the intended end state, this is referred to as recursion. It is based on the mathematics idea of recursive definitions, which define elements in a set in terms of other members in the set.

Each recursive implementation contains a base case in which the desired state is reached, and a recursive case in which the desired state is not reached and the function enters another recursive phase.

On each step, the behavior in the recursive situation before the recursive function call, the internal self-call, is repeated. Recursive structures are beneficial when a larger problem (the base case) can be solved by solving repeated subproblems (the recursive case) that incrementally advance the program to the base case.
It behaves similarly to for and while loops, with the exception that recursion moves closer to the desired condition, whereas for loops run a defined number of times and while loops run until the condition is no longer met.

In other words, recursion is declarative because you specify the desired state, whereas for/while loops are iterative because you provide the number of repeats.

Given two numbers the task is to find the product of the given two numbers using recursion in Python.

Examples:

Example1:

Input:

given the first number = 27 
given the second number = 19

Output:

The product of the given numbers 27 and 19 is 27 * 19 = 513

Example2:

Input:

given the first number = 23
given the second number = 38

Output:

The product of the given numbers 23 and 38 is 23 * 38 = 874

Program to Find the Product of two Numbers Using Recursion

Below are the ways to Find the Product of two Numbers using the recursive approach in Python:

1)Using Recursion(Static Input)

Approach:

  • Give the two numbers as static input and store them as two variables.
  • To find the product of the two numbers, pass the numbers as arguments to a recursive function.
  • Give the base condition that if the first number is less than the second, execute the method recursively with the numbers swapped.
  • If the second number is not equal to 0, call the method again recursively otherwise, return 0.
  • The function returns the product of the given two numbers.
  • Print the result using the print() function.
  • The exit of the program.

Below is the implementation:

# function who calculates the product of the given two numbers recursively
def productRecursion(firstnumb, secondnumb):
  # Give the base condition that if the first number is less than the second,
  # execute the method recursively with the numbers swapped.
    if(firstnumb < secondnumb):
        return productRecursion(secondnumb, firstnumb)
    # If the second number is not equal to 0, call the
    # method again recursively otherwise, return 0.
    elif(secondnumb != 0):
        return(firstnumb + productRecursion(firstnumb, secondnumb-1))
    else:
        return 0


# Give the two numbers as static input and store them as two variables.
firstnumb = 27
secondnumb = 19
# passing the given two numbers as arguments to the recursive function
# which returns the product of the given two numbers
# printing th product of th two numbers
print("The product of the given numbers", firstnumb, 'and', secondnumb, 'is ' +
      str(firstnumb)+' * '+str(secondnumb)+' = ', productRecursion(firstnumb, secondnumb))

Output:

The product of the given numbers 27 and 19 is 27 * 19 =  513

2)Using Recursion(User Input separated by spaces)

Approach:

  • Give the two numbers as user input using the map() and split() function and store them in two separate variables.
  • To find the product of the two numbers, pass the numbers as arguments to a recursive function.
  • Give the base condition that if the first number is less than the second, execute the method recursively with the numbers swapped.
  • If the second number is not equal to 0, call the method again recursively otherwise, return 0.
  • The function returns the product of the given two numbers.
  • Print the result using the print() function.
  • The exit of the program.

Below is the implementation:

# function who calculates the product of the given two numbers recursively
def productRecursion(firstnumb, secondnumb):
  # Give the base condition that if the first number is less than the second,
  # execute the method recursively with the numbers swapped.
    if(firstnumb < secondnumb):
        return productRecursion(secondnumb, firstnumb)
    # If the second number is not equal to 0, call the
    # method again recursively otherwise, return 0.
    elif(secondnumb != 0):
        return(firstnumb + productRecursion(firstnumb, secondnumb-1))
    else:
        return 0


# Give the two numbers as user input using the map() and split() function
# and store them in two separate variables.
firstnumb, secondnumb = map(int, input(
    'Enter some random numbers separated by spaces = ').split())
# passing the given two numbers as arguments to the recursive function
# which returns the product of the given two numbers
# printing th product of th two numbers
print("The product of the given numbers", firstnumb, 'and', secondnumb, 'is ' +
      str(firstnumb)+' * '+str(secondnumb)+' = ', productRecursion(firstnumb, secondnumb))

Output:

Enter some random numbers separated by spaces = 23 38
The product of the given numbers 23 and 38 is 23 * 38 = 874

Explanation:

  • The user must provide two integers.
  • To find the product of two numbers, the two numbers are sent as parameters to a recursive function.
  • The basic condition is that if the first number is less than the second, the function is called recursively with the inputs swapped.
  • If the second number is greater than zero, the function is called recursively; otherwise, 0 is returned.
  • The result of the two numbers is printed.

Related Programs:

Python Program to Find the Product of two Numbers Using Recursion Read More »