Random Choice of Random Module in Python with no Repeat

Random Choice of Random Module in Python with no Repeat

Given the upper limit and lower limit, the task is to generate n natural numbers which are not repeating in Python.

Examples:

Example1:

Input:

Given N=13
Given lower limit range =19
Given upper limit range =45

Output:

The random numbers present in the range from 19 to 45 are :
28 40 24 25 20 44 38 29 21 31 43

Example2:

Input:

Given N=19
Given lower limit range =23
Given upper limit range =41

Output:

The random numbers present in the range from 23 to 41 are : 26 27 40 38 37 41 30 35 36 23 25

Random choice of Random module in Python with no Repeat

Below are the ways to generate n natural numbers which are not repeating in Python.

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

Method #1: Using For Loop and randint function (Static Input)

Approach:

  • Import the random module using the import keyword.
  • Give the number n as static input and store it in a variable.
  • Give the lower limit range and upper limit range as static input and store them in two separate variables.
  • Take an empty list (say rndmnumbs) and initialize it with an empty list using [] or list().
  • Loop till n times using For loop.
  • Generate a random number using randint(lowerlimitrange,upperlimitrange) and store it in a variable.
  • Check whether the above random number is present in the list or not using not in operator.
  • If it is not in the list then append the element to the rndmnumbs list using the append() function.
  • Print the rndmnumbs.
  • The Exit of the Program.

Below is the implementation:

# Import the random module using the import keyword.
import random
# Give the number n as static input and store it in a variable.
numbe = 13
# Give the lower limit range and upper limit range as static input
# and store them in two separate variables.
lowerlimitrange = 19
upperlimitrange = 45
# Take an empty list (say rndmnumbs) and initialize it with an empty list
# using [] or list().
rndmnumbs = []
# Loop till n times using For loop.
for m in range(numbe):
        # Generate a random number using randint(lowerlimitrange,upperlimitrange)
    # and store it in a variable.
    randomnumbe = random.randint(lowerlimitrange, upperlimitrange)
    # Check whether the above random number is present in the list or not
    # using not in operator.
    if randomnumbe not in rndmnumbs:
        # If it is not in the list then append the element
        # to the rndmnumbs list using the append() function.
        rndmnumbs.append(randomnumbe)

# Print the rndmnumbs
print('The random numbers present in the range from',
      lowerlimitrange, 'to', upperlimitrange, 'are :')
for q in rndmnumbs:
    print(q, end=' ')

Output:

The random numbers present in the range from 19 to 45 are :
28 40 24 25 20 44 38 29 21 31 43

Method #2: Using For Loop and randint function (User Input)

Approach:

  • Import the random module using the import keyword.
  • Give the number n as user input using int(input()) and store it in a variable.
  • Give the lower limit range and upper limit range as user input using map(),int(),split(),input() functions.
  • Store them in two separate variables.
  • Take an empty list (say rndmnumbs) and initialize it with an empty list using [] or list().
  • Loop till n times using For loop.
  • Generate a random number using randint(lowerlimitrange,upperlimitrange) and store it in a variable.
  • Check whether the above random number is present in the list or not using not in operator.
  • If it is not in the list then append the element to the rndmnumbs list using the append() function.
  • Print the rndmnumbs.
  • The Exit of the Program.

Below is the implementation:

# Import the random module using the import keyword.
import random
# Give the number n as user input using int(input()) and store it in a variable.
numbe = int(input('Enter some random number = '))
# Give the lower limit range and upper limit range as user input
# using map(),int(),split(),input() functions.
# Store them in two separate variables.
lowerlimitrange = int(input('Enter random lower limit range = '))
upperlimitrange = int(input('Enter random upper limit range = '))
# Take an empty list (say rndmnumbs) and initialize it with an empty list
# using [] or list().
rndmnumbs = []
# Loop till n times using For loop.
for m in range(numbe):
        # Generate a random number using randint(lowerlimitrange,upperlimitrange)
    # and store it in a variable.
    randomnumbe = random.randint(lowerlimitrange, upperlimitrange)
    # Check whether the above random number is present in the list or not
    # using not in operator.
    if randomnumbe not in rndmnumbs:
        # If it is not in the list then append the element
        # to the rndmnumbs list using the append() function.
        rndmnumbs.append(randomnumbe)

# Print the rndmnumbs
print('The random numbers present in the range from',
      lowerlimitrange, 'to', upperlimitrange, 'are :')
for q in rndmnumbs:
    print(q, end=' ')

Output:

Enter some random number = 19
Enter random lower limit range = 23
Enter random upper limit range = 41
The random numbers present in the range from 23 to 41 are :
26 27 40 38 37 41 30 35 36 23 25

Related Programs:

Python Program to Union of Set of Tuples

Python Program to Union of Set of Tuples

In this tutorial, we will learn how to calculate the union of sets of tuples in Python. Let us begin by defining the union in set theory.
The set of every element in the collection of sets is the set of the union of sets. In the case of duplicate elements in different sets, the final union will only contain the specific element once. The letter ‘U’ represents the union.
This problem is centered on finding the union of sets of tuples, which indicates that the set is made up of tuple elements.

Examples:

Example1:

Input:

first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

Output:

first Union Second =  {('is', 200), ('this', 100), ('hello', 5)}
Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}
first Union Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}

Program to Union of Set of Tuples in Python

Below are the ways to find the union of the set of tuples in Python.

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

Method #1: Using  or( | ) operator

Approach:

  • Give the set of tuples as static input and store them in Separate Variables.
  • In Python, we may retrieve the union of a set of tuples by using the OR operator (|). In order to acquire the union of two variables, use the OR operator directly between them.
  • Calculate the union using | operator and store it in a variable.
  • Print the union.
  • The Exit of the Program.

Below is the implementation:

# Give the set of tuples as static input and store them in Separate Variables.
first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

# In Python, we may retrieve the union of a set of tuples
# by using the OR operator (|). In order to acquire the union of two variables,
# use the OR operator directly between them.
# Calculate the union using | operator and store it in a variable.

reslt1 = second | third
reslt2 = first | second
reslt3 = first | second | third
# Print the union of first and second
print("first Union Second = ", reslt2)
# print the union of second and third
print("Second Union third = ", reslt1)
# print the union of first second and third.
print("first Union Second Union third = ", reslt3)

Output:

first Union Second =  {('this', 100), ('is', 200), ('hello', 5)}
Second Union third =  {('this', 100), ('hello', 5), ('btechgeeks', 461), ('python', 234), ('is', 200)}
first Union Second Union third =  {('this', 100), ('hello', 5), ('btechgeeks', 461), ('python', 234), ('is', 200)}

Method #2: Using union() method

Approach:

  • Give the set of tuples as static input and store them in Separate Variables.
  • The set union() method returns the union of the set variables supplied as parameters. The first set uses the dot operator (.) to call the union() method, and the other set variables are given as arguments.
  • Calculate the union using the union() method and store it in a variable.
  • Print the union.
  • The Exit of the Program.

Below is the implementation:

# Give the set of tuples as static input and store them in Separate Variables.
first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

'''The set union() method returns the union of the set variables supplied as parameters.
The first set uses the dot operator (.) to call the union() method, and 
the other set variables are given as arguments.
Calculate the union using the union() method and store it in a variable.'''
reslt1 = second.union(third)
reslt2 = first.union(second)
reslt3 = first.union(second, third)
# Print the union of first and second
print("first Union Second = ", reslt2)
# print the union of second and third
print("Second Union third = ", reslt1)
# print the union of first second and third.
print("first Union Second Union third = ", reslt3)

Output:

first Union Second =  {('is', 200), ('this', 100), ('hello', 5)}
Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}
first Union Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}

Related Programs:

Python Program to Flipping the Binary Bits

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:

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

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:

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

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.

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

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:

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

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:

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

Program to Print an Inverted Star 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: