Python Program to Check if a Date is Valid and Print the Incremented Date

Program to Check if a Date is Valid and Print the Incremented Date

Given a date , the task is to Check if a Date is Valid and increment the given date and print it in python

Examples:

Example1:

Input:

given date ="11/02/2001"

Output:

The incremented given date is:  12 / 2 / 2001

Example2:

Input:

 given date = "29/02/2001"

Output:

The given date 29/02/2001 is not valid

Program to Check and Print the Incremented Date in Python

Below are the ways to check and implement the increment the given date in Python:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)By using if..elif..else Conditional Statements  and split() function(Static Input)

Approach:

  • Give the date in the format dd/mm/yyyy as static input
  • Separate the date by storing the day, month, and year in different variables.
  • Check the validity of the day, month, and year using various if-statements.
  • If the date is valid, increment it .
  • Print the increment date.
  • Exit of Program.

Below is the implementation:

# given given_data
given_date = "11/02/2001"
# splitting the given_data by / character to separate given_data,month and year
day, month, year = given_date.split('/')
day = int(day)
month = int(month)
year = int(year)
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
    maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
    maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
    maxdays = 29
else:
    maxdays = 28
if(month < 1 or month > 12):
    print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
    print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
    day = 1
    month = month+1
    print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
    day = 1
    month = 1
    year = year+1
    print("The incremented given date is: ", day, '/', month, '/', year)
else:
    day = day + 1
    print("The incremented given date is: ",  day, '/', month, '/', year)

Output:

The incremented given date is:  12 / 2 / 2001

Explanation:

  • Give the date in the format dd/mm/yyyy as static input.
  • The date is then divided, with the day, month, and year recorded in separate variables.
  • The date is invalid if it is not between 1 and 30 in the months of April, June, September, and November.
  • The date is invalid if it is not between 1 and 31 for the months of January, March, April, May, July, August, October, and December.
  • If the month is February, the day should be between 1 and 28 for non-leap years and between 1 and 29 for leap years.
  • If the date is correct, it should be increased.
  • The final incremented date is printed

2)By using if..elif..else Conditional Statements  and split() function(User Input)

Approach:

  • Scan the date, month and year as int(input()).
  • Separate the date by storing the day, month, and year in different variables.
  • Check the validity of the day, month, and year using various if-statements.
  • If the date is valid, increment it .
  • Print the increment date.
  • Exit of Program.

Below is the implementation:

# Scan the date, month and year as int(input()).
day = int(input("Enter some random day = "))
month = int(input("Enter some random month = "))
year = int(input("Enter some random year = "))
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
    maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
    maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
    maxdays = 29
else:
    maxdays = 28
if(month < 1 or month > 12):
    print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
    print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
    day = 1
    month = month+1
    print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
    day = 1
    month = 1
    year = year+1
    print("The incremented given date is: ", day, '/', month, '/', year)
else:
    day = day + 1
    print("The incremented given date is: ",  day, '/', month, '/', year)

Output:

Enter some random day = 11
Enter some random month = 2
Enter some random year = 2001
The incremented given date is: 12 / 2 / 2001

Related Programs:

Python Program to Print all Numbers in a Range Divisible by a Given Number

Program to Print all Numbers in a Range Divisible by a Given Number

Given three integers, the task is to print all values in the given range that are divisible by the third number, where the first number specifies the lower limit and the second number specifies the upper limit.

Examples:

Example1:

Input:

lower limit = 1 
upper limit = 263 
given number = 5

Output:

The numbers which are divisible by 5 from 17 to 263 are:
20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 
170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260

Example2:

Input:

Enter the lower limit = 37 
Enter the upper limit = 217 
Enter the given number = 3

Output:

The numbers which are divisible by 3 from 37 to 217 are:
39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111
114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168 
171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216

Example3:

Input:

Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7

Output:

The numbers which are divisible by 7 from 128 to 659 are:
133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 
315 322 329 336 343 350 357 364 371 378 385 392 399 406 413 420 427 434 441 448 455 462 469 476 483 490 
497 504 511 518 525 532 539 546 553 560 567 574 581 588 595 602 609 616 623 630 637 644 651 658

Program to Print all Numbers in a Range Divisible by a Given Number in Python

There are several ways to print all the numbers in the given range which are divisible by the given number some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using for loop(Static Input)

Approach:

  • Give three numbers as static input.
  • Using for loop, loop from lower limit to upper limit.
  • Using an if conditional statement, determine whether the iterator value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Exit of program

Below is the implementation:

# given lower limit
lower_limit = 17
# given upper limit
upper_limit = 263
# given number
numb = 5
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Using for loop, loop from lower limit to upper limit
for val in range(lower_limit, upper_limit):
    # Using an if conditional statement, determine whether
    # the iterator value is divisible by the given number.
    if(val % numb == 0):
        print(val, end=" ")

Output:

The numbers which are divisible by 5 from 17 to 263 are:
20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260

Method #2:Using for loop(User Input)

Approach:

  • Scan the lower limit, upper limit and the given number using int(input()).
  • Using for loop, loop from lower limit to upper limit.
  • Using an if conditional statement, determine whether the iterator value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Exit of program

Below is the implementation:

# Scanning the lower limit
lower_limit = int(input("Enter the lower limit = "))
# Scanning the upper limit
upper_limit = int(input("Enter the upper limit = "))
# Scanning the given number
numb = int(input("Enter the given number = "))
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Using for loop, loop from lower limit to upper limit
for val in range(lower_limit, upper_limit):
    # Using an if conditional statement, determine whether
    # the iterator value is divisible by the given number.
    if(val % numb == 0):
        print(val, end=" ")

Output:

Enter the lower limit = 37
Enter the upper limit = 217
Enter the given number = 3
The numbers which are divisible by 3 from 37 to 217 are:
39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111 114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168 171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216

Explanation:

  • The user must enter the upper and lower range limits.
  • The user is next required to provide the number to be divided from the user.
  • The value of i is between the lower and upper bounds.
  • Whenever the remainder of an integer divided by numb equals zero, the i is printed.

Method #3:Using While loop (User Input)

Approach:

  • Scan the lower limit, upper limit and the given number using int(input()).
  • Take a variable tempo and initialize it with lower limit.
  • Loop till tempo is less than upper limit using while loop.
  • Using an if conditional statement, determine whether the tempo value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Increment the tempo by 1
  • Exit of program

Below is the implementation:

# Scanning the lower limit
lower_limit = int(input("Enter the lower limit = "))
# Scanning the upper limit
upper_limit = int(input("Enter the upper limit = "))
# Scanning the given number
numb = int(input("Enter the given number = "))
# Take a variable tempo and initialize it with lower limit.
tempo = lower_limit
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Loop till tempo is less than upper limit using while loop.
while(tempo < upper_limit):
    # Using an if conditional statement, determine whether
    # the tempo value is divisible by the given number.
    if(tempo % numb == 0):
        print(tempo, end=" ")
    # Increment the tempo by 1
    tempo = tempo+1

Output:

Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7
The numbers which are divisible by 7 from 128 to 659 are:
133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 315 322 329 336 343 350 357 364 371 378 385 392 399 406 413 420 427 434 441 448 455 462 469 476 483 490 497 504 511 518 525 532 539 546 553 560 567 574 581 588 595 602 609 616 623 630 637 644 651 658

Related Programs:

Python Program to Convert Gray Code to Binary

Program to Convert Gray Code to Binary

Although binary numbers are the most common way to store numbers, they can be challenging to use in many situations, necessitating the usage of a binary number variant. This is where Gray codes come in handy.

Gray code has the property that two consecutive numbers differ in just one bit. Because of this quality, grey code cycles through multiple states with low effort and is used in K-maps, error correction, communication, and so on.

Gray Code is a type of minimum-change coding in which the two subsequent values differ by only one bit. More specifically, it is a binary number system in which only a single bit varies while travelling from one step to the next.

We will learn how to convert gray to binary code in Python in this tutorial. A binary number is a number written in the base-2 numeral system. As a result, a binary number is made up of only 0s and 1s. So, today, we’ll learn how to represent binary and gray code numbers, how to convert a gray number to binary code, and how to use a Python program to convert a gray number to binary code.

Examples:

Example1:

Input:

given gray code =1001000010

Output:

The Binary string of the given gray code= 1001000010 is 1110000011

Example2:

Input:

given gray code =1000111100110

Output:

The Binary string of the given gray code= 1000111100110 is 1111010111011

Program to Convert Gray Code to Binary in Python

Below are the ways to convert the given gray code to binary number in python:

Method #1:Using Right Shift Operator and  While loop( Static Input)

Approach:

  • Give the binary number as static.
  • The grayToBin has been defined.
  • It accepts as an argument the Gray codeword string.
  • It returns the binary number connected with it as a string.
  • If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in the corresponding binary number, where the 0th bit is the MSB, g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for I > 0.
  • Based on the preceding, b(i) = g(i) XOR g(i – 1) XOR… XOR g (0).
  • Thus, a Gray codeword g can be translated to its corresponding binary number by doing (g XOR (g >> 1) XOR (g >> 2) XOR… XOR (g >> m)), where m is such that g >> (m + 1) equals 0.

Below is the implementation:

# function which accepts the gray code  and returns the binary code  of the gray code
def grayToBin(grayCde):
   # Converting the given gray code to integer
    graynum = int(grayCde, 2)
   # Taking a temporary variable which stores the the gray code integer number
    tempnum = graynum
    # using while loop
    while tempnum != 0:
        tempnum >>= 1
        graynum ^= tempnum

        # bin(n) returns n's binary representation with the prefix '0b' removed
        # the slice operation removes the prefix.
    return bin(graynum)[2:]


# given gray code as static
graycode = "1001000010"
# passing this graycode to grayToBin function
resultbin = grayToBin(graycode)
print('The Binary string of the given gray code=', graycode, 'is', resultbin)

Output:

The Binary string of the given gray code= 1001000010 is 1110000011

Method #2:Using Right Shift Operator and  While loop( User Input)

Approach:

  • Scan the gray code string using input() function.
  • The grayToBin has been defined.
  • It accepts as an argument the Gray codeword string.
  • It returns the binary number connected with it as a string.
  • If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in the corresponding binary number, where the 0th bit is the MSB, g(0) = b(0) and b(i) = g(i) XOR b(i – 1) for I > 0.
  • Based on the preceding, b(i) = g(i) XOR g(i – 1) XOR… XOR g (0).
  • Thus, a Gray codeword g can be translated to its corresponding binary number by doing (g XOR (g >> 1) XOR (g >> 2) XOR… XOR (g >> m)), where m is such that g >> (m + 1) equals 0.

Below is the implementation:

# function which accepts the gray code  and returns the binary code  of the gray code
def grayToBin(grayCde):
   # Converting the given gray code to integer
    graynum = int(grayCde, 2)
   # Taking a temporary variable which stores the the gray code integer number
    tempnum = graynum
    # using while loop
    while tempnum != 0:
        tempnum >>= 1
        graynum ^= tempnum

        # bin(n) returns n's binary representation with the prefix '0b' removed
        # the slice operation removes the prefix.
    return bin(graynum)[2:]


# given gray code as static
graycode = input("Enter some random gray code string = ")
# passing this graycode to grayToBin function
resultbin = grayToBin(graycode)
print('The Binary string of the given gray code=', graycode, 'is', resultbin)

Output:

Enter some random gray code string = 1000111100110
The Binary string of the given gray code= 1000111100110 is 1111010111011

Related Programs:

Python Program to Print Reverse Pyramid of Numbers

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Given the number of rows of the pyramid, the task is to print a Reverse Pyramid of Numbers in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows = 10

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

Example2:

Input:

Given number of rows = 6

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

Program to Print Reverse Pyramid of Numbers in C,C++, and Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Loop from 1 to the number of rows using For loop.
  • Loop from the parent loop iterator value to 0 in decreasing order using another For loop(Nested For Loop).
  • Print the iterator value of the inner for loop.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows as static input and store it in a variable.
numbrrows = 10
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows):
    # Loop from the parent loop iterator value to 0 in decreasing order
    # using another For loop(Nested For Loop).
    for n in range(m, 0, -1):
        # Print the iterator value of the inner for loop.
        print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numbrrows = 10;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numbrrows = 10;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1 
6 5 4 3 2 1 
7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 1

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as user input and store it in a variable.
  • Loop from 1 to the number of rows using For loop.
  • Loop from the parent loop iterator value to 0 in decreasing order using another For loop(Nested For Loop).
  • Print the iterator value of the inner for loop.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Give the number of rows as user input using int(input()) and store it in a variable.

Below is the implementation:

# Give the number of rows as user input using int(input()) and store it in a variable.
numbrrows = int(input('Enter some random number of rows = '))
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows):
    # Loop from the parent loop iterator value to 0 in decreasing order
    # using another For loop(Nested For Loop).
    for n in range(m, 0, -1):
        # Print the iterator value of the inner for loop.
        print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

2) C++ Implementation

Give the number of rows as user input using cin and store it in a variable.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as user input using
    // cin and store it in a variable.
    int numbrrows;
    cin >> numbrrows;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

3) C Implementation

Give the number of rows as user input using scanf and store it in a variable.

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as user input using scanf and
    // store it in a variable.
    int numbrrows;
    scanf("%d", &numbrrows);
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m < numbrrows; m++) {
        // Loop from the parent loop iterator value to 0 in
        // decreasing order using another For loop(Nested
        // For Loop).
        for (int n = m; n > 0; n--) {
            // Print the iterator value of the inner for
            // loop.
            printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

6
1 
2 1 
3 2 1 
4 3 2 1 
5 4 3 2 1

Related Programs:

Python Program to Find the Gravitational Force Acting Between Two Objects

Program to Find the Gravitational Force Acting Between Two Objects

Gravitational Force:

The gravitational force is a force that attracts any two mass-bearing objects. The gravitational force is called attractive because it always strives to pull masses together rather than pushing them apart. In reality, every thing in the cosmos, including you, is tugging on every other item! Newton’s Universal Law of Gravitation is the name for this. You don’t have a significant mass, thus you’re not dragging on those other objects very much. Objects that are extremely far apart do not noticeably pull on each other either. However, the force exists and can be calculated.

Gravitational Force Formula :

Gravitational Force = ( G *  m1 * m2 ) / ( r ** 2 )

Given masses of two objects and the radius , the task is to calculate the Gravitational Force acting between the given two particles in Python.

Examples:

Example1:

Input:

mass1 = 1300012.67
mass2 = 303213455.953
radius = 45.4

Output:

The gravitational force of objects with masses 1300012.67 kg 303213455.953 kg  of radius= 45.4 = 12.761610184592419

Example2:

Input:

Enter the first mass of the object =2491855.892 
Enter the second mass of the object =9000872 
Enter the distance/radius between the objects =50

Output:

The gravitational force of objects with masses 24918552.892 kg 23145689000872.0 kg of radius= 50.0 = 15394799.86164859

Program to Find the Gravitational Force Acting Between Two Objects in Python

We will write the code which calculates the gravitational force acting between the particles and print it

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

1)Calculating the Gravitational Force  (Static Input)

Approach:

  • Take both the masses and the distance between the masses and store them in different variables  or give input as static
  • One of the variables should be set to the value of the gravitational constant, G.
  • The formula is used to calculate the force between the masses.
  • Print the force value, rounded up to two decimal places.
  • Exit the program.

Below is the implementation:

# given first mass
mass1 = 1300012.67
# given second mass
mass2 = 303213455.953
# enter the radius
radius = 45.4
# Given value of Gravitational Constant Gval
Gval = 6.673*(10**(-11))
# Calculating the value of the gravitational force Gforce
Gforce = (Gval*mass1*mass2)/(radius**2)
# printing the value of gravitational force
print("The gravitational force of objects with masses", str(mass1) +
      " kg "+str(mass2)+" kg ", "of radius=", radius, "=", Gforce)

Output:

The gravitational force of objects with masses 1300012.67 kg 303213455.953 kg  of radius= 45.4 = 12.761610184592419

2)Calculating the Gravitational Force  (User Input)

Approach:

  • Scan the masses and radius as a floating data type and store in different variables
  • One of the variables should be set to the value of the gravitational constant, G.
  • The formula is used to calculate the force between the masses.
  • Print the force value, rounded up to two decimal places.
  • Exit the program.

Below is the implementation:

# scanning  first mass as float
mass1 = float(input("Enter the first mass of the object ="))
# given second mass as float
mass2 = float(input("Enter the second mass of the object ="))
# enter the radius as float
radius = float(input("Enter the distance/radius between the objects ="))
# Given value of Gravitational Constant Gval
Gval = 6.673*(10**(-11))
# Calculating the value of the gravitational force Gforce
Gforce = (Gval*mass1*mass2)/(radius**2)
# printing the value of gravitational force
print("The gravitational force of objects with masses", str(mass1) +
      " kg "+str(mass2)+" kg ", "of radius=", radius, "=", Gforce)

Output:

Enter the first mass of the object =2491855.892
Enter the second mass of the object =9000872
Enter the distance/radius between the objects =50
The gravitational force of objects with masses 24918552.892 kg 23145689000872.0 kg of radius= 50.0 = 15394799.86164859

Related Programs:

Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character

Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character

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

Dictionaries in Python:

Dictionary is a mutable built-in Python Data Structure. It is conceptually related to List, Set, and Tuples. It is, however, indexed by keys rather than a sequence of numbers and can be thought of as associative arrays. On a high level, it consists of a key and its associated value. The Dictionary class in Python represents a hash-table implementation.

Given a string , the task is to create a Python program for creating a dictionary with the Key as the first character and the Value as words beginning with that character.

Examples:

Example1:

Input:

given string = "hello this is btechgeeks online programming platform to read the coding articles specially python language"

Output:

h ::: ['hello']
t ::: ['this', 'to', 'the']
i ::: ['is']
b ::: ['btechgeeks']
o ::: ['online']
p ::: ['programming', 'platform', 'python']
r ::: ['read']
c ::: ['coding']
a ::: ['articles']
s ::: ['specially']
l ::: ['language']

Example2:

Input:

given string = "this is btechgeeks today is monday and tomorrow is sunday sun sets in the east "

Output:

t ::: ['this', 'today', 'tomorrow', 'the']
i ::: ['is', 'in']
b ::: ['btechgeeks']
m ::: ['monday']
a ::: ['and']
s ::: ['sunday', 'sun', 'sets']
e ::: ['east']

Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character

Below are the ways to create a Python program for creating a dictionary with the Key as the first character and the Value as words beginning with that character.

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Using indexing, append ,items() function (Static Input)

Approach:

  • Give the string as static input .
  • Declare a dictionary which is empty using {} or dict()
  • Divide the string into words using split() and save them in a list.
  • Using a for loop and an if statement, determine whether the word already exists as a key in the dictionary.
  • If it is not present, use the letter of the word as the key and the word as the value to create a sublist in the list and append it to it.
  • If it is present, add the word to the associated sublist as the value.
  • The resultant dictionary will be printed.
  • Exit of Program

Below is the implementation:

# given string
given_string = "hello this is btechgeeks online programming platform to read the coding articles specially python language"
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Declare a dictionary which is empty using {} or dict()
resultdict = {}
# Traverse the list String
for stringword in listString:
  # checking if the first character of the word exists in dictionary resultdict keys or not
    if(stringword[0] not in resultdict.keys()):
        resultdict[stringword[0]] = []
        # adding this character to the resultdict
        resultdict[stringword[0]].append(stringword)
    else:
      # If it is present, add the word to the associated sublist as the value.
        if(stringword not in resultdict[stringword[0]]):
            resultdict[stringword[0]].append(stringword)
for key, value in resultdict.items():
    print(key, ":::", value)

Output:

h ::: ['hello']
t ::: ['this', 'to', 'the']
i ::: ['is']
b ::: ['btechgeeks']
o ::: ['online']
p ::: ['programming', 'platform', 'python']
r ::: ['read']
c ::: ['coding']
a ::: ['articles']
s ::: ['specially']
l ::: ['language']

Explanation:

  • A string must be entered by the user or give input as static and saved in a variable.
  • It is declared that the dictionary is empty.
  • The string is split down into words and kept in a list.
  • To iterate through the words in the list, a for loop is utilised.
  • An if statement is used to determine whether a word already exists as a key in the dictionary.
  • If it is not present, the letter of the word is used as the key and the word as the value, and they are appended to the list’s sublist.
  • If it is present, the word is added to the associated sublist as a value.
  • The final dictionary is printed

2)Using indexing, append ,items() function (User Input)

Approach:

  • Scan the given string using input() function.
  • Declare a dictionary which is empty using {} or dict()
  • Divide the string into words using split() and save them in a list.
  • Using a for loop and an if statement, determine whether the word already exists as a key in the dictionary.
  • If it is not present, use the letter of the word as the key and the word as the value to create a sublist in the list and append it to it.
  • If it is present, add the word to the associated sublist as the value.
  • The resultant dictionary will be printed.
  • Exit of Program

Below is the implementation:

# Scanning the given string
given_string = input("Enter some random string separated by spaces = ")
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Declare a dictionary which is empty using {} or dict()
resultdict = {}
# Traverse the list String
for stringword in listString:
  # checking if the first character of the word exists in dictionary resultdict keys or not
    if(stringword[0] not in resultdict.keys()):
        resultdict[stringword[0]] = []
        # adding this character to the resultdict
        resultdict[stringword[0]].append(stringword)
    else:
      # If it is present, add the word to the associated sublist as the value.
        if(stringword not in resultdict[stringword[0]]):
            resultdict[stringword[0]].append(stringword)
for key, value in resultdict.items():
    print(key, ":::", value)

Output:

Enter some random string separated by spaces = this is btechgeeks today is monday and tomorrow is sunday sun sets in the east
t ::: ['this', 'today', 'tomorrow', 'the']
i ::: ['is', 'in']
b ::: ['btechgeeks']
m ::: ['monday']
a ::: ['and']
s ::: ['sunday', 'sun', 'sets']
e ::: ['east']

Related Programs: