Author name: Vikram Chiluka

Program to Print All Co-binary Palindromic Numbers in a Range

Python Program to Print All Co-binary Palindromic Numbers in a Range

Given the lower limit range and upper limit range, the task is to print all Co-binary Palindromic Numbers in the given range in Python.

Co-binary Palindromic Numbers:

A co-binary palindrome is a number that is a palindrome both as a decimal number and after being binary transformed.

Examples:

Example1:

Input:

Given upper limit range =11
Given lower limit range =2426

Output:

The Co-binary palindrome numbers in the given range 11 and 2426 are:
33 99 313 585 717

Example2:

Input:

Given upper limit range =5
Given lower limit range =12564

Output:

The Co-binary palindrome numbers in the given range 5 and 12564 are:
5 7 9 33 99 313 585 717 7447 9009

Program to Print All Co-binary Palindromic Numbers in a Range in

Python

Below are the ways to print all Co-binary Palindromic Numbers in the given range in Python.

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

Method #1: Using For Loop (Static Input)

Approach:

  • Give the lower limit range as static input and store it in a variable.
  • Give the upper limit range as static input and store it in another variable.
  • Create a function checkpalindromicNumb() which accepts the string as an argument and returns true if the string is palindrome else it returns False.
  • Create a function convertBinar() which converts the given number to binary and returns it.
  • Loop from lower limit range to upper limit range using For loop.
  • Convert this iterator value to binary by passing it as an argument to convertBinar() function and store it in a variable say binarystrng.
  • Convert this iterator value to a string using the str() function say strngnumb.
  • Check if the strngnumb is palindrome or not by giving the given strngnumb as an argument to checkpalindromicNumb().
  • Check if the binarystrng is palindrome or not by giving the given binarystrng as an argument to checkpalindromicNumb().
  • Check if both statements are true using the and operator and If conditional Statement.
  • If it is true then print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkpalindromicNumb() which accepts the string as an argument and
# returns true if the string is palindrome else it returns False.
def checkpalindromicNumb(val):
    return val == val[::-1]
# Create a function convertBinar() which converts the given number to binary and returns it.
def convertBinar(orinumb):
    return bin(orinumb)[2:]
# Give the lower limit range as static input and store it in a variable.
lowlimrange = 11
# Give the upper limit range as static input and store it in another variable.
upplimrange = 2426
print('The Co-binary palindrome numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for itervalu in range(lowlimrange, upplimrange+1):
    # Convert this iterator value to binary by passing it as an argument
    # to convertBinar() function and store it in a variable say binarystrng.
    binarystrng = convertBinar(itervalu)
    # Convert this iterator value to a string
    # using the str() function say strngnumb.
    strngnumb = str(itervalu)
    # Check if the strngnumb is palindrome or not by giving the given strngnumb
    # as an argument to checkpalindromicNumb().
    # Check if the binarystrng is palindrome or not by giving the given binarystrng
    # as an argument to checkpalindromicNumb().
    # Check if both statements are true using the and operator and If conditional Statement.
    if(checkpalindromicNumb(binarystrng) and checkpalindromicNumb(strngnumb)):
        # If it is true then print it.
        print(strngnumb, end=' ')

Output:

The Co-binary palindrome numbers in the given range 11 and 2426 are:
33 99 313 585 717

Method #2: Using For Loop (User Input)

Approach:

  • Give the lower limit range and upper limit range as user input using map(),int(),split() functions.
  • Store them in two separate variables.
  • Create a function checkpalindromicNumb() which accepts the string as an argument and returns true if the string is palindrome else it returns False.
  • Create a function convertBinar() which converts the given number to binary and returns it.
  • Loop from lower limit range to upper limit range using For loop.
  • Convert this iterator value to binary by passing it as an argument to convertBinar() function and store it in a variable say binarystrng.
  • Convert this iterator value to a string using the str() function say strngnumb.
  • Check if the strngnumb is palindrome or not by giving the given strngnumb as an argument to checkpalindromicNumb().
  • Check if the binarystrng is palindrome or not by giving the given binarystrng as an argument to checkpalindromicNumb().
  • Check if both statements are true using the and operator and If conditional Statement.
  • If it is true then print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkpalindromicNumb() which accepts the string as an argument and
# returns true if the string is palindrome else it returns False.
def checkpalindromicNumb(val):
    return val == val[::-1]
# Create a function convertBinar() which converts the given number to binary and returns it.
def convertBinar(orinumb):
    return bin(orinumb)[2:]

# Give the lower limit range and upper limit range as
# user input using map(),int(),split() functions.
# Store them in two separate variables.
lowlimrange, upplimrange = map(int, input(
    'Enter lower limit range and upper limit range separate bt spaces = ').split())
print('The Co-binary palindrome numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for itervalu in range(lowlimrange, upplimrange+1):
    # Convert this iterator value to binary by passing it as an argument
    # to convertBinar() function and store it in a variable say binarystrng.
    binarystrng = convertBinar(itervalu)
    # Convert this iterator value to a string
    # using the str() function say strngnumb.
    strngnumb = str(itervalu)
    # Check if the strngnumb is palindrome or not by giving the given strngnumb
    # as an argument to checkpalindromicNumb().
    # Check if the binarystrng is palindrome or not by giving the given binarystrng
    # as an argument to checkpalindromicNumb().
    # Check if both statements are true using the and operator and If conditional Statement.
    if(checkpalindromicNumb(binarystrng) and checkpalindromicNumb(strngnumb)):
        # If it is true then print it.
        print(strngnumb, end=' ')

Output:

Enter lower limit range and upper limit range separate bt spaces = 5 12564
The Co-binary palindrome numbers in the given range 5 and 12564 are:
5 7 9 33 99 313 585 717 7447 9009

Related Programs:

Python Program to Print All Co-binary Palindromic Numbers in a Range Read More »

Program to Check whether kth Bit is Set or not

Python Program to Check whether kth Bit is Set or not

When it comes to programming challenges, bits are really significant. In this post, we looked at how to use Python to determine whether the kth bit of a number is set or not.

Examples:

Example1:

Input:

Given Number =29
Given K=3

Output:

Enter the given number and the value of k separated by spaces = 29 3
The 3 nd bit in the number 29 (binary representation = 11101 ) is set bit

Example2:

Input:

Given Number =576
Given K=3

Output:

The 3 nd bit in the number number 576 (binary representation = 1001000000 )is not a set bit

Program to Check whether kth Bit is Set or not in Python

Below are the ways to check whether the kth bit is set bit or not in python.

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Method #1: Using Left Shift Operator (Static Input)

Approach:

  • Give the number and the value of k as static input and store it in a variable.
  • First, compute 1<<(k-1) and save it in a variable called temp, resulting in temp=1<<(k-1). temp holds an integer with only the kth bit set.
  • You must execute a bitwise AND of number and temp in this step. If this gives a non-zero integer, the kth bit of the number is set otherwise, it is not.
  • To Check the above statement using the If conditional Statement.
  • If it is true then print the kth bit is set bit.
  • Else print it is not set bit.
  • The Exit of the Program.

Below is the implementation:

# Give the number and the value of k as static input
# and store it in a variable.
numb = 19
k = 2
# First, compute 1<<(k-1) and save it in a variable called temp,
# resulting in temp=1<<(k-1). temp holds an integer with only the kth bit set.
temp = 1 << (k-1)
# You must execute a bitwise AND of number and temp in this step.
# If this gives a non-zero integer, the kth bit of the number is set otherwise, it is not.
# To Check the above statement using the If conditional Statement.
if (numb & temp):
        # If it is true then print the kth bit is set bit.
    print('The', k, 'nd bit in the number ', numb,
          '(binary representation =', bin(numb)[2:], ') is set bit')
# Else print it is not set bit.
else:
    print('The', k, 'nd bit in the number ', numb,
          '(binary representation =', bin(numb)[2:], ')is not a set bit')

Output:

The 2 nd bit in the number 19 (binary representation = 10011 ) is set bit

Method #2: Using Left Shift Operator (User Input)

Approach:

  • Give the number and the value of k as user input using map(), int(), split() functions and store them in two separate variables.
  • First, compute 1<<(k-1) and save it in a variable called temp, resulting in temp=1<<(k-1). temp holds an integer with only the kth bit set.
  • You must execute a bitwise AND of number and temp in this step. If this gives a non-zero integer, the kth bit of the number is set otherwise, it is not.
  • To Check the above statement using the If conditional Statement.
  • If it is true then print the kth bit is set bit.
  • Else print it is not set bit.
  • The Exit of the Program.

Below is the implementation:

# Give the number and the value of k as user input using map(), int(), split() functions
# and store them in two separate variables.
numb, k = map(int, input(
    'Enter the given number and the value of k separated by spaces = ').split())
# First, compute 1<<(k-1) and save it in a variable called temp,
# resulting in temp=1<<(k-1). temp holds an integer with only the kth bit set.
temp = 1 << (k-1)
# You must execute a bitwise AND of number and temp in this step.
# If this gives a non-zero integer, the kth bit of the number is set otherwise, it is not.
# To Check the above statement using the If conditional Statement.
if (numb & temp):
        # If it is true then print the kth bit is set bit.
    print('The', k, 'nd bit in the number', numb,
          '(binary representation =', bin(numb)[2:], ') is set bit')
# Else print it is not set bit.
else:
    print('The', k, 'nd bit in the number', numb,
          '(binary representation =', bin(numb)[2:], ')is not a set bit')

Output:

Enter the given number and the value of k separated by spaces = 29 3
The 3 nd bit in the number 29 (binary representation = 11101 ) is set bit

Method #3: Using Right Shift Operator (Static Input)

Approach:

  • Give the number and the value of k as static input and store it in a variable.
  • First, compute number>>(k-1) and store it in a variable called temp, resulting in temp=number>>(k-1). If the kth bit is set, the last bit of temp will be 1, otherwise, it will be 0.
  • You must execute a bitwise AND of 1 and temp in this step. If this gives a non-zero integer, the kth bit of the number is set, otherwise, it is not.
  • To Check the above statement using the If conditional Statement.
  • If it is true then print the kth bit is set bit.
  • Else print it is not set bit.
  • The Exit of the Program.

Below is the implementation:

# Give the number and the value of k as static input # and store it in a variable.
numb = 19
k = 2
# First, compute number>>(k-1) and store it in a variable called temp, resulting in temp=number>>(k-1).
# If the kth bit is set, the last bit of temp will be 1, otherwise, it will be 0.
temp = numb >> (k-1)
# You must execute a bitwise AND of 1 and temp in this step.
# If this gives a non-zero integer,
# the kth bit of the number is set, otherwise, it is not.
if (1 & temp):
        # If it is true then print the kth bit is set bit.
    print('The', k, 'nd bit in the number ', numb,
          '(binary representation =', bin(numb)[2:], ') is set bit')
# Else print it is not set bit.
else:
    print('The', k, 'nd bit in the number', numb,
          '(binary representation =', bin(numb)[2:], ')is not a set bit')

Output:

The 2 nd bit in the number 19 (binary representation = 10011 ) is set bit

Method #4: Using Right Shift Operator (User Input)

Approach:

  • Give the number and the value of k as user input using map(), int(), split() functions and store them in two separate variables.
  • First, compute number>>(k-1) and store it in a variable called temp, resulting in temp=number>>(k-1). If the kth bit is set, the last bit of temp will be 1, otherwise, it will be 0.
  • You must execute a bitwise AND of 1 and temp in this step. If this gives a non-zero integer, the kth bit of the number is set, otherwise, it is not.
  • To Check the above statement using the If conditional Statement.
  • If it is true then print the kth bit is set bit.
  • Else print it is not set bit.
  • The Exit of the Program.

Below is the implementation:

# Give the number and the value of k as user input using map(), int(), split() functions
# and store them in two separate variables.
numb, k = map(int, input(
    'Enter the given number and the value of k separated by spaces = ').split())
# First, compute number>>(k-1) and store it in a variable called temp, resulting in temp=number>>(k-1).
# If the kth bit is set, the last bit of temp will be 1, otherwise, it will be 0.
temp = numb >> (k-1)
# You must execute a bitwise AND of 1 and temp in this step.
# If this gives a non-zero integer,
# the kth bit of the number is set, otherwise, it is not.
if (1 & temp):
        # If it is true then print the kth bit is set bit.
    print('The', k, 'nd bit in the number', numb,
          '(binary representation =', bin(numb)[2:], ') is set bit')
# Else print it is not set bit.
else:
    print('The', k, 'nd bit in the number', numb,
          '(binary representation =', bin(numb)[2:], ')is not a set bit')

Output:

Enter the given number and the value of k separated by spaces = 576 3
The 3 nd bit in the number 576 (binary representation = 1001000000 )is not a set bit

Related Programs:

Python Program to Check whether kth Bit is Set or not Read More »

Program to Print all Harshad Numbers within Given Range

Python Program to Print all Harshad Numbers within Given Range

In this article, we will learn how to print Harshad numbers within a specific range in Python. You will learn what a Harshad number is, how to check whether a given number is a Harshad number, and how to write a Python code that outputs all the Harshad numbers within the user-specified range.

Harshad Number:

If the given number is divisible by the sum of its constituent digits, we can conclude that the given number is a Harshad number.

Given the lower limit range and upper limit range, the task is to print all the Harshad numbers in the given range.

Examples:

Example1:

Input:

Given upper limit range =11
Given lower limit range =178

Output:

The Harshad numbers in the given range 11 and 178 are:
12 18 20 21 24 27 30 36 40 42 45 48 50 54 60 63 70 72 80 81 84 90 100 102 108 110 111 112 114 117 120 126
 132 133 135 140 144 150 152 153 156 162 171

Example2:

Input:

Given upper limit range =160
Given lower limit range =378

Output:

The Harshad numbers in the given range 160 and 378 are:
162 171 180 190 192 195 198 200 201 204 207 209 210 216 220 222 224 225 228 230 234 240 243 247 252 261
 264 266 270 280 285 288 300 306 308 312 315 320 322 324 330 333 336 342 351 360 364 370 372 375 378

Program to Print all Harshad Numbers within Given Range in Python

Below are the ways to print all the Harshad numbers in the given range.

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Method #1: Using For Loop (Static Input)

Approach:

  • Create a function checkharshadnumb() which accepts the number as an argument and returns true if it is Harshad number else returns False.
  • Give the lower limit range as static input and store it in a variable.
  • Give the upper limit range as static input and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop pass the iterator value to checkharshadnumb() function.
  • If it returns true then print the iterator value.
  • Inside the checkharshadnumb() function.
  • Make a copy of the number(argument) so you can verify the outcome later.
  • Make a result variable ( set to 0 ).
  • Create a while loop to go digit by digit through the number.
  • Every iteration, increase the result by a digit.
  • Divide the result by the number’s duplicate.
  • If a number divides perfectly, it is a Harshad number return True
  • Else return False.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkharshadnumb() which accepts the number as an argument and
# returns true if it is Harshad number else returns False.


def checkharshadnumb(numb):
    # intiialize sum of digits to 0
    sum_of_digits = 0
    # copy the number in another variable(duplicate)
    dup_number = numb
    # Traverse the digits of number using for loop
    while dup_number > 0:
        sum_of_digits = sum_of_digits + dup_number % 10
        dup_number = dup_number // 10
    # If a number divides perfectly, it is a Harshad number return True
    # Else return False.
    if(numb % sum_of_digits == 0):
        return True
    else:
        return False


# Give the lower limit range as static input and store it in a variable.
lowlimrange = 11
# Give the upper limit range as static input and store it in another variable.
upplimrange = 178
print('The Harshad numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for m in range(lowlimrange, upplimrange+1):
        # Inside the for loop pass the iterator value to checkharshadnumb() function.
    if(checkharshadnumb(m)):
        # If it returns true then print the iterator value.
        print(m, end=' ')

Output:

The Harshad numbers in the given range 11 and 178 are:
12 18 20 21 24 27 30 36 40 42 45 48 50 54 60 63 70 72 80 81 84 90 100 102 108 110 111 112 114 117 120 126
 132 133 135 140 144 150 152 153 156 162 171

Method #2: Using For Loop (User Input)

Approach:

  • Create a function checkharshadnumb() which accepts the number as an argument and returns true if it is Harshad number else returns False.
  • Give the lower limit range and upper limit range as user input using map(),int(),split() functions.
  • Store them in two separate variables.
  • Inside the for loop pass the iterator value to checkharshadnumb() function.
  • If it returns true then print the iterator value.
  • Inside the checkharshadnumb() function.
  • Make a copy of the number(argument) so you can verify the outcome later.
  • Make a result variable ( set to 0 ).
  • Create a while loop to go digit by digit through the number.
  • Every iteration, increase the result by a digit.
  • Divide the result by the number’s duplicate.
  • If a number divides perfectly, it is a Harshad number return True
  • Else return False.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkharshadnumb() which accepts the number as an argument and
# returns true if it is Harshad number else returns False.


def checkharshadnumb(numb):
    # intiialize sum of digits to 0
    sum_of_digits = 0
    # copy the number in another variable(duplicate)
    dup_number = numb
    # Traverse the digits of number using for loop
    while dup_number > 0:
        sum_of_digits = sum_of_digits + dup_number % 10
        dup_number = dup_number // 10
    # If a number divides perfectly, it is a Harshad number return True
    # Else return False.
    if(numb % sum_of_digits == 0):
        return True
    else:
        return False


# Give the lower limit range and upper limit range as
# user input using map(),int(),split() functions.
# Store them in two separate variables.
lowlimrange, upplimrange = map(int, input(
    'Enter lower limit range and upper limit range separate bt spaces = ').split())
print('The Harshad numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for m in range(lowlimrange, upplimrange+1):
        # Inside the for loop pass the iterator value to checkharshadnumb() function.
    if(checkharshadnumb(m)):
        # If it returns true then print the iterator value.
        print(m, end=' ')

Output:

Enter lower limit range and upper limit range separate bt spaces = 160 378
The Harshad numbers in the given range 160 and 378 are:
162 171 180 190 192 195 198 200 201 204 207 209 210 216 220 222 224 225 228 230 234 240 243 247 252 261
 264 266 270 280 285 288 300 306 308 312 315 320 322 324 330 333 336 342 351 360 364 370 372 375 378

Related Programs:

Python Program to Print all Harshad Numbers within Given Range Read More »

Program to Check whether String Contains Unique Characters

Python Program to Check whether String Contains Unique Characters

Given a string, the task is to check whether the given string contains all the unique characters in Python.

Examples:

Example1:

Input:

Given string =btech

Output:

The given string [ btech ] contains unique characters

Example2:

Input:

Given string =bteceeh

Output:

The given string [ bteceeh ] contains duplicate characters

Program to Check whether String Contains Unique Characters in Python

Below are the ways to check whether the given string contains unique characters in python.

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

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

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as 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 strngfreqelements)
  • Calculate the length of this frequency dictionary using the len() function and store it in a variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Check if both lengths are equal or not using the If conditional statement.
  • If both lengths are equal then the given string contains all the unique characters.
  • Else the given string contains duplicate characters.
  • 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 as static input and store it in a variable.
givenstrng = 'btech'
# 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 strngfreqelements)
strngfreqelements = Counter(givenstrng)
# Calculate the length of this frequency dictionary
# using the len() function and store it in a variable.
lengthfreq = len(strngfreqelements)
# Calculate the length of the given string using
# the len() function and store it in another variable.
lengthstrng = len(givenstrng)
# Check if both lengths are equal or not using the If conditional statement.
# If both lengths are equal then the given string contains all the unique characters.
if(lengthfreq == lengthstrng):
    print('The given string [', givenstrng, '] contains unique characters')
# Else the given string contains duplicate characters.
else:
    print('The given string [', givenstrng, '] contains duplicate characters')

Output:

The given string [ btech ] contains unique characters

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

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as 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 strngfreqelements)
  • Calculate the length of this frequency dictionary using the len() function and store it in a variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Check if both lengths are equal or not using the If conditional statement.
  • If both lengths are equal then the given string contains all the unique characters.
  • Else the given string contains duplicate characters.
  • 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 as user input using the input() function and store it in a variable.
givenstrng = 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 strngfreqelements)
strngfreqelements = Counter(givenstrng)
# Calculate the length of this frequency dictionary
# using the len() function and store it in a variable.
lengthfreq = len(strngfreqelements)
# Calculate the length of the given string using
# the len() function and store it in another variable.
lengthstrng = len(givenstrng)
# Check if both lengths are equal or not using the If conditional statement.
# If both lengths are equal then the given string contains all the unique characters.
if(lengthfreq == lengthstrng):
    print('The given string [', givenstrng, '] contains unique characters')
# Else the given string contains duplicate characters.
else:
    print('The given string [', givenstrng, '] contains duplicate characters')

Output:

Enter some random string = oneplus
The given string [ oneplus ] contains unique characters

Method #3: Using set() method (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Convert this string to set using set() function and store it in a variable.
  • Calculate the length of this set using the len() function and store it in a variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Check if both lengths are equal or not using the If conditional statement.
  • If both lengths are equal then the given string contains all the unique characters.
  • Else the given string contains duplicate characters.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
givenstrng = 'bteceeh'
# Convert this string to set using set() function and store it in a variable.
strngset = set(givenstrng)
# Calculate the length of this set using the len() function and store it in a variable.
lengthfreq = len(strngset)
# Calculate the length of the given string using
# the len() function and store it in another variable.
lengthstrng = len(givenstrng)
# Check if both lengths are equal or not using the If conditional statement.
# If both lengths are equal then the given string contains all the unique characters.
if(lengthfreq == lengthstrng):
    print('The given string [', givenstrng, '] contains unique characters')
# Else the given string contains duplicate characters.
else:
    print('The given string [', givenstrng, '] contains duplicate characters')

Output:

The given string [ bteceeh ] contains duplicate characters

Method #4: Using set() method (User Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the string as user input using the input() function and store it in a variable.
  • Calculate the length of this set using the len() function and store it in a variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Check if both lengths are equal or not using the If conditional statement.
  • If both lengths are equal then the given string contains all the unique characters.
  • Else the given string contains duplicate characters.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
givenstrng = input('Enter some random string = ')
# Convert this string to set using set() function and store it in a variable.
strngset = set(givenstrng)
# Calculate the length of this set using the len() function and store it in a variable.
lengthfreq = len(strngset)
# Calculate the length of the given string using
# the len() function and store it in another variable.
lengthstrng = len(givenstrng)
# Check if both lengths are equal or not using the If conditional statement.
# If both lengths are equal then the given string contains all the unique characters.
if(lengthfreq == lengthstrng):
    print('The given string [', givenstrng, '] contains unique characters')
# Else the given string contains duplicate characters.
else:
    print('The given string [', givenstrng, '] contains duplicate characters')

Output:

Enter some random string = xiaomi
The given string [ xiaomi ] contains duplicate characters

Related Programs:

Python Program to Check whether String Contains Unique Characters Read More »

Program to Rearrange the Letters of a String in Alphabetical Order

Python Program to Rearrange the Letters of a String in Alphabetical Order

Given a string, the task is to rearrange the letters of a string in Alphabetical order in Python.

Examples:

Example1:

Input:

Given string = btechgeeks

Output:

The original string is [ btechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ bceeeghkst ]

Example2:

Input:

Given string =Good morning this is BTechgeeks

Output:

Enter some random string = Good morning this is BTechgeeks
The original string is [ Good morning this is BTechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ BGTcdeeegghhiiikmnnooorssst ]

Program to Rearrange the Letters of a String in Alphabetical Order in Python

Below are the ways to rearrange the letters of a string in Alphabetical order 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.

Method #1: Using sorted() and join() functions (Static Input)

i)Single String

Approach:

  • Give the string as static input and store it in variable.
  • Reorder the letters of a string alphabetically using the sorted function(This method returns a list of letters in alphabetical order).
  • Join this using the join() function.
  • Print the modified string after reordering the letters of a string alphabetically.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in variable.
gvnstrng = 'btechgeeks'
# Reorder the letters of a string alphabetically using
# the sorted function(This method returns a list of letters in alphabetical order).
sortdstrng = sorted(gvnstrng)
# Join this using the join() function.
finalstrng = ''.join(sortdstrng)
# Print the modified string after reordering the letters of a string alphabetically.
print('The original string is [', gvnstrng, ']')
print(
    'The modified string after reordering the letters of a string alphabetically is [', finalstrng, ']')

Output:

The original string is [ btechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ bceeeghkst ]

ii)Multiple strings separated by spaces

Approach:

  • Give the string as static input and store it in variable.
  • Reorder the letters of a string alphabetically using the sorted function(This method returns a list of letters in alphabetical order).
  • Join this using the join() function.
  • Use the strip() function to remove spaces between the strings.
  • Print the modified string after reordering the letters of a string alphabetically.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in variable.
gvnstrng = 'Hello this is BTechgeeks'
# Reorder the letters of a string alphabetically using
# the sorted function(This method returns a list of letters in alphabetical order).
sortdstrng = sorted(gvnstrng)
# Join this using the join() function.
# Use the strip() function to remove spaces between the strings.
finalstrng = ''.join(sortdstrng).strip()
# Print the modified string after reordering the letters of a string alphabetically.
print('The original string is [', gvnstrng, ']')
print(
    'The modified string after reordering the letters of a string alphabetically is [', finalstrng, ']')

Output:

The original string is [ Hello this is BTechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ BHTceeeeghhiikllossst ]

Method #2: Using sorted() and join() functions (User Input)

i)Single String

Approach:

  • Give the string as user input using the input() function and store it in variable.
  • Reorder the letters of a string alphabetically using the sorted function(This method returns a list of letters in alphabetical order).
  • Join this using the join() function.
  • Print the modified string after reordering the letters of a string alphabetically.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Reorder the letters of a string alphabetically using
# the sorted function(This method returns a list of letters in alphabetical order).
sortdstrng = sorted(gvnstrng)
# Join this using the join() function.
finalstrng = ''.join(sortdstrng)
# Print the modified string after reordering the letters of a string alphabetically.
print('The original string is [', gvnstrng, ']')
print(
    'The modified string after reordering the letters of a string alphabetically is [', finalstrng, ']')

Output:

Enter some random string = btechgeeks
The original string is [ btechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ bceeeghkst ]

ii)Multiple strings separated by spaces

Approach:

  • Give the string as user input using the input() function and store it in variable.
  • Reorder the letters of a string alphabetically using the sorted function(This method returns a list of letters in alphabetical order).
  • Join this using the join() function.
  • Use the strip() function to remove spaces between the strings.
  • Print the modified string after reordering the letters of a string alphabetically.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Reorder the letters of a string alphabetically using
# the sorted function(This method returns a list of letters in alphabetical order).
sortdstrng = sorted(gvnstrng)
# Join this using the join() function.
# Use the strip() function to remove spaces between the strings.
finalstrng = ''.join(sortdstrng).strip()
# Print the modified string after reordering the letters of a string alphabetically.
print('The original string is [', gvnstrng, ']')
print(
    'The modified string after reordering the letters of a string alphabetically is [', finalstrng, ']')

Output:

Enter some random string = Good morning this is BTechgeeks
The original string is [ Good morning this is BTechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ BGTcdeeegghhiiikmnnooorssst ]

Method #3: Using sorted() and lambda expression (Static Input)

This procedure is similar to the last one. The only difference is that we use a lambda expression with the reduce() function to connect the strings here.

i)Single String

Approach:

  • Import the reduce from functools using the import Keyword.
  • Give the string as static input and store it in variable.
  • Use the reduce and sorted() function in a lambda expression and store it in a variable.
  • Print the modified string after reordering the letters of a string alphabetically.
  • The Exit of the Program.

Below is the implementation:

# import the reduce from functools using the import Keyword
from functools import reduce
# Give the string as user input using the input() function and store it in a variable.
gvnstrng = 'btechgeeks'
# Use the reduce and sorted() function in a lambda expression and store it in a variable.
finalstrng = reduce(lambda m, n: m + n, (sorted(gvnstrng)))
# Print the modified string after reordering the letters of a string alphabetically.
print('The original string is [', gvnstrng, ']')
print(
    'The modified string after reordering the letters of a string alphabetically is [', finalstrng, ']')

Output:

The original string is [ btechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ bceeeghkst ]

ii)Multiple strings separated by spaces

Approach:

  • Import the reduce from functools using the import Keyword.
  • Give the string as static input and store it in variable.
  • Use the reduce and sorted() function in a lambda expression and store it in a variable.
  • Use the strip() function to remove spaces between the strings.
  • Print the modified string after reordering the letters of a string alphabetically.
  • The Exit of the Program.

Below is the implementation:

# import the reduce from functools using the import Keyword
from functools import reduce
# Give the string as user input using the input() function and store it in a variable.
gvnstrng = 'this is BTechgeeks'
# Use the reduce and sorted() function in a lambda expression and store it in a variable.
# Use the strip() function to remove spaces between the strings.
finalstrng = reduce(lambda m, n: m + n, (sorted(gvnstrng))).strip()
# Print the modified string after reordering the letters of a string alphabetically.
print('The original string is [', gvnstrng, ']')
print(
    'The modified string after reordering the letters of a string alphabetically is [', finalstrng, ']')

Output:

The original string is [ this is BTechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ BTceeeghhiikssst ]

Method #4: Using sorted() and lambda expression (User Input)

This procedure is similar to the last one. The only difference is that we use a lambda expression with the reduce() function to connect the strings here.

i)Single String

Approach:

  • Import the reduce from functools using the import Keyword.
  • Give the string as user input using the input() function and store it in variable.
  • Use the reduce and sorted() function in a lambda expression and store it in a variable.
  • Print the modified string after reordering the letters of a string alphabetically.
  • The Exit of the Program.

Below is the implementation:

# import the reduce from functools using the import Keyword
from functools import reduce
# Give the string as user input using the input() function and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Use the reduce and sorted() function in a lambda expression and store it in a variable.
finalstrng = reduce(lambda m, n: m + n, (sorted(gvnstrng)))
# Print the modified string after reordering the letters of a string alphabetically.
print('The original string is [', gvnstrng, ']')
print(
    'The modified string after reordering the letters of a string alphabetically is [', finalstrng, ']')

Output:

The original string is [ btechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ bceeeghkst ]

ii)Multiple strings separated by spaces

Approach:

  • Import the reduce from functools using the import Keyword.
  • Give the string as user input using the input() function and store it in variable.
  • Use the reduce and sorted() function in a lambda expression and store it in a variable.
  • Use the strip() function to remove spaces between the strings.
  • Print the modified string after reordering the letters of a string alphabetically.
  • The Exit of the Program.

Below is the implementation:

# import the reduce from functools using the import Keyword
from functools import reduce
# Give the string as user input using the input() function and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Use the reduce and sorted() function in a lambda expression and store it in a variable.
# Use the strip() function to remove spaces between the strings.
finalstrng = reduce(lambda m, n: m + n, (sorted(gvnstrng))).strip()
# Print the modified string after reordering the letters of a string alphabetically.
print('The original string is [', gvnstrng, ']')
print(
    'The modified string after reordering the letters of a string alphabetically is [', finalstrng, ']')

Output:

Enter some random string = Good morning this is BTechgeeks
The original string is [ Good morning this is BTechgeeks ]
The modified string after reordering the letters of a string alphabetically is [ BGTcdeeegghhiiikmnnooorssst ]

Related Programs:

Python Program to Rearrange the Letters of a String in Alphabetical Order Read More »

Program to Sort the List According to the Second Element in Sublist

Python Program to Sort the List According to the Second Element in Sublist

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.

Given list of lists which contain two elements in every sub list , the task is to sort the lists according to the second element in sub list.

Examples:

Example1:

Input:

given nested list =[['hello', 11], ['this', 1], ['is', 23], ['btechgeeks', 19], ['online', 39], ['platform', 7], ['for', 29]]

Output:

printing the sorted nested list before sorting :
[['hello', 11], ['this', 1], ['is', 23], ['btechgeeks', 19], ['online', 39], ['platform', 7], ['for', 29]]
printing the sorted nested list after sorting :
[['this', 1], ['platform', 7], ['hello', 11], ['btechgeeks', 19], ['is', 23], ['for', 29], ['online', 39]]

Example2:

Input:

[['hello', 46], ['this', 31], ['morning', 29], ['is', 26], ['btechGeeks', 19], ['online', 33]]

Output:

printing the sorted nested list before sorting :
[['hello', 46], ['this', 31], ['morning', 29], ['is', 26], ['btechGeeks', 19], ['online', 33]]
printing the sorted nested list after sorting :
[['btechGeeks', 19], ['is', 26], ['morning', 29], ['this', 31], ['online', 33], ['hello', 46]]

Example3:

Input:

[['sky', 12], ['is', 39], ['blue', 5]]

Output:

printing the sorted nested list before sorting :
[['sky', 12], ['is', 39], ['blue', 5]]
printing the sorted nested list after sorting :
[['blue', 5], ['sky', 12], ['is', 39]]

Program to Sort the List According to the Second Element in Sub list in Python

Below are the ways to sort the given list of lists according to the second element in sub list in python some of them are:

Method #1: Using nested loops and temporary variable(Static Input)

Approach:

  • Take in a list that contains sublists as static input.
  • Using two for loops, sort the sublists using bubble sort based on the second value of the sublist.
  • If the second element of the first sublist is greater than the second element of the second sublist, the complete sublist should be exchanged/swapped.
  • The sorted list should be printed.
  • Exit of program.

Below is the implementation:

# Take in a list that contains sublists as static input.
nestedList = [['hello', 46], ['this', 31], ['morning', 29],
              ['is', 26], ['btechGeeks', 19], ['online', 33]]
# printing the sorted nested list before sorting
print('printing the sorted nested list before sorting :')
print(nestedList)
# Using two for loops, sort the sublists using bubble
# sort based on the second value of the sublist.
for m in range(len(nestedList)):
    for n in range(len(nestedList)-m-1):
      # If the second element of the first sublist is greater than the second element of the second sublist,
      # the complete sublist should be exchanged/swapped using temporary variable
        if(nestedList[n][1] > nestedList[n+1][1]):
            tempo = nestedList[n]
            nestedList[n] = nestedList[n+1]
            nestedList[n+1] = tempo
# printing the sorted nested list after sorting
print('printing the sorted nested list after sorting :')
print(nestedList)

Output:

printing the sorted nested list before sorting :
[['hello', 46], ['this', 31], ['morning', 29], ['is', 26], ['btechGeeks', 19], ['online', 33]]
printing the sorted nested list after sorting :
[['btechGeeks', 19], ['is', 26], ['morning', 29], ['this', 31], ['online', 33], ['hello', 46]]

Method #2: Using nested loops and temporary variable(User Input)

Approach:

  • Take a empty list.
  • Scan the number of elements /number of sublists as user input using int(input()) function.
  • Loop from 1 to given number of elements times using for loop.
  • Scan the list elements using input() and int(input()) functions and append to the empty list using append() function.
  • Using two for loops, sort the sublists using bubble sort based on the second value of the sublist.
  • If the second element of the first sublist is greater than the second element of the second sublist, the complete sublist should be exchanged/swapped.
  • The sorted list should be printed.
  • Exit of program.

Below is the implementation:

# Take a empty list.
nestedList = []
# Scan the number of elements /number of sublists as user input using int(input()) function.
totalsublists = int(input('Enter some random number of sublists ='))
# Loop from 1 to given number of elements times using for loop.
for r in range(totalsublists):
    # Scan the list elements using input() and int(input()) functions and append
    # to the empty list using append() function.
    firsteleme = input('Enter some random first element =')
    secondeleme = int(input('Enter some random second element ='))
    nestedList.append([firsteleme, secondeleme])

# printing the sorted nested list before sorting
print('printing the sorted nested list before sorting :')
print(nestedList)
# Using two for loops, sort the sublists using bubble
# sort based on the second value of the sublist.
for m in range(len(nestedList)):
    for n in range(len(nestedList)-m-1):
      # If the second element of the first sublist is greater than the second element of the second sublist,
      # the complete sublist should be exchanged/swapped using temporary variable
        if(nestedList[n][1] > nestedList[n+1][1]):
            tempo = nestedList[n]
            nestedList[n] = nestedList[n+1]
            nestedList[n+1] = tempo
# printing the sorted nested list after sorting
print('printing the sorted nested list after sorting :')
print(nestedList)

Output:

Enter some random number of sublists =7
Enter some random first element =hello
Enter some random second element =11
Enter some random first element =this
Enter some random second element =1
Enter some random first element =is
Enter some random second element =23
Enter some random first element =btechgeeks
Enter some random second element =19
Enter some random first element =online
Enter some random second element =39
Enter some random first element =platform
Enter some random second element =7
Enter some random first element =for
Enter some random second element =29
printing the sorted nested list before sorting :
[['hello', 11], ['this', 1], ['is', 23], ['btechgeeks', 19], ['online', 39], ['platform', 7], ['for', 29]]
printing the sorted nested list after sorting :
[['this', 1], ['platform', 7], ['hello', 11], ['btechgeeks', 19], ['is', 23], ['for', 29], ['online', 39]]

Explanation:

  • The user must enter a list with numerous sublists.
  • Scan the list elements using input() and int(input()) functions and append to the empty list using append() function.
  • The list is then sorted using bubble sort based on the second member in the sublist.
  • The entire sublist is switched if the second element of the first sublist is bigger than the second element of the second sublist.
  • This step is repeated until the full list has been sorted.
  • After that, the sorted list is printed.

Related Programs:

Python Program to Sort the List According to the Second Element in Sublist Read More »

Program to Count Number of Lowercase Characters in a String

Python Program to Count Number of Lowercase Characters in a String

Strings in Python:

In Python, a string may be a sequence of characters. It is an information type that has been derived. Strings are unchangeable. This means that when they have been defined, they can not be modified. Many Python functions change strings, like replace(), join(), and split(). They do not, however, alter the original string. They make a duplicate of a string, alter it, then return it to the caller.

Given a string, the task is to write a python program to calculate the total number of lowercase characters in the given string.

Examples:

Example1:

Input:

given string = 'Hello this is BTechGeeks'

Output:

The total number of lower case letters present in the given string [ Hello this is BTechGeeks ] =  17

Example2:

Input:

given string = BTechgeeks

Output:

The total number of lower case letters present in the given string [ BTechgeeks ] = 8

Program to Count Number of Lowercase Characters in a String in Python

There are several ways to count the number of lowercase characters in the given string some of them are:

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.

1)Using Count Variable and islower() function(Static Input)

Approach:

  • Give the string as static input and save it in a variable.
  • Take a variable to say countlow that stores the total number of lowercase characters present in the given string.
  • Initialize the countlow to 0.
  • Traverse the given string using for loop.
  • Check if the iterator value is lowercase or not using islower() function.
  • If the character is in lowercase then increment the countlow by 1.
  • Print the countlow.

Below is the implementation:

# Give the string as static input and save it in a variable.
given_strng = 'Hello this is BTechGeeks'
# Take a variable to say countlow that stores the total number of lowercase characters present in the given string.
# Initialize the countlow to 0.
countlow = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Check if the iterator value is lowercase or not using islower() function.
    if(charact.islower()):
        # If the character is in lowercase then increment the countlow by 1.
        countlow = countlow+1
# Print the countlow.
print(
    'The total number of lower case letters present in the given string [', given_strng, '] = ', countlow)

Output:

The total number of lower case letters present in the given string [ Hello this is BTechGeeks ] =  17

2)Using Count Variable and islower() function(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable to say countlow that stores the total number of lowercase characters present in the given string.
  • Initialize the countlow to 0.
  • Traverse the given string using for loop.
  • Check if the iterator value is lowercase or not using islower() function.
  • If the character is in lowercase then increment the countlow by 1.
  • Print the countlow.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
given_strng = input('Enter some random string = ')
# Take a variable to say countlow that stores the total number of lowercase characters present in the given string.
# Initialize the countlow to 0.
countlow = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Check if the iterator value is lowercase or not using islower() function.
    if(charact.islower()):
        # If the character is in lowercase then increment the countlow by 1.
        countlow = countlow+1
# Print the countlow.
print('The total number of lower case letters present in the given string [', given_strng, '] = ', countlow)

Output:

Enter some random string = BTechgeeks
The total number of lower case letters present in the given string [ BTechgeeks ] = 8

Explanation:

  • A string must be entered by the user and saved in a variable.
  • The count variable is set to zero.
  • The for loop is used to go over the characters in a string.
  • When a lowercase character is encountered, the count is increased.
  • The string’s total number of lowercase characters is printed using the print() function.

3)By Checking Ascii values(Static Input)

Approach:

  • Give the string as static input and save it in a variable.
  • Take a variable to say countlow that stores the total number of lowercase characters present in the given string.
  • Initialize the countlow to 0.
  • Traverse the given string using for loop.
  • Calculate the ASCII value of the character using the ord() function and store it in a variable.
  • If the ASCII values lie between 97 to 122 then the character is in lowercase.
  • If the character is in lowercase then increment the countlow by 1.
  • Print the countlow.

Below is the implementation:

# Give the string as static input and save it in a variable.
given_strng = 'Hello this is BTechGeeks'
# Take a variable to say countlow that stores the total number of lowercase characters present in the given string.
# Initialize the countlow to 0.
countlow = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Calculate the ASCII value of the character using the ord() function and
    # store it in a variable.
    ascValue = ord(charact)
    # If the ASCII values lie between 97 to 122 then the character is in lowercase.
    if(ascValue >= 97 and ascValue <= 122):
        # If the character is in lowercase then increment the countlow by 1.
        countlow = countlow+1
# Print the countlow.
print(
    'The total number of lower case letters present in the given string [', given_strng, '] = ', countlow)

Output:

The total number of lower case letters present in the given string [ Hello this is BTechGeeks ] =  17

4)By Checking Ascii values(User Input)

Approach:

  • Give the string as user input using input() function and save it in a variable.
  • Take a variable to say countlow that stores the total number of lowercase characters present in the given string.
  • Initialize the countlow to 0.
  • Traverse the given string using for loop.
  • Calculate the ASCII value of the character using the ord() function and store it in a variable.
  • If the ASCII values lie between 97 to 122 then the character is in lowercase.
  • If the character is in lowercase then increment the countlow by 1.
  • Print the countlow.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
given_strng = input('Enter some random string = ')
# Take a variable to say countlow that stores the total number of lowercase characters present in the given string.
# Initialize the countlow to 0.
countlow = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Calculate the ASCII value of the character using the ord() function and
    # store it in a variable.
    ascValue = ord(charact)
    # If the ASCII values lie between 97 to 122 then the character is in lowercase.
    if(ascValue >= 97 and ascValue <= 122):
        # If the character is in lowercase then increment the countlow by 1.
        countlow = countlow+1
# Print the countlow.
print(
    'The total number of lower case letters present in the given string [', given_strng, '] = ', countlow)

Output:

Enter some random string = btechGeeks
The total number of lower case letters present in the given string [ btechGeeks ] = 9

Related Programs:

Python Program to Count Number of Lowercase Characters in a String Read More »

Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically

Python Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically

Strings in Python:

“String is a character collection or array”

Well in Python too, for the string data type, we say the same definition. The string is a sequenced character array and is written within single, double, or three quotes. Also, Python does not have the data type character, thus it is used as a string of length 1 if we write ‘s’.

Given a hyphen-separated sequence of strings, the task is to sort the strings and print them as hyphen-separated strings in Python.

Examples:

Example1:

Input:

given hyphen-separated string =hello-this-is-btechgeeks

Output:

The string before modification =  hello-this-is-btechgeeks
The string after modification =  btechgeeks-hello-is-this

Example2:

Input:

given hyphen-separated string =good-morning-codechef

Output:

The string before modification = good-morning-codechef
The string after modification = codechef-good-morning

Examples3:

Input:

given hyphen-separated string =btechgeeks-online-platform-fror-coding-students

Output:

The string before modification = btechgeeks-online-platform-fror-coding-students
The string after modification = btechgeeks-coding-fror-online-platform-students

Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically in Python

Below are the ways to accept a hyphen-separated sequence of strings, the task is to sort the strings and print them as hyphen-separated strings 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 split() and join() functions(Static Input)

Approach:

  • Give the hyphen-separated string as static input and store it in a variable.
  • Split the hyphen-separated strings into a list of strings using the split() function and store it in a variable.
  • sort the given list using the sort() function.
  • Print the sorted sequence by joining the words in the list with a hyphen.
  • The Exit of the program.

Below is the implementation of the above approach:

# Give the string as static input and store it in a variable.
givn_strng = 'hello-this-is-btechgeeks'
# print the string before modification
print('The string before modification = ', givn_strng)
# Split the hyphen-separated strings into a list of strings using the split()
# function and store it in a variable.
wordsLis = givn_strng.split('-')
# sort the given list using the sort() function.
wordsLis.sort()
# Print the sorted sequence by joining the words in the list with a hyphen.
resultwords = '-'.join(wordsLis)
# print the resultwords
print('The string after modification = ', resultwords)

Output:

The string before modification =  hello-this-is-btechgeeks
The string after modification =  btechgeeks-hello-is-this

Explanation:

  • Give the hyphen-separated string as static input and store it in a variable.
  • The hyphen is used as a key to split the sequence, and the words are saved in a list.
  • Using the sort() function, the words in the list are sorted alphabetically.
  • The terms in the list are then connected together by utilizing a hyphen as a reference.
  • The word sequence is then printed in its sorted order.

Method #2:Using split() and join() functions(User Input)

Approach:

  • Give the hyphen-separated string as user input using the input() function.
  • Split the hyphen-separated strings into a list of strings using the split() function and store it in a variable.
  • sort the given list using the sort() function.
  • Print the sorted sequence by joining the words in the list with a hyphen.
  • The Exit of the program.

Below is the implementation of the above approach:

# Give the hyphen-separated string as user input using the input() function.
givn_strng = input('Enter some random string = ')
# print the string before modification
print('The string before modification = ', givn_strng)
# Split the hyphen-separated strings into a list of strings using the split()
# function and store it in a variable.
wordsLis = givn_strng.split('-')
# sort the given list using the sort() function.
wordsLis.sort()
# Print the sorted sequence by joining the words in the list with a hyphen.
resultwords = '-'.join(wordsLis)
# print the resultwords
print('The string after modification = ', resultwords)

Output:

Enter some random string = good-morning-codechef
The string before modification = good-morning-codechef
The string after modification = codechef-good-morning

Explanation:

  • As input, the user must enter a hyphen-separated string of words.
  • The hyphen is used as a key to split the sequence, and the words are saved in a list.
  • Using the sort() function, the words in the list are sorted alphabetically.
  • The terms in the list are then connected together by utilizing a hyphen as a reference.
  • The word sequence is then printed in its sorted order.
  • It is the fastest and efficient approach.

Related Programs:

Python Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically Read More »

Python Program to Calculate the Average of a Number’s digits of Every Number in Given List

Python Program to Calculate the Average of a Number’s digits of Every Number in Given List

Given a list, the task is to calculate the average of every number digit in the given List in Python.

Examples:

Example1:

Input:

Given list =[9, 15, 21, 356, 3243, 9139, 4467285, 123456, 5783892, 4535363, 69]

Output:

The list before calculating Average of digits =  [9, 15, 21, 356, 3243, 9139, 4467285, 123456, 5783892, 4535363, 69]
The list after calculating Average of digits =  [9.0, 3.0, 1.5, 4.666666666666667, 3.0, 5.5, 5.142857142857143, 3.5, 6.0, 4.142857142857

Example2:

Input:

Given list = [245, 1739, 102, 199, 488, 58]

Output:

The list before calculating Average of digits = [245, 1739, 102, 199, 488, 58]
The list after calculating Average of digits = [3.6666666666666665, 5.0, 1.0, 6.333333333333333, 6.666666666666667, 6.5]

Program to Calculate the Average of a Number’s digits of Every Number in Given List in Python

Below are the ways to Calculate the Average of a Number’s digits of Every Number in the given List 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 For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Take an empty to store the Average digit sums of all the individual elements using [] or list() say resulist.
  • Create a function numAverageDigits() which accepts the number as an argument and returns the Average of all the digits in the given number.
  • Traverse the given list using For loop.
  • Pass the iterator value(element) to the numAverageDigits() as an argument and append the result to the resulist using the append() function.
  • Print the resulist.
  • The Exit of the Program.

Below is the implementation:

# Create a function numAverageDigits() which accepts the number as an argument and
# returns the Average of all the digits in the given Number.


def numAverageDigits(numbe):
  # convert the given number to string using str() function
    stringnum = str(numbe)
    # Create a list of digits using map(),list(),int functions
    digitslist = list(map(int, stringnum))
    # calculate the sum of digits of the above digitslist
    sumdigits = sum(digitslist)
    # calculate the total number of digits by calculating length of the digits list
    numOfDigits = len(digitslist)
    # calculate the average of digits of the given number
    # by diving sum of digits by number of digits
    avgdigits = sumdigits/numOfDigits
    # Return the average of the digits.
    return avgdigits


# Give the list as static input and store it in a variable.
givenlist = [9, 15, 21, 356, 3243, 9139, 4467285, 123456, 5783892, 4535363, 69]
# Take an empty to store the Average digit sums of all the individual elements
# using [] or list() say resulist.
resulist = []
# Traverse the given list using For loop.
for Number in givenlist:
    # Pass the iterator value(element) to the numAverageDigits() as an argument
    # and append the result to the resulist using the append() function.
    resulist.append(numAverageDigits(Number))
# Print the givenlist before calculating Average of digits
print('The list before calculating Average of digits = ', givenlist)
# Print the resulist after calculating Average of digits
print('The list after calculating Average of digits = ', resulist)

Output:

The list before calculating Average of digits =  [9, 15, 21, 356, 3243, 9139, 4467285, 123456, 5783892, 4535363, 69]
The list after calculating Average of digits =  [9.0, 3.0, 1.5, 4.666666666666667, 3.0, 5.5, 5.142857142857143, 3.5, 6.0, 4.142857142857143, 7.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 an empty to store the Average digit sums of all the individual elements using [] or list() say resulist.
  • Create a function numAverageDigits() which accepts the number as an argument and returns the Average of all the digits in the given number.
  • Traverse the given list using For loop.
  • Pass the iterator value(element) to the numAverageDigits() as an argument and append the result to the resulist using the append() function.
  • Print the resulist.
  • The Exit of the Program.

Below is the implementation:

# Create a function numAverageDigits() which accepts the number as an argument and
# returns the Average of all the digits in the given Number.


def numAverageDigits(numbe):
  # convert the given number to string using str() function
    stringnum = str(numbe)
    # Create a list of digits using map(),list(),int functions
    digitslist = list(map(int, stringnum))
    # calculate the sum of digits of the above digitslist
    sumdigits = sum(digitslist)
    # calculate the total number of digits by calculating length of the digits list
    numOfDigits = len(digitslist)
    # calculate the average of digits of the given number
    # by diving sum of digits by number of digits
    avgdigits = sumdigits/numOfDigits
    # Return the average of the digits.
    return avgdigits


# Give the list as user input using list(),map(),input(),and split() functions.
# store it in a variable.
givenlist = list(
    map(int, input('Enter some random List Elements separated by spaces = ').split()))
# Take an empty to store the Average digit sums of all the individual elements
# using [] or list() say resulist.
resulist = []
# Traverse the given list using For loop.
for Number in givenlist:
    # Pass the iterator value(element) to the numAverageDigits() as an argument
    # and append the result to the resulist using the append() function.
    resulist.append(numAverageDigits(Number))
# Print the givenlist before calculating Average of digits
print('The list before calculating Average of digits = ', givenlist)
# Print the resulist after calculating Average of digits
print('The list after calculating Average of digits = ', resulist)

Output:

Enter some random List Elements separated by spaces = 245 1739 102 199 488 58
The list before calculating Average of digits = [245, 1739, 102, 199, 488, 58]
The list after calculating Average of digits = [3.6666666666666665, 5.0, 1.0, 6.333333333333333, 6.666666666666667, 6.5]

Related Programs:

Python Program to Calculate the Average of a Number’s digits of Every Number in Given List Read More »

Program to Calculate the Number of Digits and Letters in a String

Python Program to Calculate the Number of Digits and Letters in a String

Strings in Python:

“String is a character collection or array”

Well in Python too, for the string data type, we say the same definition. The string is a sequenced character array and is written within single, double, or three quotes. Also, Python does not have the data type character, thus it is used as a string of length 1 if we write ‘r’.

Given a string, the task is to calculate the total number of digits and letters present in the given string in Python.

Examples:

Example1:

Input:

given string =Hel34lo18th3is9is38 BTech23Geeks

Output:

The total number of digits present in the given string [ Hel34lo18th3is9is38 BTech23Geeks ] =  10
The total number of characters present in the given string [ Hel34lo18th3is9is38 BTech23Geeks ] =  32

Example2:

Input:

given string =btechgeeks2online82platform92for1000geeks

Output:

Enter some random string = btechgeeks2online82platform92for1000geeks
The total number of digits present in the given string [ btechgeeks2online82platform92for1000geeks ] = 9
The total number of characters present in the given string [ btechgeeks2online82platform92for1000geeks ] = 41

Program to Calculate the Number of Digits and Letters in a String

There are several ways to calculate the total number of digits and letters in the given string some of them are:

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 isdigit() function and Count Variable(Static Input)

Approach:

  • Give the string as static input and store it in a  variable.
  • Take a variable to say stringdigits that stores the total digits in the given string.
  • Initialize the stringdigits to 0.
  • Take a variable to say stringcharacters that stores the total characters in the given string.
  • Initialize the stringcharacters to 0.
  • Traverse the given string using for loop.
  • Check if the character is a numerical digit or not using the isdigit() function.
  • If the character is a numerical digit then increment the value of stringdigits by 1.
  • Increase the stringcharacters by 1.
  • Print the total count of digits and characters present in the given string.
  • The Exit of the Program

Below is the implementation:

# Give the string as static input and save it in a variable.
given_strng = 'Hel34lo18th3is9is38 BTech23Geeks'
# Take a variable to say stringdigits that stores the total digits in the given string.
# Initialize the stringdigits to 0.
stringdigits = 0
# Take a variable to say stringcharacters that stores the total characters in the given string.
# Initialize the stringcharacters to 0.
stringcharacters = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Check if the character is a numerical digit or not using the isdigit() function.
    if(charact.isdigit()):
        # If the character is a numerical digit then increment the value of stringdigits by 1.
        stringdigits = stringdigits+1
    # Increase the stringcharacters by 1.
    stringcharacters = stringcharacters+1
# Print the total count of digits and characters present in the given string.
print(
    'The total number of digits present in the given string [', given_strng, '] = ', stringdigits)
print(
    'The total number of characters present in the given string [', given_strng, '] = ', stringcharacters)

Output:

The total number of digits present in the given string [ Hel34lo18th3is9is38 BTech23Geeks ] =  10
The total number of characters present in the given string [ Hel34lo18th3is9is38 BTech23Geeks ] =  32

Method #2:Using isdigit() function and Count Variable(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a  variable.
  • Take a variable to say stringdigits that stores the total digits in the given string.
  • Initialize the stringdigits to 0.
  • Take a variable to say stringcharacters that stores the total characters in the given string.
  • Initialize the stringcharacters to 0.
  • Traverse the given string using for loop.
  • Check if the character is a numerical digit or not using the isdigit() function.
  • If the character is a numerical digit then increment the value of stringdigits by 1.
  • Increase the stringcharacters by 1.
  • Print the total count of digits and characters present in the given string.
  • The Exit of the Program

Below is the implementation:

# Give the string as user input using the input() function and store it in a  variable.
given_strng = input('Enter some random string = ')
# Take a variable to say stringdigits that stores the total digits in the given string.
# Initialize the stringdigits to 0.
stringdigits = 0
# Take a variable to say stringcharacters that stores the total characters in the given string.
# Initialize the stringcharacters to 0.
stringcharacters = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Check if the character is a numerical digit or not using the isdigit() function.
    if(charact.isdigit()):
        # If the character is a numerical digit then increment the value of stringdigits by 1.
        stringdigits = stringdigits+1
    # Increase the stringcharacters by 1.
    stringcharacters = stringcharacters+1
# Print the total count of digits and characters present in the given string.
print(
    'The total number of digits present in the given string [', given_strng, '] = ', stringdigits)
print(
    'The total number of characters present in the given string [', given_strng, '] = ', stringcharacters)

Output:

Enter some random string = btechgeeks2online82platform92for1000geeks
The total number of digits present in the given string [ btechgeeks2online82platform92for1000geeks ] = 9
The total number of characters present in the given string [ btechgeeks2online82platform92for1000geeks ] = 41

Explanation:

  • A string must be entered by the user and saved in a variable.
  • The count variables are both set to zero.
  • The for loop is used to go over the characters in a string.
  • When a digit is encountered, the first count variable is incremented, and when a character is encountered, the second count variable is incremented.
  • The total number of digits and characters in the string is printed.

Method #3:Using isdigit() and len() functions(Static Input)

Approach:

  • Give the string as static input and store it in a  variable.
  • Take a variable to say stringdigits that stores the total digits in the given string.
  • Initialize the stringdigits to 0.
  • Traverse the given string using for loop.
  • Check if the character is a numerical digit or not using the isdigit() function.
  • If the character is a numerical digit then increment the value of stringdigits by 1.
  • Calculate the length of the given string using the len() function.
  • The length of a given string gives the total number of characters present in the given string.
  • Print the total count of digits and characters present in the given string.
  • The Exit of the Program

Below is the implementation:

# Give the string as static input and save it in a variable.
given_strng = 'Hel34lo18th3is9is38 BTech23Geeks'
# Take a variable to say stringdigits that stores the total digits in the given string.
# Initialize the stringdigits to 0.
stringdigits = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Check if the character is a numerical digit or not using the isdigit() function.
    if(charact.isdigit()):
        # If the character is a numerical digit then increment the value of stringdigits by 1.
        stringdigits = stringdigits+1
# Calculate the length of the given string using the len() function.
# The length of a given string gives the total
# number of characters present in the given string.
strngLength = len(given_strng)
# Print the total count of digits and characters present in the given string.
print(
    'The total number of digits present in the given string [', given_strng, '] = ', stringdigits)
print(
    'The total number of characters present in the given string [', given_strng, '] = ', strngLength)

Output:

The total number of digits present in the given string [ Hel34lo18th3is9is38 BTech23Geeks ] =  10
The total number of characters present in the given string [ Hel34lo18th3is9is38 BTech23Geeks ] =  32

Method #4:Using isdigit() and len() functions(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a  variable.
  • Take a variable to say stringdigits that stores the total digits in the given string.
  • Initialize the stringdigits to 0.
  • Traverse the given string using for loop.
  • Check if the character is a numerical digit or not using the isdigit() function.
  • If the character is a numerical digit then increment the value of stringdigits by 1.
  • Calculate the length of the given string using the len() function.
  • The length of a given string gives the total number of characters present in the given string.
  • Print the total count of digits and characters present in the given string.
  • The Exit of the Program

Below is the implementation:

# Give the string as user input using the input() function and store it in a  variable.
given_strng = input('Enter some random string = ')
# Take a variable to say stringdigits that stores the total digits in the given string.
# Initialize the stringdigits to 0.
stringdigits = 0
# Traverse the given string using for loop.
for charact in given_strng:
    # Check if the character is a numerical digit or not using the isdigit() function.
    if(charact.isdigit()):
        # If the character is a numerical digit then increment the value of stringdigits by 1.
        stringdigits = stringdigits+1
# Calculate the length of the given string using the len() function.
# The length of a given string gives the total
# number of characters present in the given string.
strngLength = len(given_strng)
# Print the total count of digits and characters present in the given string.
print(
    'The total number of digits present in the given string [', given_strng, '] = ', stringdigits)
print(
    'The total number of characters present in the given string [', given_strng, '] = ', strngLength)

Output:

Enter some random string = btechgeeks278onlineplatform2391forgeeks
The total number of digits present in the given string [ btechgeeks278onlineplatform2391forgeeks ] = 7
The total number of characters present in the given string [ btechgeeks278onlineplatform2391forgeeks ] = 39

Related Programs:

Python Program to Calculate the Number of Digits and Letters in a String Read More »