Python

Program to Flipping the Binary Bits

Python Program to Flipping the Binary Bits

Given a binary string, the task is to flip the bits in the given binary string in Python.

Examples:

Example1:

Input:

Given Binary string =1101010001001

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Example2:

Input:

Given Binary string =00110011111

Output:

The given binary string before flipping bits is [ 00110011111 ]
The given binary string after flipping bits is [ 11001100000 ]

Program to Flipping the Binary Bits in Python

Below are the ways to flip the bits in the given binary string in Python.

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the binary string as static input and store it in a variable.
  • Take an empty string(say flipbinary) which is the result after flipping the bits and initialize its value to a null string using “”.
  • Traverse the given binary string using For loop.
  • If the bit is 1 then concatenate the flipbinary with 0.
  • Else concatenate the flipbinary with 1.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as static input and store it in a variable.
gvnbinstring = '1101010001001'
# Take an empty string(say flipbinary) which is the result after flipping the bits
# and initialize its value to a null string using "".
flipbinary = ""
# Traverse the given binary string using For loop.
for bitval in gvnbinstring:
    # If the bit is 1 then concatenate the flipbinary with 0.
    if bitval == '1':
        flipbinary += '0'
    # Else concatenate the flipbinary with 1.
    else:
        flipbinary += '1'
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the binary string as user input using input() and store it in a variable.
  • Take an empty string(say flipbinary) which is the result after flipping the bits and initialize its value to a null string using “”.
  • Traverse the given binary string using For loop.
  • If the bit is 1 then concatenate the flipbinary with 0.
  • Else concatenate the flipbinary with 1.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as user input using input() and store it in a variable.
gvnbinstring = input('Enter some random binary string = ')
# Take an empty string(say flipbinary) which is the result after flipping the bits
# and initialize its value to a null string using "".
flipbinary = ""
# Traverse the given binary string using For loop.
for bitval in gvnbinstring:
    # If the bit is 1 then concatenate the flipbinary with 0.
    if bitval == '1':
        flipbinary += '0'
    # Else concatenate the flipbinary with 1.
    else:
        flipbinary += '1'
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

Enter some random binary string = 0011100110101010
The given binary string before flipping bits is [ 0011100110101010 ]
The given binary string after flipping bits is [ 1100011001010101 ]

Method #3: Using replace() function (Static Input)

Approach:

  • Give the binary string as static input and store it in a variable.
  • Replace all 1’s present in the given binary string with some random character like p.
  • Replace all 0’s present in the given binary string with 1.
  • Replace all p’s present in the given binary string with 0.
  • Here ‘p’ acts as a temporary variable.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as static input and store it in a variable.
gvnbinstring = '1101010001001'

# Replace all 1's present in the given binary string
# with some random character like p.
flipbinary = gvnbinstring.replace('1', 'p')
# Replace all 0's present in the given
# binary string with 1.
flipbinary = flipbinary.replace('0', '1')
# Replace all p's present in the given
# binary string with 0.
# Here 'p' acts as a temporary variable.
flipbinary = flipbinary.replace('p', '0')
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Method #4: Using replace() function (User Input)

Approach:

  • Give the binary string as user input using input() and store it in a variable.
  • Replace all 1’s present in the given binary string with some random character like p.
  • Replace all 0’s present in the given binary string with 1.
  • Replace all p’s present in the given binary string with 0.
  • Here ‘p’ acts as a temporary variable.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as user input using input() and store it in a variable.
gvnbinstring = input('Enter some random binary string = ')

# Replace all 1's present in the given binary string
# with some random character like p.
flipbinary = gvnbinstring.replace('1', 'p')
# Replace all 0's present in the given
# binary string with 1.
flipbinary = flipbinary.replace('0', '1')
# Replace all p's present in the given
# binary string with 0.
# Here 'p' acts as a temporary variable.
flipbinary = flipbinary.replace('p', '0')
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

Enter some random binary string = 00110011111
The given binary string before flipping bits is [ 00110011111 ]
The given binary string after flipping bits is [ 11001100000 ]

Related Programs:

Program to Print all the Prime Numbers within a Given Range

Python Program to Print all the Prime Numbers within a Given Range

Given the upper limit range, the task is to print all the prime numbers in the given range in Python.

Examples:

Example1:

Input:

given number = 95

Output:

The prime numbers from 2 to upper limit [ 95 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89

Example2:

Input:

given number = 52

Output:

Enter some random upper limit range = 52
The prime numbers from 2 to upper limit [ 52 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Python Program to Print all the Prime Numbers within a Given Range

There are several ways to print all the prime numbers from 2 to the upper limit range some of them are:

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1:Using for loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Set the first for loop to have a range of 2 to the upper limit range.
  • Take a temporary variable which is the count variable and initialize it to zero.
  • Allow the second for loop to have a range of 2 to half the number (excluding 1 and the number itself).
  • Then, using the if statement, determine the number of divisors and increment the count variable each time.
  • The number is prime if the number of divisors is lower than or equal to zero.
  • Prime numbers till the given upper limit range are printed.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
givenNumbr = 95
print('The prime numbers from 2 to upper limit [', givenNumbr, '] :')
# Set the first for loop to have a range of 2 to the upper limit range.
for valu in range(2, givenNumbr+1):
  # Take a temporary variable which is the count variable and initialize it to zero.
    cntvar = 0
    # Allow the second for loop to have a range of 2 to
    # half the number (excluding 1 and the number itself).
    for divi in range(2, valu//2+1):
      # Then, using the if statement, determine the number of divisors
      # and increment the count variable each time.
        if(valu % divi == 0):
            cntvar = cntvar+1
    # The number is prime if the number of divisors is lower than or equal to zero.
    if(cntvar <= 0):
        print(valu, end=' ')

Output:

The prime numbers from 2 to upper limit [ 95 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89

All the prime numbers till the upper limit range are printed.

Method #2:Using for loop(User Input)

Approach:

  • Give the number as user input with the help of the int(input()) function and store it in a variable.
  • Set the first for loop to have a range of 2 to the upper limit range.
  • Take a temporary variable which is the count variable and initialize it to zero.
  • Allow the second for loop to have a range of 2 to half the number (excluding 1 and the number itself).
  • Then, using the if statement, determine the number of divisors and increment the count variable each time.
  • The number is prime if the number of divisors is lower than or equal to zero.
  • Prime numbers till the given upper limit range are printed.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input with the help
# of the int(input()) function and store it in a variable.
givenNumbr = int(input('Enter some random upper limit range = '))
print('The prime numbers from 2 to upper limit [', givenNumbr, '] :')
# Set the first for loop to have a range of 2 to the upper limit range.
for valu in range(2, givenNumbr+1):
  # Take a temporary variable which is the count variable and initialize it to zero.
    cntvar = 0
    # Allow the second for loop to have a range of 2 to
    # half the number (excluding 1 and the number itself).
    for divi in range(2, valu//2+1):
      # Then, using the if statement, determine the number of divisors
      # and increment the count variable each time.
        if(valu % divi == 0):
            cntvar = cntvar+1
    # The number is prime if the number of divisors is lower than or equal to zero.
    if(cntvar <= 0):
        print(valu, end=' ')

Output:

Enter some random upper limit range = 52
The prime numbers from 2 to upper limit [ 52 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Explanation:

  • The user must enter the range’s upper limit and save it in a separate variable.
  • The first for loop runs until the user enters an upper limit.
  • The count variable is initially set to 0.
  • Because the for loop runs from 2 to half of the number, 1 and the number itself is not considered divisors.
  • If the remainder is equal to zero, the if statement looks for the number’s divisors.
  • The count variable counts the number of divisors, and if the count is less than or equal to zero, the integer is prime.
  • If the count exceeds zero, the integer is not prime.
  • All the prime numbers till the upper limit range are printed.

Related Programs:

Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion

Python Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion

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

If we examine closely at this problem, we can see that the concept of “loop” is to track some counter value, such as “i=0″ till I = higher”. So, if we aren’t permitted to use loops, how can we track something in Python?
One option is to use ‘recursion,’ however we must be careful with the terminating condition. Here’s a solution that uses recursion to output numbers.

Examples:

Example1:

Input:

Enter some upper limit range = 11

Output:

The numbers from 1 to 11 without using loops : 
1
2
3
4
5
6
7
8
9
10
11

Example2:

Input:

Enter some upper limit range = 28

Output:

The numbers from 1 to 28 without using loops : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Program to Print Numbers in a Range (1,upper) Without Using any Loops/Recursive Approach

Below are the ways to print all the numbers in the range from 1 to upper without using any loops or by using recursive approach.

Method #1:Using Recursive function(Static Input)

Approach:

  • Give the upper limit range using static input.
  • Create a recursive function.
  • Create a basic case for that function in when the integer is greater than zero.
  • If the number is more than zero, call the function again with the input set to the number -1.
  • Print the number.
  • Exit of program.

Below is the implementation:

# function which prints numbers from 1 to gievn upper limit range
# without loop/by using recursion


def printNumbers(upper_limit):
  # checking if th upper limit value is greater than 0 using if statement
    if(upper_limit > 0):
      # If the number is more than zero, call the function again with
      # the input set to the number -1.
        printNumbers(upper_limit-1)
        # Print the upper limit
        print(upper_limit)


# giveen upper limt range
upper_limit = 28
print('The numbers from 1 to', upper_limit, 'without using loops : ')
# passing the given upper limit range to printNumbers
printNumbers(upper_limit)

Output:

The numbers from 1 to 28 without using loops : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Method #2:Using Recursive function(User Input)

Approach:

  • Scan the upper limit range using int(input()).
  • Create a recursive function.
  • Create a basic case for that function in when the integer is greater than zero.
  • If the number is more than zero, call the function again with the input set to the number -1.
  • Print the number.
  • Exit of program.

Below is the implementation:

# function which prints numbers from 1 to gievn upper limit range
# without loop/by using recursion


def printNumbers(upper_limit):
  # checking if th upper limit value is greater than 0 using if statement
    if(upper_limit > 0):
      # If the number is more than zero, call the function again with
      # the input set to the number -1.
        printNumbers(upper_limit-1)
        # Print the upper limit
        print(upper_limit)


# giveen upper limt range
upper_limit = int(input('Enter some upper limit range = '))
print('The numbers from 1 to', upper_limit, 'without using loops : ')
# passing the given upper limit range to printNumbers
printNumbers(upper_limit)

Output:

Enter some upper limit range = 11
The numbers from 1 to 11 without using loops : 
1
2
3
4
5
6
7
8
9
10
11

Explanation:

  • The user must enter the range’s top limit.
  • This value is supplied to the recursive function as an argument.
  • The recursive function’s basic case is that number should always be bigger than zero.
  • If the number is greater than zero, the function is called again with the argument set to the number minus one.
  • The number has been printed.
  • The recursion will continue until the number is less than zero.
Program to Check Whether a String is a Palindrome or not Using Recursion

Python Program to Check Whether a String is a Palindrome or not Using Recursion

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

Recursion in Python:

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

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

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

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

Strings in Python:

A string is typically a piece of text (sequence of characters). To represent a string in Python, we use ” (double quotes) or ‘ (single quotes).

Examples:

Example1:

Input:

given string = "btechgeeksskeeghcetb"

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

Example2:

Input:

given string = "aplussulpa"

Output:

The given string [ aplussulpa ] is a palindrome

Program to Check Whether a String is a Palindrome or not Using Recursion

Below are the ways to Check Whether a String is a Palindrome or not using the recursive approach in Python:

1)Using Recursion (Static Input)

Approach:

  • Give some string as static input and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some string as static input and store it in a variable.
given_str = 'btechgeeksskeeghcetb'
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

2)Using Recursion (User Input)

Approach:

  • Give some random string as user input using the input() function and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some random string as user input using the input()
# function and store it in a variable.
given_str = input('Enter some random string = ')
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

Enter some random string = aplussulpa
The given string [ aplussulpa ] is a palindrome

Explanation:

  • A string must be entered by the user.
  • A recursive function gets the string as an argument.
  • If the length of the string is less than one, the function returns True.
  • If the end letter is the same as the initial letter, the function is repeated recursively with the argument as the sliced list with the first and last characters removed, otherwise, false is returned.
  • The if statement is used to determine whether the returned value is True or False, and the result is printed.

Related Programs:

Program to Search the Number of Times a Particular Number Occurs in a List

Python Program to Search the Number of Times a Particular Number Occurs in a List

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

Lists in Python:

The Python list is a straightforward ordered list of items. Python lists are extremely powerful since the objects in them do not have to be homogeneous or even of the same type. Strings, numbers, and characters, as well as other lists, can all be found in a Python list. Python lists are also mutable: once stated, they can be easily altered via a variety of list methods. Let’s look at how to use these techniques to handle Python lists.

Given a list and a element, the task is to write a  Python Program to Determine the Number of Occurrences of a Specific Number in a given List

Examples:

Examples1:

Input:

given list = ["my", "name", "is", "BTechGeeks", "coding", "platform", "for", "BTechGeeks"]

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Examples2:

Input:

given list = [5, 9, 1, 3, 6, 9, 2, 12, 8]

Output:

The count of the element ' 9 ' in the list [5, 9, 1, 3, 6, 9, 2, 12, 8] = 2

Python Program to Search the Number of Times a Particular Number Occurs in a List

There are several ways to determine the Number of Occurrences of a Specific Number in a given List some of them are:

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.

Method #1: Using a Counter Variable

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Take a variable which stores the count of the element say countEleme and initialize it to 0.
  • Traverse the given list using for loop.
  • If the iterator element is equal to the given element.
  • Then increment the countEleme value by 1.
  • Print the countEleme.

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Take a variable which stores the count of the element
# say totalCount and initialize it to 0.
countEleme = 0
# Traverse the given list using for loop.
for value in given_list:
    # if the value is equal too given_element then increase the countEleme by 1
    if(value == given_element):
        countEleme = countEleme+1
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #2: Using Count() function

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Count the given element in the list using count() function.
  • Print the countEleme.

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Count the given element in the list using count() function.
countEleme = given_list.count(given_element)
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #3: Using Counter() function

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Use Counter function which stores the frequency as values and element as keys in its dictionary
  • Print the value of the given element

Below is the implementation:

# importing counter function from collections
from collections import Counter
# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Using counter function
freqValues = Counter(given_list)
# Count the given element in the list
countEleme = freqValues[given_element]
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #4:Using List Comprehension

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Using list Comprehension checking if given element is equal to the iterator value
  • The count of the length of this new list gives the required answer

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Using list comprehension
elementlist = [eleme for eleme in given_list if eleme == given_element]

# Count the given element in the list using len function
countEleme = len(elementlist)
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Python Program to Print Even Number Pattern

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.

Given the number of rows, the task is to print Even Number Pattern in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows = 10

Output:

20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

Example2:

Input:

Given number of rows = 6

Output:

12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2

Program to Print Even Number Pattern in C, C++, and Python

Below are the ways to print Even Number Pattern 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.
  • Take a variable and initialize it with 2*double the number of rows say lastnumb.
  • Take another variable and initialize it with the lastnumb say evennumb.
  • Loop from 1 to the number of rows using For loop.
  • Initialize the evennumb with the lastnumb.
  • Loop from 0 to the iterator value of the parent For loop using another for loop(Nested For loop).
  • Print the evennumb.
  • Reduce the evennumb by 2.
  • 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.
numberOfRows = 10
# Take a variable and initialize it with 2*double the number of rows say lastnumb.
lastnumb = 2*numberOfRows
# Take another variable and initialize it with the lastnumb say evennumb.
evennumb = lastnumb
# Loop from 1 to the number of rows using For loop.
for m in range(1, numberOfRows+1):
    # Initialize the evennumb with the lastnumb.
    evennumb = lastnumb
    # Loop from 0 to the iterator value of the parent For loop using
    # another for loop(Nested For loop).
    for n in range(0, m):
        # Print the evennumb.
        print(evennumb, end=' ')
        # Reduce the evennumb by 2.
        evennumb = evennumb-2

    # Print the Newline character after the end of the inner loop.
    print()

Output:

20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

2) C++ Implementation

Below is the implementation:

#include <iostream>
#include <math.h>
using namespace std;
int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numberOfRows = 8;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            cout << evennumb << " ";

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

16 
16 14 
16 14 12 
16 14 12 10 
16 14 12 10 8 
16 14 12 10 8 6 
16 14 12 10 8 6 4 
16 14 12 10 8 6 4 2

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 numberOfRows = 8;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            printf("%d ", evennumb);

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

16 
16 14 
16 14 12 
16 14 12 10 
16 14 12 10 8 
16 14 12 10 8 6 
16 14 12 10 8 6 4 
16 14 12 10 8 6 4 2

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as user input and store it in a variable.
  • Take a variable and initialize it with 2*double the number of rows say lastnumb.
  • Take another variable and initialize it with the lastnumb say evennumb.
  • Loop from 1 to the number of rows using For loop.
  • Initialize the evennumb with the lastnumb.
  • Loop from 0 to the iterator value of the parent For loop using another for loop(Nested For loop).
  • Print the evennumb.
  • Reduce the evennumb by 2.
  • 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.
numberOfRows = int(input('Enter some random number of rows = '))
# Take a variable and initialize it with 2*double the number of rows say lastnumb.
lastnumb = 2*numberOfRows
# Take another variable and initialize it with the lastnumb say evennumb.
evennumb = lastnumb
# Loop from 1 to the number of rows using For loop.
for m in range(1, numberOfRows+1):
    # Initialize the evennumb with the lastnumb.
    evennumb = lastnumb
    # Loop from 0 to the iterator value of the parent For loop using
    # another for loop(Nested For loop).
    for n in range(0, m):
        # Print the evennumb.
        print(evennumb, end=' ')
        # Reduce the evennumb by 2.
        evennumb = evennumb-2

    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 10
20 
20 18 
20 18 16 
20 18 16 14 
20 18 16 14 12 
20 18 16 14 12 10 
20 18 16 14 12 10 8 
20 18 16 14 12 10 8 6 
20 18 16 14 12 10 8 6 4 
20 18 16 14 12 10 8 6 4 2

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
    // int(input()) and store it in a variable.
    int numberOfRows;
    cin >> numberOfRows;
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            cout << evennumb << " ";

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }

    return 0;
}

Output:

6
12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2 

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 numberOfRows;
    scanf("%d", &numberOfRows);
    // Take a variable and initialize it with 2*double the
    // number of rows say lastnumb.
    int lastnumb = 2 * numberOfRows;

    // Take another variable and initialize it with the
    // lastnumb say evennumb.
    int evennumb = lastnumb;
    //  Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numberOfRows; m++) {
        // Initialize the evennumb with the lastnumb.
        evennumb = lastnumb;
        // Loop from 0 to the iterator value of the parent
        // For loop using
        // another for loop(Nested For loop).
        for (int n = 0; n < m; n++) {
            // Print the evennumb.
            printf("%d ", evennumb);

            // Reduce the evennumb by 2.
            evennumb = evennumb - 2;
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

6
12 
12 10 
12 10 8 
12 10 8 6 
12 10 8 6 4 
12 10 8 6 4 2

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:

Program to Print an Inverted Star Pattern

Python Program to Print an Inverted Star Pattern | Python code to create an inverted Pyramid start pattern

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.

Python Program to Print the pattern of an Inverted Star: Given a number, the task is to print an Inverted Star Pattern in Python. In our python programming articles, you can also learn how to print a program of Inverted pyramid pattern and print inverted pyramid star pattern in python language.

Let’s see the examples of python program to print inverted star pattern from here

Example1:

Input:

given rows = 8

Output:

********
 *******
  ******
   *****
    ****
     ***
      **
       *

Example2:

Input:

given rows=10

Output:

**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

Here is the program to print Inverted Star Pattern:

# python 3 code to print inverted star
# pattern 
  
# n is the number of rows in which
# star is going to be printed.
n=11
  
# i is going to be enabled to
# range between n-i t 0 with a
# decrement of 1 with each iteration.
# and in print function, for each iteration,
# ” ” is multiplied with n-i and ‘*’ is
# multiplied with i to create correct
# space before of the stars.
for i in range (n, 0, -1):
    print((n-i) * ' ' + i * '*')

python 3 code to print inverted star pattern

Program to Print an Inverted Star Pattern in Python

Below are the ways to print an Inverted Star Pattern 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)Using for loop printing the inverted star pattern in Python(Static Input)

Using for loop printing the inverted star pattern in Python(Static Input)

Approach:

  • Give the number as static and store it in a variable
  • Use a for loop in which the value of k varies between n-1 and 0 and is decremented by one with each iteration.
  • Multiply empty spaces by n-i and ‘*’ by k then print both of them.
  • Exit of program.

Below is the implementation:

# given number numb
numb = 8
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
for k in range(numb, 0, -1):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((numb-k) * ' ' + k * '*')

Output:

********
 *******
  ******
   *****
    ****
     ***
      **
       *

Explanation:

  • Give the number as static and stored it in  a variable numb
  • The for loop allows I to range between n-1 and 0, with each iteration decrementing by one.
  • To maintain proper star spacing, ” ” is multiplied by n-i and ‘*’ is multiplied by I for each iteration.
  • The requisite pattern has been printed.

2)Using for loop printing the inverted star pattern in Python(User Input)

Using for loop printing the inverted star pattern in Python(User Input)

Approach:

  • Scan the given number using int(input()) and store it in a variable.
  • Use a for loop in which the value of k varies between n-1 and 0 and is decremented by one with each iteration.
  • Multiply empty spaces by n-i and ‘*’ by k then print both of them.
  • Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter the number of rows required = "))
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
for k in range(numb, 0, -1):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((numb-k) * ' ' + k * '*')

Output:

enter the number of rows required = 10
**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

3)Using while loop printing the inverted star pattern in Python(Static Input)

Using while loop printing the inverted star pattern in Python(Static Input)

Approach:

  • Give the number as static and store it in a variable
  • Using while loop iterate till number is greater than 0.
  • Multiply empty spaces by tem-i and ‘*’ by numb then print both of them.
  • Decrement the number by 1.
  • The Exit of the program.

Below is the implementation:

# given number numb
numb = 10
# Make a duplicate of the integer by storing it in a variable
tem = numb
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
while(numb > 0):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((tem-numb) * ' ' + numb * '*')
    # decrement the number by 1
    numb = numb-1

Output:

**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

4)Using while loop printing the inverted star pattern in Python(User Input)

Using while loop printing the inverted star pattern in Python(User Input)

Approach:

  • Scan the given number using int(input()) and store it in a variable.
  • Using while loop iterate till number is greater than 0.
  • Multiply empty spaces by tem-i and ‘*’ by numb then print both of them.
  • Decrement the number by 1.
  • Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter the number of rows required = "))
# Make a duplicate of the integer by storing it in a variable
tem = numb
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
while(numb > 0):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((tem-numb) * ' ' + numb * '*')
    # decrement the number by 1
    numb = numb-1

Output:

enter the number of rows required = 10
**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

Programs to print inverted half pyramid using *

This instance is similar to an upright pyramid but that here we begin from the total number of rows and in each iteration, we decrease the number of rows by 1.

Programs to print inverted half pyramid using star

Source Code:

rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):
    for j in range(0, i):
        print("* ", end=" ")
    
    print("\n")

output: 

* * * * *
* * * *
* * *
* *
*

Related Programs:

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

Python 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:

Program to Find the Gravitational Force Acting Between Two Objects

Python 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: