True pangram – Python Program to Check if a String is a Pangram or Not

Program to Check if a String is a Pangram or Not

Strings in Python:

True pangram: A Python string is an ordered collection of characters used to express and store text-based data. Strings are saved in an adjacent memory area as individual characters. It is accessible in both directions: forward and backward. Characters are merely symbols. Strings are immutable Data Types in Python, which means they cannot be modified once they are formed. Python check if string is all characters, Python check if string is latin, Python check if a string is all digits, Python check if string is a dictionary, It depends on function too whether pangram program in python without function or if not.

Pangram:

If a sentence or string contains all 26 letters of the English alphabet at least once, it is considered to be a pangram. There are some solutions for pangram (pangram hackerrank solution in python) are also considered.

Examples:

Example1:

Input:

given string ="Helloabcdfegjilknmporqstvuxwzy"

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Example2:

Input:

given string ="hellothisisbtechgeeks"

Output:

The given string hellothisisbtechgeeks is not a pangram

Python Program to Check if a String is a Pangram or Not

There are several ways to check if the given string is pangram or not some of them are:

Follow to check pangram python code

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

Method #1:Naive Approach

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • The brute force method is to take a string that contains all of the letters of the English alphabet.
  • Traverse through all of the alphabet’s characters string
  • Check to see if this character appears in the given string.
  • If it isn’t present, return False.
  • Return True at the end of the loop (which implies it is pangram)

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
def checkPangramString(string):

    # creating a new string (alphabet string which stores all the alphabets of the english language
    AlphabetString = 'abcdefghijklmnopqrstuvwxyz'

    # Traverse through the alphabets string
    for char in AlphabetString:
        # Check if this character is present in given string .
        if char not in string.lower():
            # if yes then this character is not available hence return False
            return False
    # After the end of loop return True (which implies it is pangram)
    return True


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Method #2:Using set() method

The following program can be easily implemented in Python by using the set() method.

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • Use the set() function to convert this string to a set.
  • Determine the length of the set.
  • If the length is 26, it is a pangram (since the English language has only 26 alphabets).
  • Otherwise, it is not a pangram.

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
def checkPangramString(string):

    # converting given string to set using set() function
    setString = set(string)
    # calculate the length of the set
    length = len(setString)
    # If the length is 26, it is a pangram so return true
    if(length == 26):
        return True
    else:
        return False


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Note:

This method is only applicable if the given string contains alphabets.

Method #3:Using Counter() function (Hashing)

The following program can be easily implemented in Python by using the counter() function

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • Calculate the frequency of all characters in the given string using Counter() method
  • Calculate the length of the Counter dictionary.
  • If the length is 26, it is a pangram (since the English language has only 26 alphabets).
  • Otherwise, it is not a pangram.

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
# importing counter from collections
from collections import Counter


def checkPangramString(string):

    # Calculate the frequency of all characters in the given string
    # using Counter() method
    frequ = Counter(string)
    # calculate the length of the frequency dictionary which is
    # returned from counter() function
    length = len(frequ)
    # If the length is 26, it is a pangram so return true
    if(length == 26):
        return True
    else:
        return False


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Note:

This method is only applicable if the given string contains alphabets.

Read Also: Python Program to Check a Number is Prime or Not

Test Yourself: 

  1. How to check whether a string is pangram or not in java?
  2. Write a python program to execute a string containing python code?
  3. Check if a string contains all letters of the alphabet python?
  4. How to check whether a string is pangram or not in c?
  5. Pangram hackerrank solution in python?
  6. How to check whether a string is pangram or not in c++?
  7. How to check whether a string is pangram or not in java?
  8. Python program to check if a string is a pangram or not?
  9. Python function to check whether a string is a pangram or not?
  10. How to check whether a string is pangram or not in python?

Related Programs:

Count palindromes java – Python Program to Count Palindrome Words in a Sentence

Program to Count Palindrome Words in a Sentence

Count palindromes java: Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Given a sentence/string the task is to count the number of palindromic words in the given string in Python.

Examples:

Example1:

Input:

Given Sentence =madam how are you

Output:

The total number of palindromic words in the given sentence { madam how are you } are 1

Example2:

Input:

Given Sentence = helleh this issi btechgeeksskeeghcetb pyyp

Output:

The total number of palindromic words in the given sentence { helleh this issi btechgeeksskeeghcetb pyyp } are  4

Program to Count Palindrome Words in a Sentence in Python

Below are the ways to Count Palindrome words in the given sentence in Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the sentence/string as static input and store it in a variable.
  • Take a variable palcnt which stores the count of palindromic words in the given sentence and initialize its value to 0.
  • Split the given sentence into a list of words using the built-in function split() and store it in a variable.
  • Traverse in this list of words using the For loop.
  • Inside the for loop,Reverse the iterator word using slicing and store it in a variable.
  • Check if this reverse word is equal to the iterator word(Palindrome Condition) using the If conditional statement.
  • If it is true then increment the value of palcnt by 1.
  • Print the palcnt value.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as static input and store it in a variable.
gvnsentence ="helleh this issi btechgeeksskeeghcetb pyyp"
# Take a variable palcnt which stores the count of palindromic words
# in the given sentence and initialize its value to 0.
palcnt = 0
# Split the given sentence into a list of words using
# the built-in function split() and store it in a variable.
sentcewords = gvnsentence.split()
# Traverse in this list of words using the For loop.
for itrword in sentcewords:
    # Inside the for loop,Reverse the iterator word
    # using slicing and store it in a variable.
    reveword = itrword[::-1]
    # Check if this reverse word is equal to the
    # iterator word(Palindrome Condition) using the If conditional statement.
    if(reveword == itrword):
        # If it is true then increment the value of palcnt by 1.
        palcnt = palcnt+1


# Print the palcnt value.
print(
    'The total number of palindromic words in the given sentence {', gvnsentence, '} are ', palcnt)

Output:

The total number of palindromic words in the given sentence { helleh this issi btechgeeksskeeghcetb pyyp } are  4

Method #2: Using For Loop (User Input)

Approach:

  • Give the sentence/string as user input using the input() function and store it in a variable.
  • Take a variable palcnt which stores the count of palindromic words in the given sentence and initialize its value to 0.
  • Split the given sentence into a list of words using the built-in function split() and store it in a variable.
  • Traverse in this list of words using the For loop.
  • Inside the for loop,Reverse the iterator word using slicing and store it in a variable.
  • Check if this reverse word is equal to the iterator word(Palindrome Condition) using the If conditional statement.
  • If it is true then increment the value of palcnt by 1.
  • Print the palcnt value.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as user input using the input() function and store it in a variable.
gvnsentence = input('Enter some random sentence =')
# Take a variable palcnt which stores the count of palindromic words
# in the given sentence and initialize its value to 0.
palcnt = 0
# Split the given sentence into a list of words using
# the built-in function split() and store it in a variable.
sentcewords = gvnsentence.split()
# Traverse in this list of words using the For loop.
for itrword in sentcewords:
    # Inside the for loop,Reverse the iterator word
    # using slicing and store it in a variable.
    reveword = itrword[::-1]
    # Check if this reverse word is equal to the
    # iterator word(Palindrome Condition) using the If conditional statement.
    if(reveword == itrword):
        # If it is true then increment the value of palcnt by 1.
        palcnt = palcnt+1


# Print the palcnt value.
print(
    'The total number of palindromic words in the given sentence {', gvnsentence, '} are ', palcnt)

Output:

Enter some random sentence =madam how are you
The total number of palindromic words in the given sentence { madam how are you } are 1

Answer these:

  1. Count palindrome words in a sentence python?
  2. Count palindrome words in a sentence in java?
  3. Write a function to find all the words in a string which are palindrome in c#?
  4. Given a sentence write a program to count the number of palindrome words in it in c?
  5. Write a function to find all the words in a string which are palindrome in python?
  6. Write a function to find all the words in a string which are palindrome java?
  7. Write a function to find all the words in a string which are palindrome in c?
  8. Python program to count words in a sentence?
  9. Python program to count number of words in a paragraph?
  10. Python program to count words in a string?
  11. Python program to count number of words in a sentence?
  12. Palindrome count program in python?

Related Programs:

Add column to csv python – Python: Add a Column to an Existing CSV File

Python Add a Column to an Existing CSV File

Methods to add a column to an existing CSV File

Add column to csv python: In this article, we will discuss how to add a column to an existing CSV file using csv.reader and csv.DictWriter  classes. Apart from appending the columns, we will also discuss how to insert columns in between other columns of the existing CSV file.

We also include these for beginners:

  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Python csv write to specific row and column
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Python add a column to an existing csv file
  • Python add a new column to csv
  • Python add csv column to list
  • Python pandas append column to csv
  • Add a line to a csv file python

Original CSV file content

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
  • Method 1-Add a column with the same values to an existing CSV file

Python add column to csv: In this, we see how we make one column and add it to our CSV file but all the values in this column are the same.

Steps will be to append a column in CSV file are,

  1. Open ‘input.csv’ file in read mode and create csv.reader object for this CSV file
  2. Open ‘output.csv’ file in write mode and create csv.writer object for this CSV file
  3. Using reader object, read the ‘input.csv’ file line by line
  4. For each row (read like a list ), append default text in the list.
  5. Write this updated list / row in the ‘output.csv’ using csv.writer object for this file.
  6. Close both input.csv and output.csv file.

Let see this with the help of an example

from csv import writer
from csv import reader
default_text = 'New column'
# Open the input_file in read mode and output_file in write mode
with open('example1.csv', 'r') as read_obj, \
        open('output_1.csv', 'w', newline='') as write_obj:
    # Create a csv.reader object from the input file object
    csv_reader = reader(read_obj)
    # Create a csv.writer object from the output file object
    csv_writer = writer(write_obj)
    # Read each row of the input csv file as list
    for row in csv_reader:
        # Append the default text in the row / list
        row.append(default_text)
        # Add the updated row / list to the output file
        csv_writer.writerow(row)
output_data=pd.read_csv('output_1.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New column
0 16.99 1.01 Female No Sun Dinner 2 New column
1 10.34 1.66 Male No Sun Dinner 3 New column
2 21.01 3.50 Male No Sun Dinner 3 New column
3 23.68 3.31 Male No Sun Dinner 2 New column
4 24.59 3.61 Female No Sun Dinner 4 New column

Here we see that new column is added but all value in this column is same.

Now we see how we can add different values in the column.

  •  Method 2-Add a column to an existing CSV file, based on values from other columns

How to add a new column to a csv file using python: In this method how we can make a new column but in this column the value we add will be a combination of two or more columns. As we know there is no direct function to achieve so we have to write our own function to achieve this task. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
add_column_in_csv('example1.csv', 'output_2.csv', lambda row, line_num: row.append(row[0] + '__' + row[1]))
output_data=pd.read_csv('output_2.csv')
output_data.head()

Output

total_bill tip sex smoker day time size total_bill__tip
0 16.99 1.01 Female No Sun Dinner 2 16.99__1.01
1 10.34 1.66 Male No Sun Dinner 3 10.34__1.66
2 21.01 3.50 Male No Sun Dinner 3 21.01__3.5
3 23.68 3.31 Male No Sun Dinner 2 23.68__3.31
4 24.59 3.61 Female No Sun Dinner 4 24.59__3.61

Here we see the new column is formed as the combination of the values of the 1st and 2nd column.

Explanation:

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is a merger of the first and second value of the list. It appended the column in the contents of example1.csv by merging values of the first and second columns and then saved the changes as output_2.csv files.

  • Method 3-Add a list as a column to an existing csv file

Python csv write column: In this method, we will add our own value in the column by making a list of our values and pass this into the function that we will make. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
l=[]
l.append("New Column")
rows = len(data.axes[0])
for i in range(rows):
    val=i+1
    l.append(val)
add_column_in_csv('example1.csv', 'output_3.csv', lambda row, line_num: row.append(l[line_num - 1]))
output_data=pd.read_csv('output_3.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New Column
0 16.99 1.01 Female No Sun Dinner 2 1
1 10.34 1.66 Male No Sun Dinner 3 2
2 21.01 3.50 Male No Sun Dinner 3 3
3 23.68 3.31 Male No Sun Dinner 2 4
4 24.59 3.61 Female No Sun Dinner 4 5

Explanation

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is an entry from our list l at index  line_num – 1.Thus all the entries in the list l are added as a column in the CSV.

So these are some of the methods to add new column in csv.

Test yourself:

  1. Write to a specific column in csv python pandas?
  2. Write to specific column csv python?
  3. How do i add a column to an existing csv file in python?
  4. How to add column in existing csv file using python?

 

Python Program to Print the Equilateral Triangle Pattern of Star

Python Program to Print the Equilateral Triangle Pattern of Star

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. They have tried to include all details like, python program to print equilateral triangle, print star pattern in python using for loop, python star pattern programs, python pattern programs, triangle pattern in python, star pattern in python using while loop, inverted equilateral triangle in python, python star pattern programs, python pattern programs, triangle pattern in python, python program to print the equilateral triangle pattern of star.

Given the number of rows, the task is to Print Equilateral triangle Pattern of Star in C, C++, and Python

Examples:

Example1:

Input:

Given number of rows = 8

Output:

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

Example2:

Input:

Given number of rows = 10
Given Character to print ='$'

Output

                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

Program to Print the Equilateral triangle Pattern of Star in C, C++, and Python

Below are the ways to Print the Equilateral triangle Pattern of Star in C, C++, and Python.

Method #1: Using For Loop (Star Character)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Take a variable to say g and initialize its value with (2*number of rows)-2.
  • Loop from 0 to the number of rows using For loop.
  • Loop from 0 to g using another For Loop(Inner For loop).
  • Print the space character in the inner For Loop.
  • Decrement the value of g by 1 after the end of the inner For loop.
  • Loop from 0 to m+1 using another For loop(Nested For loop) where m is the iterator value of the parent For loop.
  • Print the star character with space.
  • Print the Newline character after the end of the Two inner For loops.
  • 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 = 8
# Take a variable to say g and initialize its value with (2*number of rows)-2.
g = (2*numberOfRows)-2
# Loop from 0 to the number of rows using For loop.
for m in range(0, numberOfRows):
    # Loop from 0 to g using another For Loop(Inner For loop).
    for n in range(0, g):
      # Print the space character in the inner For Loop.
        print(end=" ")
    # Decrement the value of g by 1 after the end of the inner For loop.
    g = g-1
    # Loop from 0 to m+1 using another For loop(Nested For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(0, m+1):
      # Print the star character with space.
        print('*', end=" ")
    # Print the Newline character after the end of the Two inner For loops.
    print()

Output:

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

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 numberOfRows = 8;

    // Take a variable to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            cout << " ";
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the star character with space.
            cout << "* ";
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        cout << endl;
    }
    return 0;
}

Output:

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

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 = 13;

    // Take a variable to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            printf(" ");
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the star character with space.
            printf("* ");
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        printf("\n");
    }
    return 0;
}

Output:

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

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Scan the character to print as user input and store it in a variable.
  • Take a variable to say g and initialize its value with (2*number of rows)-2.
  • Loop from 0 to the number of rows using For loop.
  • Loop from 0 to g using another For Loop(Inner For loop).
  • Print the space character in the inner For Loop.
  • Decrement the value of g by 1 after the end of the inner For loop.
  • Loop from 0 to m+1 using another For loop(Nested For loop) where m is the iterator value of the parent For loop.
  • Print the star character with space.
  • Print the Newline character after the end of the Two inner For loops.
  • 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.
  • Give the Character as user input using input() and store it in another 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 = '))
# Give the character to print as user input using int(input()) and store it in another variable.
characte = input('Enter some random character to print = ')
# Take a variable to say g and initialize its value with (2*number of rows)-2.
g = (2*numberOfRows)-2
# Loop from 0 to the number of rows using For loop.
for m in range(0, numberOfRows):
    # Loop from 0 to g using another For Loop(Inner For loop).
    for n in range(0, g):
      # Print the space character in the inner For Loop.
        print(end=" ")
    # Decrement the value of g by 1 after the end of the inner For loop.
    g = g-1
    # Loop from 0 to m+1 using another For loop(Nested For loop)
    # where m is the iterator value of the parent For loop.
    for n in range(0, m+1):
      # Print the given character with space.
        print(characte, end=" ")
    # Print the Newline character after the end of the Two inner For loops.
    print()

Output

Enter some random number of rows = 10
Enter some random character to print = $
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

2) C++ Implementation

  • Give the number of rows as user input using cin and store it in a variable.
  • Give the Character as user input using cin and store it in another 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 numberOfRows;
    cin >> numberOfRows;
    // Create a character variable.
    char characte;
    // Give the character as user input using cin and store
    // it in another variable.
    cout << "Enter some random character to print = "
         << endl;
    cin >> characte;
    cout << endl;
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            cout << " ";
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the given character with space.
            cout << characte << " ";
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        cout << endl;
    }
    return 0;
}

Output

10
Enter some random character to print = $
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

3) C Implementation

  • Give the number of rows as user input using scanf and store it in a variable.
  • Give the Character as user input using scanf and store it in another 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);
    // Create a character variable.
    // Give the character as user input using scanf and
    // store it in another variable.
    char characte;
    scanf("%c", &characte);
    printf("\n");
    // Take a variable to say g and initialize its value
    // with (2*number of rows)-2.
    int g = (2 * numberOfRows) - 2;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < numberOfRows; m++) {
        // Loop from 0 to g using another For Loop(Inner For
        // loop).
        for (int n = 0; n < g; n++) {
            // Print the space character in the inner For
            // Loop.
            printf(" ");
        }
        // Decrement the value of g by 1 after the end of
        // the inner For loop.
        g = g - 1;
        // Loop from 0 to m+1 using another For loop(Nested
        // For loop) where m is the iterator value of the
        // parent For loop.
        for (int n = 0; n < m + 1; n++) {
            // Print the given character with space.
            printf("%c ",characte);
        }
        // Print the Newline character after the end of the
        // Two inner For loops.
        printf("\n");
    }
    return 0;
}

Output

10$
                  $ 
                 $ $ 
                $ $ $ 
               $ $ $ $ 
              $ $ $ $ $ 
             $ $ $ $ $ $ 
            $ $ $ $ $ $ $ 
           $ $ $ $ $ $ $ $ 
          $ $ $ $ $ $ $ $ $ 
         $ $ $ $ $ $ $ $ $ $

Related Programs:

Python n nn nnn nnnn – Program to Read a Number n and Compute n+nn+nnn in C++ and Python

Program to Read a Number n and Compute n+nn+nnn in C++ and Python

Python n nn nnn nnnn: In the previous article, we have discussed about Program to Clear the Rightmost Set Bit of a Number in C++ and Python. Let us learn Program to Read a Number n and Compute n+nn+nnn in C++ Program and Python.

Given a number n , the task is to calculate the value of n+ nn +nnn in C++ and Python.

Examples:

Example1:

Input:

given number = 8

Output:

The value of 8 + 88 + 888 = 984

Example2:

Input:

given number = 4

Output:

Enter any random number = 4
The value of 4 + 44 + 444 = 492

Example3:

Input:

given number = 9

Output:

The value of 9 + 99 + 999 = 1107

Program to Read a Number n and Compute n+nn+nnn in C++ and Python

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

There are several ways to calculate the value of n + nn + nnn in C++ and  python some of them are:

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

Method #1:Using String Concatenation (Static Input) in Python

Approach:

  • Give the input number as static.
  • Convert the number to a string and save it in a different variable.
  • Add the string twice to concatenate it and store it in another variable.
  • Then multiply the string by three and assign the result to the third variable.
  • Convert the second and third variables’ strings to integers.
  • Add the values from all the integers together.
  • Print the expression’s total value.
  • Exit of program

Below is the implementation:

# given number numb
numb = 8
# converting the given number to string
strnum = str(numb)
# Add the string twice to concatenate it and store it in another variable.
strnum1 = strnum+strnum
# Add the string thrice  to concatenate it and store it in another variable.
strnum2 = strnum+strnum+strnum
# converting the strnum1 and strnum2 from string to integer using int() function
intnum1 = int(strnum1)
intnum2 = int(strnum2)
# Calculating the result value
resultVal = numb+intnum1+intnum2
print("The value of", strnum, "+", strnum1, "+", strnum2, "=", resultVal)

Output:

The value of 8 + 88 + 888 = 984

Method #2:Using String Concatenation (User Input) in Python

Approach:

  • Scan the given number and store it in the numb variable.
  • Convert the number to a string and save it in a different variable.
  • Add the string twice to concatenate it and store it in another variable.
  • Add the string thrice to concatenate it and store it in another variable.
  • Convert the second and third variables strings to integers.
  • Add the values from all the integers together.
  • Print the expression’s total value.
  • Exit of program

Below is the implementation:

# Scan the give number
numb = int(input("Enter any random number = "))
# converting the given number to string
strnum = str(numb)
# Add the string twice to concatenate it and store it in another variable.
strnum1 = strnum+strnum
# Add the string thrice  to concatenate it and store it in another variable.
strnum2 = strnum+strnum+strnum
# converting the strnum1 and strnum2 from string to integer using int() function
intnum1 = int(strnum1)
intnum2 = int(strnum2)
# Calculating the result value
resultVal = numb+intnum1+intnum2
print("The value of", strnum, "+", strnum1, "+", strnum2, "=", resultVal)

Output:

Enter any random number = 4
The value of 4 + 44 + 444 = 492

Method #3:Using String Concatenation (Static Input) in C++

Approach:

  • Give the input number as static.
  • Convert the number to a string  using to_string() function in C++ and save it in a different variable.
  • Add the string twice to concatenate it and store it in another variable.
  • Add the string thrice to concatenate it and store it in another variable.
  • Convert the second and third variables strings to integers using stoi() function.
  • Add the values from all the integers together.
  • Print the expression’s total value.
  • Exit of program

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // given number numb
    int numb = 9;
    // converting the given number to string
    string strnum = to_string(numb);

    // Add the string twice to concatenate it and store it
    // in another variable.
    string strnum1 = strnum + strnum;
    // Add the string thrice to concatenate it and store it
    // in another variable.
    string strnum2 = strnum + strnum + strnum;
    // converting the strnum1 and strnum2 from string to
    // integer using stoi() function
    int intnum1 = stoi(strnum1);
    int intnum2 = stoi(strnum2);
    // Calculating the result value
    int resultVal = numb + intnum1 + intnum2;
    cout << "The value of " << strnum << " + " << strnum1
         << " + " << strnum2 << " = " << resultVal;
    return 0;
}

Output:

The value of 9 + 99 + 999 = 1107

Also Read: Python Program to Compute the Value of Euler’s Number ,Using the Formula: e = 1 + 1/1! + 1/2! + …… 1/n!

Answer yourself:

  1. Read a number n and compute nnnnnn in python?
  2. Input an integer n and computes the value of nnnnnn?
  3. nnnnnnnn1000 n?
  4. How to print nnnnnn in python?
  5. Input an integer (n and computes the value of n+nn+nnn)?
  6. nnn+nn+n+n+n=1000 n=?
  7. How to print n+nn+nnn in python?
  8. Read a number n and compute n+nn+nnn in python?
  9. Calculate n + nn + nnn + … + n(n times) in c++?

Related Programs:

Python pythagorean triples – Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Python pythagorean triples: In the previous article, we have discussed about Program to Print Collatz Conjecture for a Given Number in C++ and Python. Let us learn Program to Determine all Pythagorean Triplets in C++ Program.

A Pythagorean triplet is a collection of three positive numbers, a, b, and c, such that a^2 + b^2 = c^2. Some things you have to notice while reading.

  • Program to check pythagorean triples in c
  • Pythagorean triples list
  • Pythagorean triples program in java
  • Pythagorean triples in python assignment expert
  • Pythagorean triples leetcode
  • Pythagorean triples hackerrank solution

Given a limit, find all Pythagorean Triples with values less than that limit.

Examples:

Example1:

Input:

given upper limit =63

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Example2:

Input:

given upper limit =175

Output:

printing the Pythagorean triplets till the upper limit 175 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Find all Pythagorean triplets in the given range in C++ and Python

Pythagorean triples c program: A simple solution is to use three nested loops to generate these triplets that are less than the provided limit. Check if the Pythagorean condition is true for each triplet; if so, print the triplet. This solution has a time complexity of O(limit3), where ‘limit’ is the stated limit.

An Efficient Solution will print all triplets in O(k) time, where k is the number of triplets to be printed. The solution is to apply the Pythagorean triplet’s square sum connection, i.e., addition of squares a and b equals square of c, and then represent these numbers in terms of m and n.

For every choice of positive integer m and n, the formula of Euclid creates Pythagorean Triplets:

a=m^2 -n^2

b= 2 * m * n

c= m ^2 +n^2

Below is the implementation of efficient solution in C++ and 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)Finding all Pythagorean till the given limit in Python

Approach:

  • Scan the upper limit or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

# enter the upper limit till you find pythagorean triplets
upper_limit = 63
n3 = 0
a = 2
print("printing the pythagorean triplets till the upper limit", upper_limit, ":")
while(n3 < upper_limit):
    for b in range(1, a+1):
        n1 = a*a-b*b
        n2 = 2*a*b
        n3 = a*a+b*b
        if(n3 > upper_limit):
            break
        if(n1 == 0 or n2 == 0 or n3 == 0):
            break
        print(n1, n2, n3)
    a = a+1

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Explanation:

The upper limit / input should be entered by a user as static, and stored in a variable.
The value of Pythagorean triplets using the formula is used during and for loops.
The loop breaks out if the value of a side is greater than the upper boundary, or if one side is 0.
The triplets will then be printed.

2)Finding all Pythagorean till the given limit in C++

Approach:

  • Scan the upper limit using cin or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{

    // enter the upper limit till you find pythagorean
    // triplets
    int upper_limit = 175;
    int n3 = 0;
    int a = 2;
    cout << "printing the pythagorean triplets till the "
            "upper limit"
         << upper_limit << ":" << endl;
    while (n3 < upper_limit) {
        for (int b = 1; b <= a; b++) {
            int n1 = a * a - b * b;
            int n2 = 2 * a * b;
            n3 = a * a + b * b;
            if (n3 > upper_limit)
                break;
            if (n1 == 0 or n2 == 0 or n3 == 0)
                break;
            cout << n1 << " " << n2 << " " << n3 << endl;
        }
        a = a + 1;
    }
    return 0;
}

Output:

printing the Pythagorean triplets till the upper limit175:
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Answer yourself:

  1. Write a program to print all pythagorean triplets between 1 to 100?
  2. Find all pythagorean triples below the given limit?
  3. Program to determine all pythagorean triplets in the range in c++ and python?

Related Programs:

Python Interview Questions on Decision Making and Loops

Python Interview Questions on Decision Making and Loops

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels. You can observe Python coding questions and answers, python programming interview questions and answers pdf, Python tricky interview questions, Python interview questions for 5 years experience, Tcs python interview questions, Python interview questions and answers, Python interview questions on loops, python decision making and loops, Python interview questions on decorators, Python interview questions machine learning, Python interview questions on dictionary, Python interview questions in deloitte, Python interview questions on algorithms and data structures.

Python Interview Questions on Decision Making and Loops

Control Statements

Control statements are used to control the flow of program execution. They help in deciding the next steps under specific conditions also allow repetitions of the program a certain number of times.
Two types of control statements are as follows:

1. Conditional branching

  • If
    Syntax:
    if (condition): to do statement
    If the condition evaluates to be true only then if code under if block will be executed.
  • if. . .else Syntax:
    if (condition): to do statement else:
    to do statement
  • Nested if statements Syntax:
    if (condition1):
    to dd statement elif(condition2):
    else do this
    elif(condition3):
    else do this

2. Loops

  • while: repeat a block of statements as long as a given condition is true
    Syntax:
    while(condition): ;
    to do statement
  • for: repeat a block of statements for a certain number of times
    , Syntax: ‘
    for < iterating_variable > in sequence:
    Repeat these steps
  • nested loops

Question 1.
What would be the output for the following piece of code?

animals = [ 'cat', 'dog'] .
for pet in animals: .
pet.upper( ) 
print(animals)

Answer:
The output will be [‘cat’, ‘dog’]. The value returned by a pet. upper( ) is not assigned to anything hence it does not update the value in any way.

Question 2.
What would be the output of the following code?

for i in range(len(animals)):
animals[i] = animals[i].upper( ) 
print(animals)

Answer:

[‘CAT’, ‘DOG’]

Question 3.
What would be the output of the following code?

numbers = [1,2,3,4] 
for i in numbers:
numbers.append(i + 1) 
print(numbers)

Answer:
This piece of code will not generate any output as the ‘for’ loop will never stop executing. In every iteration, one element is added to the end of the list and the list keeps growing in size.

Question 4.
What will be the output for the following code?

i = 6
while True:
if i%4 == 0:
break
print(i)
i -= 2

Answer:
6

Question 5.
Write a code to print the following pattern:
*
**
***
****
Answer:

for i in range(1,5):
print("*"*i)

Or

count = 1 
while count < 5:
print(*count) 
count = count + 1

Question 6.
Write code to produce the following pattern:
1
22
333
4444
Answer:
The code will be as follows:

count = 1 
while count < 5:
print(str(count)*count) 
count = count + 1

Question 7.
Write a code to generate the following pattern:
1
12
123
1234
Answer:
The code will be as follows:

count = 1 
string1 =' ' 
while count < 5:
for i in range(1, count+1):
string1 = string1+str(i)
count = count + 1 
print(string1) 
string1 =' '

Question 8.
Write code to spell a word entered by the user.
Answer:
The code will be as follows:

word = input ("Please enter a word : ") 
for i in word: 
print (i)

Output
Please enter a word: Aeroplane
A
e
r
0
P
l
a
n
e

Question 9.
Write code to reverse a string.
Answer:
The code:

string1 = "AeRoPlAnE" 
temp = list (string1) 
count = len(temp)-1 
reverse_str=' ' 
while count>=0:
reverse_str = reverse_str + temp[count] 
count = count-1 
print(reverse_str)

Output

EnAlPoReA

Statements to control a loop
The following three statements can be used to control a loop:

  1. break: breaks the execution of the loop and jumps to the next statement after the loop
  2. continue: takes the control back to the top of the loop without executing the remaining statements
  3. pass: does nothing

Question 10.
What will be the output for the following code?

a = 0
for i in range(5): 
a = a+1 
continue 
print(a)

Answer:
5

Question 11.
What would be the output for the following code?
Answer:
The code:

for item in ('a','b','c','d'): 
print (item) 
if item == 'c' : 
break 
continue
print ("challenge to reach here")

Question 12.
How would you use a “if ” statement to check whether an integer is even ?
Answer:
Code

x = int(input("enter number : ")) 
if x%2 == 0:
print("You have entered an even number")

Output

enter number: 6
You have entered an even number
>>>

Question 13.
How would you use an  “if ” statement to check whether an integer is odd?
Answer:
Code

x = int(input("enter number : ")) 
if x%2 != 0:
print("You have entered an odd number")

Output
enter number: 11
You have entered an odd number

Question 14.
Use an if-else statement to check if a given number is even if yes then display that a message stating that the given number is even else print that the given number is odd.
Answer:
Please have a look at the following code:
Code

x = int(input("enter number : ")) if x%2 == 0:
print("You have entered an even number") else:
print("You have entered an odd number")

Output

enter number: 11
You have entered an odd number
>>>
enter number: 4
You have entered an even number
>>>

Question 15.
What is a ternary operator?
Answer:
The ternary operator is a conditional expression used to compress the if.. .else block in one single line.

[to do if true] if [Expression] else [to do if false]

Code

X = 27
print("You have entered an even number") if x%2
== 0 else print("You have entered an odd number")

Output

You have entered an odd number

Question 16.
What would be the output of the following code? Why?
i = j = 10 if i > j:
print(“i is greater than j”) elif i<= j:
print(“i is smaller than j”) else:
print(“both i and j are equal”)
Answer:
The output of the above code will be:
i is smaller than j
i is equal to j.
So, the second condition elif i>j evaluates to true and so, the message printed in this block is displayed.

Question 17.
How can the following piece of code be expressed in one single line?
i = j = 10 if i > j :
print(“i is greater than j”)
elif i< j:
print(“i is smaller than j”)
else:
print(“both i and j are equal”)
Answer:
print (“i is greater than j” if i > j else “i is smaller than j” if i < j else “both i and j are equal”)

Question 18.
What will be the output for the following code?
i = 2 j = 16
minimum_val = i < j and i or j minimum_val
Answer:
2

Question 19.
What is the meaning of conditional branching?
Answer:
Deciding whether certain sets of instructions must be executed or not based on the value of an expression is called conditional branching.

Question 20.
What would be the output for the following code?
a = 0
b = 9
i = [True,False] [a > b]
print(i)
Answer:
The answer would be “True”. This is another ternary syntax: [value_if_false, value_if_true][testcondition]
In the above code a < b, therefore the test condition is false. Hence, ‘i’ will be assigned the value of value_if_false which in this case is set to “True”.

Question 21.
What is the difference between the continue and pass statement?
Answer:
pass does nothing whereas continue starts the next iteration of the loop.

Python Looping

Question 22.
What are the two major loop statements?
Answer:
for and while

Question 23.
Under what circumstances would you use a while statement rather than for?
Answer:
The while statement is used for simple repetitive looping and the for statement is used when one wishes to iterate through a list of items, such as database records, characters in a string, etc.

Question 24.
What happens if you put an else statement after a block?
Answer:
The code in the else block is executed after the for loop completes, unless a break is encountered in the for loop execution, in which case the else block is not executed.

Question 25.
Explain the use of break and continue in Python looping.
Answer:
The break statement stops the execution of the current loop, and transfers control to the next block. The continue statement ends the current block’s execution and jumps to the next iteration of the loop.

Question 26.
When would you use a continue statement in a for loop?
Answer:
When processing a particular item was complete; to move on to the next, without executing further processing in the block.
The continued statement says, “I’m done processing this item, move on to the next item.”

Question 27.
When would you use a break statement in a for loop?
Answer:
When the loop has served its purpose. As an example, after finding the item in a list searched for, there is no need to keep looping. The break statement says, “I’m done in this loop; move on to the next block of code.”

Question 28.
What is the structure of a for loop?
Answer:
for <item> in <sequence>:… The ellipsis represents a code block to be executed, once for each item in the sequence. Within the block, the item is available as the current item from the entire list.

Question 29.
What is the structure of a while loop?
Answer:
while <condition>:… The ellipsis represents a code block to be executed until the condition becomes false. The condition is an expression that is considered true unless it evaluates to 0, null or false.

Question 30.
Use a for loop and illustrate how you would define and print the characters in a string out, one per line.
Answer:
my String = “I Love Python”
for my Char in my String:
print myChar

Question 31.
even the string “I LoveQPython” uses a for loop and illustrates printing each character up to, but not including the Q.
Answer:
my String = “I Love Python”
for my car in my String:
if my car = ‘Q’:
break
print myChar

Question 32.
Given the string “I Love Python” print out each character except for the spaces, using a for a loop.
Answer:
my String = “I Love Python”
for myChar in my String:
if myChar — ‘ ‘ ,
continue print myChar

Question 33.
Illustrate how to execute a loop ten times.
Answer:
i = 1
while i < 10:
i+=1

Question 34.
When using a while loop, a condition was encountered that made staying in the loop pointless, what statement is used to transfer control?
Answer:
The break statement is used to terminate the processing of the loop and move on to the next block of code.

Question 35.
How is execution in the while loop block abandoned, but the loop itself is not exited?
Answer:
The continue statement is used to terminate the processing of the block and move control to the next iteration of the loop.

Question 36.
What is a looping use of the range( ) function?
Answer:
The range function is used to generate a sequence of numbers for iteration. For example range(5) returns the list [0,1, 2, 3, 4] This list could be used in a a loop.

Question 37.
Can the else clause be used after a while loop? When is it executed? ,
Answer:
Yes. The else block is executed after the while condition becomes false, but not if the while loop is exited with a break statement.

Question 38.
Illustrate how the range( ) and len( ) functions be used to iterate over the indices of a sequence?
Answer:
myltems = [T, ‘Love’, ‘Python’]
for i in rangeden(myltems)):
print i, myltems[i]

Question 39.
How is the body of a loop defined?
Answer:
The body of the loop is defined by indentation.

Question 40.
How are loops nested?
Answer:
Ever greater levels of indentation.

Question 41.
Illustrate a nested loop that uses the following list IT, ‘Love’, ‘Python’] and outputs each character on a separate line.
Answer:
myltems = [T, ‘Love’, ‘Python’]
for myWord in myltems:
for myChar in myWord:
print myChar

Python Program to Find Number of Rectangles in N*M Grid

Program to Find Number of Rectangles in NM Grid

In the previous article, we have discussed Python Program for Minimum Perimeter of n Blocks
Given a grid of size N*M the task is to find the number of rectangles in the given grid in Python, Number of rectangles in a 4×4 grid, Number of rectangles formula, number of rectangles in a 3×3 grid, number of squares in mn grid, number of rectangles in the grid shown which are not squares is, count number of rectangles given points, number of rectangles in a grid leetcode, formula for number of squares in a grid, number of squares in m*n grid, number of rectangles in mxn grid, python program to find area of rectangle, you will get an idea.

Examples:

Example1:

Input:

Given N = 6
Given M = 4

Output:

Number of Rectangles in the grid of size { 6 * 4 } : 210

Example2:

Input:

Given N = 4
Given M = 2

Output:

Number of Rectangles in the grid of size { 4 * 2 } : 30

Program to Find Number of Rectangles in N*M Grid in Python

Below are the ways to find the number of rectangles in the given N*M:

Let’s try to come up with a formula for the number of rectangles.

There is one rectangle in a grid of 1*1

There will be 2 + 1 = 3 rectangles if the grid is 2*1.

There will be 3 + 2 + 1 = 6 rectangles if the grid is 3*1

The formula for Number of Rectangles = M(M+1)(N)(N+1)/4

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the number N as static input and store it in a variable.
  • Give the number M as static input and store it in another variable.
  • Create a function getCountRect() which accepts given N, M grid sides as arguments and returns the number of rectangles.
  • Inside the getCountRect() function Calculate the number of rectangles using the MatheMatical Formula M(M+1)(N)(N+1)/4 and store it in a variable say reslt.
  • Return the reslt value.
  • Inside the Main Function.
  • Pass the given N, M as arguments to getCountRect() function and store the result returned from the function in a variable say countRect.
  • Print the countRect value.
  • The Exit of the Program.

Below is the implementation:

# Create a function getCountRect() which accepts given N, M grid sides
# as arguments and returns the number of rectangles.


def getCountRect(nVal, mVal):
        # Inside the getCountRect() function Calculate the number of rectangles
    # using the MatheMatical Formula M(M+1)(N)(N+1)/4 
    # and store it in a variable say reslt.
    reslt = (mVal * nVal * (nVal + 1) * (mVal + 1)) / 4
    # Return the reslt value.
    return reslt


# Inside the Main Function.
# Give the number N as static input and store it in a variable.
nVal = 6
# Give the number M as static input and store it in another variable.
mVal = 4
# Pass the given N, M as arguments to getCountRect() function
# and store the result returned from the function in a variable say countRect.
countRect = int(getCountRect(nVal, mVal))
# Print the countRect value.
print(
    'Number of Rectangles in the grid of size {', nVal, '*', mVal, '} :', countRect)
#include <iostream>

using namespace std;
int getCountRect ( int nVal, int mVal ) {
  int reslt = ( mVal * nVal * ( nVal + 1 ) * ( mVal + 1 ) ) / 4;
  return reslt;
}
int main() {
    int nVal = 6;
  int mVal = 4;
  int countRect = ( int ) getCountRect ( nVal, mVal );
  cout << "Number of Rectangles in the grid of size {" << nVal << '*' << mVal << " } is: " << countRect << endl;
  return 0;
}

Output:

Number of Rectangles in the grid of size { 6 * 4 } : 210

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the number N as user input using the int(input()) function and store it in a variable.
  • Give the number M as user input using the int(input()) function and store it in another variable.
  • Create a function getCountRect() which accepts given N, M grid sides as arguments and returns the number of rectangles.
  • Inside the getCountRect() function Calculate the number of rectangles using the MatheMatical Formula M(M+1)(N)(N+1)/4 and store it in a variable say reslt.
  • Return the reslt value.
  • Inside the Main Function.
  • Pass the given N, M as arguments to getCountRect() function and store the result returned from the function in a variable say countRect.
  • Print the countRect value.
  • The Exit of the Program.

Below is the implementation:

# Create a function getCountRect() which accepts given N, M grid sides
# as arguments and returns the number of rectangles.


def getCountRect(nVal, mVal):
        # Inside the getCountRect() function Calculate the number of rectangles
    # using the MatheMatical Formula M(M+1)(N)(N+1)/4 
    # and store it in a variable say reslt.
    reslt = (mVal * nVal * (nVal + 1) * (mVal + 1)) / 4
    # Return the reslt value.
    return reslt


# Inside the Main Function.
# Give the number N as user input using the int(input()) function and store it in a variable.
nVal = int(input('Enter Some Random N value = '))
# Give the number M as static input and store it in another variable.
mVal = int(input('Enter Some Random M value = '))
# Pass the given N, M as arguments to getCountRect() function
# and store the result returned from the function in a variable say countRect.
countRect = int(getCountRect(nVal, mVal))
# Print the countRect value.
print(
    'Number of Rectangles in the grid of size {', nVal, '*', mVal, '} :', countRect)

Output:

Enter Some Random N value = 4
Enter Some Random M value = 2
Number of Rectangles in the grid of size { 4 * 2 } : 30

Explore more Example Python Programs with output and explanation and practice them for your interviews, assignments and stand out from the rest of the crowd.

Analyze yourself:

  1. Python program to read number n and compute n*nn*nnn?
  2. How to find number of rectangles in a grid?
  3. How to calculate number of rectangles in a grid?
  4. Python program to find area of a rectangle?
  5. Finding number of rectangles in a grid?
  6. Python program to find area of rectangle using class?

Related Posts On:

Xor in python – Python Program to Perform XOR on Two Lists

Program to Perform XOR on Two Lists

xor in python: Given two lists of the same length, the task is to perform the Xor Operation on both the list elements which are having the same index in Python. See Xor Of Two Lists Python, Python xor two lists, Xor Two Lists Python, xor in python list, xor of list in python, List xor python, Python Xor List, Python List Xor, python xor sets, Xor of a list python, python set xor, python xor lists, xor list python, xor python 3, python xor operator, xor between two arrays, xor set python, Xor Two Arrays Python, set xor python, python xor all elements in list.

Examples:

Example1:

Input:

Given list 1= [4, 19, 11, 5, 3, 9, 7]
Given list 2= [10, 3, 7, 2, 9, 8, 6, 5]

Output:

The given First list elements are = [4, 19, 11, 5, 3, 9, 7]
The given Second list elements are = [10, 3, 7, 2, 9, 8, 6, 5]
The result after applying xor operation on both lists is [14, 16, 12, 7, 10, 1, 1]

Example2:

Input:

Given list 1 = [5, 7, 9, 6]
Given list 2 = [3, 8, 9, 4]

Output:

The given First list elements are = [5, 7, 9, 6]
The given Second list elements are = [3, 8, 9, 4]
The result after applying xor operation on both list is [6, 15, 0, 2]

Program to Perform XOR on Two Lists in Python

Python xor operator: Below are the ways to perform Xor on Two lists 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 For Loop (Static Input)

Approach:

  • Give the first list as static input and store it in a variable.
  • Give the second list as static input and store it in another variable.
  • Calculate the length of the first list using the len() function(as both lists have same length) and store it in a variable.
  • Loop till the above length using the For loop.
  • Inside the for loop initialize the list 1 element as xor operation between list1 and list2 using xor operator i.e lst1[p]=lst1[p]^lst2[p] where p is the iterator value of the For loop.
  • Print the list1 which is the result.
  • The Exit of Program.

Below is the implementation:

# Give the first list as static input and store it in a variable.
lstt1 = [4, 19, 11, 5, 3, 9, 7]
# Give the second list as static input and store it in another variable.
lstt2 = [10, 3, 7, 2, 9, 8, 6, 5]
print('The given First list elements are =', lstt1)
print('The given Second list elements are =', lstt2)
# Calculate the length of the first list using the len()
# function(as both lists have same length) and store it in a variable.
lenlst = len(lstt1)
# Loop till the above length using the For loop.
for p in range(lenlst):
    # Inside the for loop initialize the list 1 element as xor operation
    # between list1 and list2 using xor operator i.e lst1[p]=lst1[p]^lst2[p]
    # where p is the iterator value of the For loop.
    lstt1[p] = lstt1[p] ^ lstt2[p]
# Print the list1 which is the result.
print('The result after applying xor operation on both lists is', lstt1)

Output:

The given First list elements are = [4, 19, 11, 5, 3, 9, 7]
The given Second list elements are = [10, 3, 7, 2, 9, 8, 6, 5]
The result after applying xor operation on both lists is [14, 16, 12, 7, 10, 1, 1]

Method #2: Using For Loop (User Input)

Approach:

  • Give the first list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the first list using the len() function(as both lists have same length) and store it in a variable.
  • Loop till the above length using the For loop.
  • Inside the for loop initialize the list 1 element as xor operation between list1 and list2 using xor operator i.e lst1[p]=lst1[p]^lst2[p] where p is the iterator value of the For loop.
  • Print the list1 which is the result.
  • The Exit of Program.

Below is the implementation:

# Give the first list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
lstt1 = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the second list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
lstt2 = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
print('The given First list elements are =', lstt1)
print('The given Second list elements are =', lstt2)
# Calculate the length of the first list using the len()
# function(as both lists have same length) and store it in a variable.
lenlst = len(lstt1)
# Loop till the above length using the For loop.
for p in range(lenlst):
    # Inside the for loop initialize the list 1 element as xor operation
    # between list1 and list2 using xor operator i.e lst1[p]=lst1[p]^lst2[p]
    # where p is the iterator value of the For loop.
    lstt1[p] = lstt1[p] ^ lstt2[p]
# Print the list1 which is the result.
print('The result after applying xor operation on both lists is', lstt1)

Output:

Enter some random List Elements separated by spaces = 5 7 9 6
Enter some random List Elements separated by spaces = 3 8 9 4
The given First list elements are = [5, 7, 9, 6]
The given Second list elements are = [3, 8, 9, 4]
The result after applying xor operation on both list is [6, 15, 0, 2]

Check Once:

  1. How To Xor In Python
  2. Python Xor List Of Numbers

Related Programs:

User defined function python – Python Interview Questions on User Defined Functions

_Python Interview Questions on User Defined Functions

User defined function python: We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels. You can also Observe Python coding questions and answers, Python tricky interview questions, Python coding interview questions geeksforgeeks, Python coding questions for placement, Python interview questions for 5 years experience, Tcs python interview questions, Python interview questions and answers, Python interview questions and answers pdf, Python interview questions and answers for freshers, Python interview questions on functions, Questions on user defined functions in python, Python interview questions on decorators, Python interview questions on oops, Python interview questions on oops concepts, Python interview questions on object oriented programming, Python oops interview questions with realtime examples, Python interview questions on variables.

Python Interview Questions on User Defined Functions

Python user defined function: While going through the chapter on standard data types you have learned about several inbuilt defined by functions. These functions already exist in Python libraries. However, programming is all about creating your own functions that can be called at any time. A function is basically a block of code that will execute only when it is called. To define a function we use the keyword def as shown in the following code:

def function_name ( ):
    to do statements

So, let’s define a simple function:

def new_year_greetings( ) :
    print("Wish you a very happy and properous new year")
new_year_greetings( )

The new_year_greetings( ) function is a very simple function that simply displays a new year message when called.

You can also pass a parameter to a function. So, if you want the function new_year_greetings( ) to print a personalized message, we may want to consider passing a name as a parameter to the function.

def new_year_greetings(name):
print("Hi ", name.upper(),"! ! Wish you a very happy and prosperous new year")
name = input("Hello!! May I know your good name please: ")
new_year_greetings(name)

The output for the code given above would be as follows:

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and prosperous new year
>>>

Indentation is very important. In order to explain, let’s add another print statement to the code.

def new_year_greetings (name) :
print("Hi ", name.upper(),"! ! Wish you a very !
happy and prosperous new year")
print("Have a great year")
name = input("Hello!! May I know your good name please: ")
new_year_greetings(name)

So, when the function is called, the output will be as follows:

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and properous new year
Have a great year

Improper indentation can change the meaning of the function: ;

def new_year_greetings(name):
print("Hi ", name.upper( ),"! ! Wish you a very happy and properous new year")
print("Have a great year")

In the code given above the second print, the statement will be executed even if the function is not called because it is not indented properly and it is no more part of the function. The output will be as follows:

Have a great year

Multiple functions can also be defined and one function can call the other.

def new_year_greetings(name):
print("Hi ", name.upper( ),"!! Wish you a very happy and properous new year")
extended_greetings( )
def extended_greetings( ):
print("Have a great year ahead") name = input ("Hello! !' May I know your good name please: ")
new-_year_greetings (name)

When a new year greeting ( ) a message is printed and then it calls the extended_greetings( ) function which prints another message.

Output

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and properous new year
Have a great year ahead

Multiple parameters can also be passed to a function.

def new_year_greetings(name1,name2):
print("Hi ",namel," and ",name2,"!! Wish you a very happy and properous new year")
extended_greetings( )
def extended_greetings( ):
print("Have a great year ahead") new_year_greetings("Jazz","George")

The output will be as follows:

Hi Jazz and George !! Wish you a very happy and properous new year Have a great year ahead

Question 1.
What are the different types of functions in Python?
Answer:
There are two types of functions in Python:

  1. Built-in functions: library functions in Python
  2. User-defined functions: defined by the developer

Question 2.
Why are functions required?
Answer:
Many times in a program a certain set of instructions may be called again and again. Instead of writing the same piece of code where it is required it is better to define a function and place the code in it. This function can be called whenever there is a need. This saves time and effort and the program can be developed easily. Functions help in organizing coding work and testing of code also becomes easy.

Question 3.
What is a function header?
Answer:
The first line of function definition that starts with def and ends with a colon (:) is called a function header.

Question 4.
When does a function execute?
Answer:
A function executes when a call is made to it. It can be called directly from the Python prompt or from another function.

Question 5.
What is a parameter? What is the difference between a parameter and an argument?
Answer:
A parameter is a variable that is defined in a function definition whereas an argument is an actual value that is passed on to the function. The data carried in the argument is passed on to the parameters. An argument can be passed on as a literal or as a name.

def function_name(param):

In the preceding statement, param is a parameter. Now, take a look at the statement given below, it shows how a function is called:

function_name(arg):

arg is the data that we pass on while calling a function. In this statement arg is an argument.
So, a parameter is simply a variable in method definition and an argument is the data passed on the method’s parameter when a function is called.

Question 6.
What is a default parameter?
Answer:
The default parameter is also known as the optional parameter. While defining a function if a parameter has a default value provided to it then it is called a default parameter. If while calling a function the user does not provide any value for this parameter then the function will consider the default value assigned to it in the function definition.

Question 7.
What are the types of function arguments in Python?
Answer:
There are three types of function arguments in Python:
1. Default Arguments: assumes a default value, if no value is provided by the user.

def func(name = "Angel"):
print("Happy Birthday ", name)
func ( )
Happy Birthday Angel

You can see that the default value for the name is “Angel” and since the user has not provided any argument for it, it uses the default value.

2. Keyword Arguments: We can call a function and pass on values irrespective of their positions provided we use the name of the parameter and assign them values while calling the function.

def func(name1, name2):
print("Happy Birthday", name1, " and ",name2,"!!!")

Output:

func(name2 = "Richard",namel = "Marlin")
Happy Birthday Marlin and Richard !!!

3. Variable-length Arguments: If there is uncertainty about how many arguments might be required for processing a function we can make use of variable-length arguments. In the function definition, if a single is placed before the parameter then all positional arguments from this point to the end are taken as a tuple. On the other hand, if “**” is placed before the parameter name then all positional arguments from that point to the end are collected as a dictionary.

def func(*name, **age): print(name)
print(age)
func("Lucy","Aron","Alex", Lucy = "10",Aron ="15",Alex="12")

Output:

('Lucy', 'Aron', 'Alex')
{'Lucy': '10', 'Aron': '15', 'Alex': '12'}

Question 8.
What is a fruitful and non-fruitful function?
Answer:
The fruitful function is a function that returns a value and a non-fruitful function does not return a value. Non-fruitful functions are also known as void functions.

Question 9.
Write a function to find factorial of a number using for loop
Answer:
The code for finding a factorial using for loop will be as follows:
Code

def factorial(number):
j = 1
if number==0|number==1:
print(j)
else:
for i in range (1, number+1):
print (j," * ",i," = ", j * i)
j = j*i
print(j)

Execution

factorial(5)

Output

1 * 1 = 1
1 * 2 = 2
2 * 3 = 6
6 * 4 = 24
24 * 5 = 120
120

Question 10.
Write a function for Fibonacci series using a for loop:
Answer:
Fibonacci series: 0, 1, 1, 2, 3, 5, 8….
We take three variables:
i, j, and k:

  • If i = 0, j =0, k =0
  • If i =1, j =1, k =0
  • If i> 1:

temp =j
j =j+k
k=temp
The calculations are as shown as follows:

I K J
0 0 0
1 0 1
2 0 Temp = j = 1

J = j + k = 1+10 = 1

K = temp = 1

3 1 Temp = j = 1

J = j +k = 1 +1 = 2

K = temp = 1

4 1 Temp = j = 2

J = j + k = 2+1 = 3

K = temp = 2

5 2 Temp = j = 3

J = j + k = 3+2 = 5

K = temp = 3

6 3 Temp = j =5

J = j + k = 5+3=8

K = temp = 1

Code

def fibonacci_seq (num) :
i = 0
j = 0
k = 0
for i in range(num):
if i==0:
print(j)

elif i==1:
j = 1
print(j)
else:
temp = j
j = j+k
k = temp
print(j)

Execution

fibonacci_seq (10)

Output

0
1
1
2
3
5
8
13
21
34

Question 11.
How would you write the following code using a while loop?
[Note: You may want to refer to recursion before attempting this question.]

def test_function(i, j) :
if i == 0:
return j;
else:
return test_function(i-1, j+1)
print(test_function(6,7) )

Answer:

def test_function (i,j) :
while i > 0:
i =i- 1
j = j + 1
return j
print(test_function(6, 7) )

Question 12.
Write code for finding the HCF of two given numbers.
Answer:
HCF stands for Highest Common Factor or Greatest Common Divisor for two numbers. This means that it is the largest number within the range of 1 to smaller of the two given numbers that divides the two numbers perfectly giving the remainder as zero.
1. Define a function hcf() that takes two numbers as input.

def hcf(x,y):

2. Find out which of the two numbers is greatest, the other one will be the smallest.

small_num = 0
if x > y:
small_nura = y
else:
small_num = x

Set a for loop for the range 1 to small_num+1. (We take the upper limit as small_num+l because the for loop operates for one number less than the upper limit of the range). In this for loop, divide both the numbers with each number in the range and if any number divides both, perfectly assign that value to have as shown in the following code:

for i in range(1,small_num+1):
if (x % i == 0) and (y % i == 0) :
hcf = i

Suppose, the two numbers are 6 and 24, first both numbers are divisible by 2. So, hcf = 2, then both numbers will be divisible by 3 so, the value of 3 will be assigned to 3. Then the loop will encounter 6, which will again divide both the numbers equally. So, 6 will be assigned to hcf. Since the upper limit of the range has reached, the function will finally have hcf value of 6.
3. Return the value of hcf: return hcf
Code

def hcf (x,y) :
small_num = 0
if x>y:
small_num = y
else:
small_num = x

for i in range (1, small_num+1):
if (x % i ==0) and (y % i ==0):
hcf = i
return hcf

Execution

print (hcf(6,24))

Output

6

Scope of a variable

The scope of a variable can be used to know which program can be used from which section of a code. The scope of a variable can be local or global.
Local variables are defined inside a function and global functions are defined outside a function. Local variables can be accessed only within
the function in which they are defined. A global variable can be accessed throughout the program by all functions.

total = 0 # Global variable
def add(a,b) :
sumtotal = a+b #Local variable
print("inside total = ", total)

Question 13.
What will be the output of the following code?

total = 0
def add(a,b):
global total
total = a+b
print("inside total = ", total)

add(6,7)
print("outside total = ", total)

Answer:
The output will be as follows:

inside total = 13
outside total = 13

Question 14.
What would be the output for the following code?

total = 0
def add(a,b):
total = a+b
print("inside total = ", total)

add(6,7)
print("outside total = ", total)

Answer:

inside total = 13
outside total = 0

Question 15.
Write the code to find HCF using Euclidean Algorithm.
Answer:
The following figure shows two ways to find HCF.
On the left-hand side, you can see the traditional way of finding the HCF.

On the right-hand side is the implementation of the Euclidean Algorithm to find HCF.
Python Interview Questions on User Defined Functions chapter 5 img 1

Code

def hcf(x,y):
small_num = 0
greater_num = 0
temp = 0
if x > y:
small_num = y
greater_num = x
else:
small_num = x
greater_num = y

while small_num > 0:
temp = small_num
small_num = greater_num % small_num
greater_num = temp
return temp

Execution

print("HCF of 6 and 2 4 = ",hcf(6,24))
print("HCF of 400 and 300 = ",hcf(400,300))

Output

HCF of 6 and 24= 6
HCF of 400 and 300 = 100

Question 16.
Write code to find all possible palindromic partitions in a string.
Answer:
The code to find all possible palindromic partitions in a string will involve the following steps:

  1. Create a list of all possible substrings.
  2. Substrings are created by slicing the strings as all possible levels using for loop.
  3. Every substring is then checked to see if it is a palindrome.
  4. The substring is converted to a list of single characters.
  5. In reverse order, the characters from the list are added to a string.
  6. If the resultant string matches the original string then it is a palindrome.

Code

def create_substrings(x):
substrings = [ ]

for i in range(len (x)) :
for j in range(1, len(x)+l):
if x[i:j] != ' ' :
substrings.append(x[i:j])
for i in substrings:
check_palin(i)

def check_palin(x):
palin_str = ' '
palin_list = list(x)
y = len(x)-1
while y>=0:
palin_str = palin_str + palin_list[y]
y = y-1
if(palin_str == x):
print("String ", x," is a palindrome")

Execution

x = ''malayalam"
create_substrings(x)

Output

String m is a palindrome
String malayalam is a palindrome
String a is a palindrome
String ala is a palindrome
String alayala is a palindrome
String 1 is a palindrome
String layal is a palindrome
String a is a palindrome
String aya is a palindrome
String y is a palindrome
String a is a palindrome
String ala is a palindrome
String 1 is a palindrome
String a is a palindrome
String m is a palindrome

Question 17.
What are anonymous functions?
Answer:
Lambda facility in Python can be used for creating a function that has no names. Such functions are also known as anonymous functions. Lambda functions are very small functions that have just one line in the function body, ft requires no return statement.

total = lambda a, b: a + b
total(10,50)
60

Question 18.
What is the use of a return statement?
Answer:
The return statement exits the function and hands back value to the function’s caller. You can see this in the code given below. The function func( ) returns the sum of two numbers. This value assigned to “total” and then the value- of the total is printed.

def func(a,b):
return a+b
total = func(5,9)
print(total)
14

Question 19.
What will be the output of the following function?

def happyBirthday( ):
print("Happy Birthday")
a = happyBirthday() print(a)

Answer:

Happy Birthday
None

Question 20.
What will be the output of the following code?

def outerWishes( ):
global wishes
wishes = "Happy New Year"
def innerWishes():
global wishes
wishes = "Have a great year ahead"
print('wishes =', wishes)
wishes = "Happiness and Prosperity Always"
router wishes( )
print('wishes =', wishes)

Answer:
The output will be as follows:

wishes = Happy New Year

Question 21.
What is the difference between passing immutable and mutable objects as an argument to a function?
Answer:
If immutable arguments like strings, integers, or tuples are passed to a function, the object reference is passed but the value of these parameters cannot be changed. It acts like a pass-by-value call. Mutable objects too are passed by object reference but their values can be changed.