Python

Print all Integers that Aren’t Divisible by Either 2 or 3 and Lie between 1 and 50 in C++ and Python

Print all Integers that Aren’t Divisible by Either 2 or 3 and Lie between 1 and 50 in C++ and Python

In the previous article, we have discussed about Allocating and deallocating 2D arrays dynamically in C++. Let us learn how to Print all Integers that Aren’t Divisible by Either 2 or 3 and Lie between 1 and 50 in C++ Program.

The task is to print all the numbers from 1 to 50 which are not divisible by 2 or 3 in C++ and Python.

Sample Output:

The numbers from 1 to 50 which are not divisible by 2 and 3 are:
Number =  1
Number =  5
Number =  7
Number =  11
Number =  13
Number =  17
Number =  19
Number =  23
Number =  25
Number =  29
Number =  31
Number =  35
Number =  37
Number =  41
Number =  43
Number =  47
Number =  49

Print all Integers that Aren’t Divisible by Either 2 or 3 and Lie between 1 and 50 in C++ and Python

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

There are several ways to print all the numbers from 1 to 50 which are not divisible by 2 or 3 some of them are:

Method #1: Using for loop in Python

Approach:

  • Use a for loop and a range() function which iterates from 1 to 50.
  • Then, using an if statement, determine whether the integer is not divisible by both 2 and 3.
  • If the number is not divisible by 2 and 3 then print it.
  • Exit of program

Below is the implementation:

# Use a for loop and a range() function which iterates from 1 to 50.
print("The numbers from 1 to 50 which are not divisible by 2 and 3 are:")
for numb in range(1, 51):
    # Then, using an if statement, determine whether the integer is
    # not divisible by both 2 and 3.
    if(numb % 2 != 0 and numb % 3 != 0):
        # If the number is not divisible by 2 and 3 then print it.
        print("Number = ", numb)

Output:

The numbers from 1 to 50 which are not divisible by 2 and 3 are:
Number =  1
Number =  5
Number =  7
Number =  11
Number =  13
Number =  17
Number =  19
Number =  23
Number =  25
Number =  29
Number =  31
Number =  35
Number =  37
Number =  41
Number =  43
Number =  47
Number =  49

Method #2: Using for loop in C++

Approach:

  • Use for loop in Which starts from 1 and ends at 50 using the
  • syntax : for (numb=1;numb<=50;numb++)
  • Then, using an if statement, determine whether the integer is not divisible by both 2 and 3.
  • If the number is not divisible by 2 and 3 then print it.
  • Exit of program

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{
    // Use for loop in Which starts from 1 and ends at 50
    // using the syntax : for (numb=1;numb<=50;numb++)
    cout << "The numbers from 1 to 50 which are not "
            "divisible by 2 and 3 are:"
         << endl;
    for (int numb = 1; numb <= 50; numb++) {
        // Then, using an if statement determine whether the
        // integer is not divisible by both 2 and 3.

        if (numb % 2 != 0 && numb % 3 != 0) {
            // If the number is not divisible by 2 and 3
            // then print it.
            cout << "Number = " << numb << endl;
        }
    }
    return 0;
}

Output:

The numbers from 1 to 50 which are not divisible by 2 and 3 are:
Number = 1
Number = 5
Number = 7
Number = 11
Number = 13
Number = 17
Number = 19
Number = 23
Number = 25
Number = 29
Number = 31
Number = 35
Number = 37
Number = 41
Number = 43
Number = 47
Number = 49

Method #3: Using while loop in Python

Approach:

  • Take a variable  say tempo which stores the lower limit (in this case it is 1)
  • Using while loop iterate from 1 to 51 by using the condition tempo <=50
  • Then, using an if statement, determine whether the integer is not divisible by both 2 and 3.
  • If the number is not divisible by 2 and 3 then print it.
  • Increment the value of tempo by 1
  • Exit of program

Below is the implementation:

# Use a for loop and a range() function which iterates from 1 to 50.
print("The numbers from 1 to 50 which are not divisible by 2 and 3 are:")
# Take a integer variable  say tempo which stores the lower limit (in this case it is 1)
tempo = 1
# Using while loop iterate from 1 to 51 by using the condition tempo <=50
while(tempo <= 50):

    # Then, using an if statement, determine whether the integer is
    # not divisible by both 2 and 3.
    if(tempo % 2 != 0 and tempo % 3 != 0):
        # If the number is not divisible by 2 and 3 then print it.
        print('Number =', tempo)
    # Increment the value of tempo by 1
    tempo = tempo+1

Output:

The numbers from 1 to 50 which are not divisible by 2 and 3 are:
Number = 1
Number = 5
Number = 7
Number = 11
Number = 13
Number = 17
Number = 19
Number = 23
Number = 25
Number = 29
Number = 31
Number = 35
Number = 37
Number = 41
Number = 43
Number = 47
Number = 49

Method #4: Using while loop in C++

Approach:

  • Take a integer variable  say tempo which stores the lower limit (in this case it is 1)
  • Using while loop iterate from 1 to 51 by using the condition tempo <=50
  • Then, using an if statement, determine whether the integer is not divisible by both 2 and 3.
  • If the number is not divisible by 2 and 3 then print it.
  • Increment the value of tempo by 1
  • Exit of program

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{
    // Use for loop in Which starts from 1 and ends at 50
    // using the syntax : for (numb=1;numb<=50;numb++)
    cout << "The numbers from 1 to 50 which are not "
            "divisible by 2 and 3 are:"
         << endl;
    // Take a integer variable  say tempo which stores the
    // lower limit (in this case it is 1)
    int tempo = 1;
    // Using while loop iterate from 1 to 51 by using the
    // condition tempo <=50
    while (tempo <= 50) {
        // Then, using an if statement determine whether the
        // integer is not divisible by both 2 and 3.

        if (tempo % 2 != 0 && tempo % 3 != 0) {
            // If the number is not divisible by 2 and 3
            // then print it.
            cout << "Number = " << tempo << endl;
        }
        // Increment the value of tempo by 1
        tempo = tempo + 1;
    }
    return 0;
}

Output:

The numbers from 1 to 50 which are not divisible by 2 and 3 are:
Number = 1
Number = 5
Number = 7
Number = 11
Number = 13
Number = 17
Number = 19
Number = 23
Number = 25
Number = 29
Number = 31
Number = 35
Number = 37
Number = 41
Number = 43
Number = 47
Number = 49

Related Programs:

Print all Integers that Aren’t Divisible by Either 2 or 3 and Lie between 1 and 50 in C++ and Python Read More »

Program to Append, Delete and Display Elements of a List Using Classes

Python Program to Append, Delete and Display Elements of a List Using Classes

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Object-Oriented Programming(OOPS):

Object-Oriented Programming (OOP) is a programming paradigm based on the concepts of classes and objects. It is used to organize a software program into simple, reusable code blueprints (typically referred to as classes), which are then used to build individual instances of objects. Object-oriented programming languages include JavaScript, C++, Java, and Python, among others.

A class is a generic blueprint that can be used to generate more specific, concrete things. Classes are frequently used to represent broad groups, such as Cars or Dogs, that share property. These classes indicate what properties, such as color, an instance of this type will have, but not the value of those attributes for a specific object.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Python, like other general-purpose programming languages, has always been an object-oriented language. It enables us to create a program with an Object-Oriented approach. Classes and objects are simple to build and utilize in Python.

The task is to perform append, delete and display elements of the given list using classes in Python.

Program to Append, Delete and Display Elements of a List Using Classes

Below is the full approach to perform append, delete and display elements of the given list using classes in Python.

Approach:

  • Create a class and use a default constructor to initialize its values(initializing an empty list).
  • Initialize empty list using [] operator or list() function.
  • Create three methods inside the class.
  • AddEle: Which appends the given argument to the list using the append function.
  • RemEle: Which removes the given argument from the list using the remove() function.
  • DisplayList: This prints all the elements of the given list.
  • Implement methods for appending, deleting, and displaying list elements, and return the corresponding values.
  • Create an object to represent the class.
  •  Using the object, call the appropriate function based on the user’s selection.
  •  Print the modified list after every operation
  • The Exit of the Program.

Below is the implementation:

# creating a class named ListOperations
class ListOperations():
  # Default constructor to initialize its values(initializing an empty list).
    def __init__(self):
      # initializing empty list using [] operator or list() function.
        self.givenllist = []
    # Creating three methods inside the class.
    # AddEle: Which appends the given argument to the list using the append function.

    def AddEle(self, eleme):
        return self.givenllist.append(eleme)
    # RemEle: Which removes the given argument from the list using the remove() function.

    def RemEle(self, eleme):
        self.givenllist.remove(eleme)
    # DisplayList: This prints all the elements of the given list.
    # Implement methods for appending, deleting, and displaying list elements,
    # and return the corresponding values.

    def DisplayList(self):
        return (self.givenllist)


# Create an object to represent the class.
listObject = ListOperations()
# taking a choice from the user .
# initializing option as 1
option = 1
while option != 0:
    print("Enter [0] to Exit the program")
    print("Enter [1] to Add element to the given list")
    print("Enter [2] to remove element from the given list")
    print("Enter [3] to print all the elements of the given list")
    option = int(input("Enter some random choice from 0 to 3 = "))
    if option == 1:
      # scanning the element as user input using
      # int(input()) and storing it in a variable
        ele = int(
            input("Enter some random number to be appended to the given list = "))
        listObject.AddEle(ele)
        print("The given list after adding element=",
              ele, '\n', listObject.DisplayList())

    elif option == 2:
        ele = int(
            input("Enter some number which should be removed from the given list = "))
        listObject.RemEle(ele)
        print("The given list after removing the given element=",
              ele, '\n', listObject.DisplayList())

    elif option == 3:
        print("The given list : \n", listObject.DisplayList())
    elif option == 0:
        print("Exit of program")
    else:
        print("The choice entered by user is invalid")

    print()

Output:

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 19
The given list after adding element= 19 
[19]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 11
The given list after adding element= 11 
[19, 11]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 35
The given list after adding element= 35 
[19, 11, 35]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 38
The given list after adding element= 38 
[19, 11, 35, 38]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 75
The given list after adding element= 75 
[19, 11, 35, 38, 75]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 585
The given list after adding element= 585 
[19, 11, 35, 38, 75, 585]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 685
The given list after adding element= 685 
[19, 11, 35, 38, 75, 585, 685]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 191
The given list after adding element= 191 
[19, 11, 35, 38, 75, 585, 685, 191]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 1
Enter some random number to be appended to the given list = 29
The given list after adding element= 29 
[19, 11, 35, 38, 75, 585, 685, 191, 29]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 2
Enter some number which should be removed from the given list = 191
The given list after removing the given element= 191 
[19, 11, 35, 38, 75, 585, 685, 29]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 3
The given list : 
[19, 11, 35, 38, 75, 585, 685, 29]

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 8
The choice entered by user is invalid

Enter [0] to Exit the program
Enter [1] to Add element to the given list
Enter [2] to remove element from the given list
Enter [3] to print all the elements of the given list
Enter some random choice from 0 to 3 = 0
Exit of program

Explanation:

  • The ListOperationsclass is created, and the __init__() function is used to initialize the class’s values.
  • The methods for adding, deleting, and displaying list elements have been specified.
  • The menu is printed, and the user makes his or her selection.
  • The class’s object is created.
  • The object is used to call the appropriate method based on the user’s selection.
  • The final list has been printed.

Related Programs:

Python Program to Append, Delete and Display Elements of a List Using Classes Read More »

Program to Create a Class and Get All Possible Subsets from a List

Python Program to Create a Class and Get All Possible Subsets from a List

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Object-Oriented Programming(OOPS):

Object-Oriented Programming (OOP) is a programming paradigm based on the concepts of classes and objects. It is used to organize a software program into simple, reusable code blueprints (typically referred to as classes), which are then used to build individual instances of objects. Object-oriented programming languages include JavaScript, C++, Java, and Python, among others.

A class is a generic blueprint that can be used to generate more specific, concrete things. Classes are frequently used to represent broad groups, such as Cars or Dogs, that share property. These classes indicate what properties, such as color, an instance of this type will have, but not the value of those attributes for a specific object.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Python, like other general-purpose programming languages, has always been an object-oriented language. It enables us to create a program with an Object-Oriented approach. Classes and objects are simple to build and utilize in Python.

Lists in Python:

In Python, a list is a data structure that works as a container for several values. A Python list is an ordered sequence of values that can be added to, deleted from, and replaced with new values. As a result, a list in Python can expand and contract in size. Each item in a list is referred to as an element, a list item, or simply an item.

Given a list, the task is to print all the subsets of the given list using classes.

Examples:

Example1:

Input:

given list = [4, 19, 2, 5, 3]

Output:

Subsets of the given list [4, 19, 2, 5, 3] :
[[], [19], [5], [5, 19], [4], [4, 19], [4, 5], [4, 5, 19], [3], [3, 19], [3, 5], [3, 5, 19], [3, 4], [3, 4, 19], [3, 4, 5], [3, 4, 5, 19],
 [2], [2, 19], [2, 5], [2, 5, 19], [2, 4], [2, 4, 19], [2, 4, 5], [2, 4, 5, 19], [2, 3], [2, 3, 19], [2, 3, 5], [2, 3, 5, 19], [2, 3, 4], 
[2, 3, 4, 19], [2, 3, 4, 5], [2, 3, 4, 5, 19]]

Example2:

Input:

given list = ['hello', 'this', 'is', 'btechgeeks']

Output:

Subsets of the given list ['hello', 'this', 'is', 'btechgeeks'] :
[[], ['this'], ['is'], ['is', 'this'], ['hello'], ['hello', 'this'], ['hello', 'is'], ['hello', 'is', 'this'], ['btechgeeks'], ['btechgeeks', 'this'],
 ['btechgeeks', 'is'], ['btechgeeks', 'is', 'this'], ['btechgeeks', 'hello'], ['btechgeeks', 'hello', 'this'], ['btechgeeks', 'hello',
 'is'], ['btechgeeks', 'hello', 'is', 'this']]

Program to Create a Class and Get All Possible Subsets from a List in Python

Below are the ways to print all the subsets of the given list using classes in Python.

i)Integer List

Approach:

  • Give the integer list as static input and store it in a variable.
  • Method sortlist() is used to pass an empty list and the user-supplied sorted list to method printSubsets().
  • Create an object to represent the class.
  • Call the sortlist method with the object created above.
  • To compute all possible subsets of the list, the method printSubsets() is called from sortlist() method.
  • The printSubsetsis used to return all possible sublists of the given list.
  • The Exit of the program.

Below is the implementation:

class sublist:
    def sortlist(self, given_list):
      # To compute all possible subsets of the list, the method
      # printSubsets() is called from sortlist() method.
        return self.printSubsets([], sorted(given_list))
    # The printSubsetsis used to return all possible sublists of the given list.

    def printSubsets(self, curr, given_list):
        if given_list:
            return self.printSubsets(curr, given_list[1:]) + self.printSubsets(curr + [given_list[0]], given_list[1:])
        return [curr]


# given list
given_list = [4, 19, 2, 5, 3]
# Create an object to represent the class.
listobj = sublist()
# Call the sortlist method with the object created above.
print("Subsets of the given list", given_list, ":")
print(sublist().sortlist(given_list))

Output:

Subsets of the given list [4, 19, 2, 5, 3] :
[[], [19], [5], [5, 19], [4], [4, 19], [4, 5], [4, 5, 19], [3], [3, 19], [3, 5], [3, 5, 19], [3, 4], [3, 4, 19], [3, 4, 5], [3, 4, 5, 19],
 [2], [2, 19], [2, 5], [2, 5, 19], [2, 4], [2, 4, 19], [2, 4, 5], [2, 4, 5, 19], [2, 3], [2, 3, 19], [2, 3, 5], [2, 3, 5, 19], [2, 3, 4], 
[2, 3, 4, 19], [2, 3, 4, 5], [2, 3, 4, 5, 19]]

ii)String list

Approach:

  • Give the string list as static input and store it in a variable.
  • Method sortlist() is used to pass an empty list and the user-supplied sorted list to method printSubsets().
  • Create an object to represent the class.
  • Call the sortlist method with the object created above.
  • To compute all possible subsets of the list, the method printSubsets() is called from sortlist() method.
  • The printSubsetsis used to return all possible sublists of the given list.
  • The Exit of the program.

Below is the implementation:

class sublist:
    def sortlist(self, given_list):
      # To compute all possible subsets of the list, the method
      # printSubsets() is called from sortlist() method.
        return self.printSubsets([], sorted(given_list))
    # The printSubsetsis used to return all possible sublists of the given list.

    def printSubsets(self, curr, given_list):
        if given_list:
            return self.printSubsets(curr, given_list[1:]) + self.printSubsets(curr + [given_list[0]], given_list[1:])
        return [curr]


# given list
given_list = ['hello', 'this', 'is', 'btechgeeks']
# Create an object to represent the class.
listobj = sublist()
# Call the sortlist method with the object created above.
print("Subsets of the given list", given_list, ":")
print(sublist().sortlist(given_list))

Output:

Subsets of the given list ['hello', 'this', 'is', 'btechgeeks'] :
[[], ['this'], ['is'], ['is', 'this'], ['hello'], ['hello', 'this'], ['hello', 'is'], ['hello', 'is', 'this'], ['btechgeeks'], ['btechgeeks', 'this'],
 ['btechgeeks', 'is'], ['btechgeeks', 'is', 'this'], ['btechgeeks', 'hello'], ['btechgeeks', 'hello', 'this'], ['btechgeeks', 'hello',
 'is'], ['btechgeeks', 'hello', 'is', 'this']]

Explanation:

  • A class called sublist is defined, as are the methods sortlist() and printSubsets.
  • The function sortlist of the class sub is then called, with the user’s list as a parameter.
  • Method sortlist, in turn, calls method printSubsets with an empty list and the user-supplied sorted list as inputs.
  • The printSubsets method is a recursive function.
  • This method computes all possible subsets by splits the given list into parts, starting with an empty list, and updating the given list’s value.
  • This process is repeated until the given list is empty.
  • The current value of the list is returned, which is a list containing subsets as separate lists.
  • The sublists are printed.

Related Programs:

Python Program to Create a Class and Get All Possible Subsets from a List Read More »

Program to Remove Adjacent Duplicate Characters from a String

Python Program to Remove Adjacent Duplicate Characters from a String | How to Remove All Adjacent Duplicates from a String?

Are you looking for help to remove all the adjacent duplicate characters in a string? Then, this tutorial can be extremely helpful for you as we have compiled all about how to remove adjacent duplicate characters from a string in Python clearly. Refer to the Sample Programs for removing all adjacent duplicates from a string and the function used for doing so.

Remove All Adjacent Duplicates from a String in Python

Given a string, which contains duplicate characters the task is to remove the adjacent duplicate characters from the given string.

Examples:

Example 1:

Input:

given string =bteechhgeeeekkkkssss

Output:

given string before removing adjacent duplicate characters =  bteechhgeeeekkkkssss
given string without after adjacent duplicate characters =  btechgeks

Example 2:

Input:

given string ='appplussstoppperr'

Output:

given string before removing adjacent duplicate characters = appplussstoppperr
given string without after adjacent duplicate characters = aplustoper

How to Remove Adjacent Duplicate Characters from a String in Python?

Below is the full approach to remove the adjacent duplicate characters from the given string in Python.

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

1)Using For loop and If statements(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Pass the given string to the remAdj function which accepts the given string as the argument and returns the modified string with no adjacent duplicates.
  • The aim is to loop through the string, comparing each character to the one before it. If the current character differs from the preceding one, it should be included in the resultant string; otherwise, it should be ignored. The Time Complexity of this approach is n, where n is the length of the input string, and no extra space is required.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

Python Program to Remove Adjacent Duplicate Characters from a String using for Loop and If Statements

# Function to remove adjacent duplicates characters from a string
def remAdj(givenstrng):
    # convert the given string to list using list() function
    charslist = list(givenstrng)
    prevele = None
    p = 0
    # Traverse the given string
    for chars in givenstrng:
        if prevele != chars:
            charslist[p] = chars
            prevele = chars
            p = p + 1
    # join the list which contains characters to string using join function and return it
    return ''.join(charslist[:p])


# Driver code
# Give the string as static input and store it in a variable.
givenstrng = "bteechhgeeeekkkkssss"
# printing the given string before removing adjacent duplicate characters
print('given string before removing adjacent duplicate characters = ', givenstrng)
# Pass the given string to the remAdj function which accepts
# the given string as the argument
# and returns the modified string with no adjacent duplicates.
modistring = remAdj(givenstrng)
# printing the given string after removing adjacent duplicate characters
print('given string without after adjacent duplicate characters = ', modistring)

Output:

given string before removing adjacent duplicate characters =  bteechhgeeeekkkkssss
given string without after adjacent duplicate characters =  btechgeks

2)Using For loop and If statements(User Input)

Approach:

  • Give the string as user input using the input() function.
  • Store it in a variable.
  • Pass the given string to the remAdj function which accepts the given string as the argument and returns the modified string with no adjacent duplicates.
  • The aim is to loop through the string, comparing each character to the one before it. If the current character differs from the preceding one, it should be included in the resultant string; otherwise, it should be ignored. The Time Complexity of this approach is n, where n is the length of the input string, and no extra space is required.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

Python Program to Remove Adjacent Duplicate Characters from a String using for Loop and If Statements(User Input)

# Function to remove adjacent duplicates characters from a string
def remAdj(givenstrng):
    # convert the given string to list using list() function
    charslist = list(givenstrng)
    prevele = None
    p = 0
    # Traverse the given string
    for chars in givenstrng:
        if prevele != chars:
            charslist[p] = chars
            prevele = chars
            p = p + 1
    # join the list which contains characters to string using join function and return it
    return ''.join(charslist[:p])


# Driver code
# Give the string as user input using the input() function.
# Store it in a variable.
givenstrng = input('Enter some random string = ')
# printing the given string before removing adjacent duplicate characters
print('given string before removing adjacent duplicate characters = ', givenstrng)
# Pass the given string to the remAdj function which accepts
# the given string as the argument
# and returns the modified string with no adjacent duplicates.
modistring = remAdj(givenstrng)
# printing the given string after removing adjacent duplicate characters
print('given string without after adjacent duplicate characters = ', modistring)

Output:

Enter some random string = appplussstoppperr
given string before removing adjacent duplicate characters = appplussstoppperr
given string without after adjacent duplicate characters = aplustoper

Related Programs:

Python Program to Remove Adjacent Duplicate Characters from a String | How to Remove All Adjacent Duplicates from a String? Read More »

Program to Create a Class and Compute the Area and the Perimeter of the Circle

Python Program to Create a Class and Compute the Area and the Perimeter of the Circle

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Object-Oriented Programming(OOPS):

Object-Oriented Programming (OOP) is a programming paradigm based on the concepts of classes and objects. It is used to organize a software program into simple, reusable code blueprints (typically referred to as classes), which are then used to build individual instances of objects. Object-oriented programming languages include JavaScript, C++, Java, and Python, among others.

A class is a generic blueprint that can be used to generate more specific, concrete things. Classes are frequently used to represent broad groups, such as Cars or Dogs, that share property. These classes indicate what properties, such as color, an instance of this type will have, but not the value of those attributes for a specific object.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Python, like other general-purpose programming languages, has always been an object-oriented language. It enables us to create a program with an Object-Oriented approach. Classes and objects are simple to build and utilize in Python.

Given the radius of the circle, the task is to write the python program using classes that calculate the area and perimeter of the circle.

Examples:

Example1:

Input:

given radius = 13.5

Output:

The Perimeter of circle with given radius 13.5 = 84.823
The Area of circle with given radius 13.5 = 572.5553

Example2:

Input:

given radius = 20.98

Output:

The Perimeter of circle with given radius 20.98 = 131.8212
The Area of circle with given radius 20.98 = 1382.8047

Program to Create a Class and Compute the Area and the Perimeter of the Circle

Below is the full approach for writing a Python program that creates a class with two methods that calculate the area and perimeter of the circle.

1)Using Classes(Static Input)

Approach:

  • Give the radius of the circle as static input and store it in a variable.
  • Create a class and use a parameterized constructor to initialize its value (radius of the circle).
  • Create two methods inside the class.
  • printPerimeter: which calculates the perimeter of the circle and returns it.
  • printArea: which calculates the area of the circle and returns it.
  • Create an object to represent the class.
  • Call both methods with the object created above.
  • Hence the area and perimeter of the circle are calculated and printed.
  • The Exit of the Program.

Below is the implementation:

# importing math module
import math
# creating a class


class circleClass():
  # use a parameterized constructor to initialize its value (radius of the circle).
    def __init__(self, circleradius):
        self.circleradius = circleradius
    # Create two methods inside the class.
    # printArea: which calculates the area of the circle and returns it.

    def printArea(self):
        return math.pi*(self.circleradius**2)
     # printPerimeter: which calculates the perimeter of the circle and returns it.

    def printPerimeter(self):
        return 2*math.pi*self.circleradius


# Give the radius of the circle as static input and store it in a variable.
circleradius = 13.5
# Create an object to represent the class.
circleobj = circleClass(circleradius)
# Call both methods with the object created above.
# Hence the area and perimeter of the circle are calculated and printed.
print("The Perimeter of circle with given radius",
      circleradius, '=', round(circleobj.printPerimeter(), 4))
print("The Area of circle with given radius", circleradius,
      '=', round(circleobj.printArea(), 4))

Output:

The Perimeter of circle with given radius 13.5 = 84.823
The Area of circle with given radius 13.5 = 572.5553

Explanation:

  • The radius value must be given as static input from the user.
  • A circle class is created, and the __init__() method is used to initialize the class’s values (radius of the circle.
  • The area method returns math. pi*(self. radius**2), which is the class’s area.
  • Another method, perimeter, returns 2*math. pi*self. radius, which represents the class’s perimeter.
  • The class’s object is created.
  • The methods printArea() and printPerimeter() are called using the object.
  • The area and perimeter of the circle are printed.

2)Using Classes(User Input)

Approach:

  • Give the radius of the circle as user input using float(input()) and store it in a variable.
  • Create a class and use a parameterized constructor to initialize its value (radius of the circle).
  • Create two methods inside the class.
  • printPerimeter: which calculates the perimeter of the circle and returns it.
  • printArea: which calculates the area of the circle and returns it.
  • Create an object to represent the class.
  • Call both methods with the object created above.
  • Hence the area and perimeter of the circle are calculated and printed.
  • The Exit of the Program.

Below is the implementation:

# importing math module
import math
# creating a class


class circleClass():
  # use a parameterized constructor to initialize its value (radius of the circle).
    def __init__(self, circleradius):
        self.circleradius = circleradius
    # Create two methods inside the class.
    # printArea: which calculates the area of the circle and returns it.

    def printArea(self):
        return math.pi*(self.circleradius**2)
     # printPerimeter: which calculates the perimeter of the circle and returns it.

    def printPerimeter(self):
        return 2*math.pi*self.circleradius


# Give the radius of the circle as user input using float(input()) and store it in a variable.
circleradius = float(input('Enter some random radius of the circle = '))
# Create an object to represent the class.
circleobj = circleClass(circleradius)
# Call both methods with the object created above.
# Hence the area and perimeter of the circle are calculated and printed.
print("The Perimeter of circle with given radius",
      circleradius, '=', round(circleobj.printPerimeter(), 4))
print("The Area of circle with given radius", circleradius,
      '=', round(circleobj.printArea(), 4))

Output:

Enter some random radius of the circle = 20.98
The Perimeter of circle with given radius 20.98 = 131.8212
The Area of circle with given radius 20.98 = 1382.8047

Related Programs:

Python Program to Create a Class and Compute the Area and the Perimeter of the Circle Read More »

Program to Remove the First Occurrence of Character in a String

Python Program to Remove the First Occurrence of Character in a String

In this article, we’ll learn how to use Python to remove the first occurrence of a character in a string. The aim is to remove the first occurrence of a character in a string. To begin, locate the character in the string and confirm that it is the first occurrence. Finally, remove the character from the string and display the result.

Examples:

Example1:

Input:

Given String =goodmorningthisisbtechgeekspython
Given Character =s

Output:

The Given string after removing first occurence of the character [ s ] is goodmorningthisisbtechgeekspython
The Given string after removing first occurence of the character [ s ] is goodmorningthiisbtechgeekspython

Example2:

Input:

Given String =hellothisisbtechgeeks
Given Character =e

Output:

The Given string after removing first occurence of the character [ e ] is hellothisisbtechgeeks
The Given string after removing first occurence of the character [ e ] is hllothisisbtechgeeks

Program to Remove the First Occurrence of Character in a String in Python

Below are the ways to remove the first occurrence of the given character in a string in Python.

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

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the character as static input and store it in another variable.
  • Calculate the length of the string using the len() function.
  • Loop in the characters of the string using the For loop.
  • Check if the iterator character is equal to the given character using the if conditional statement and == operator.
  • Initialize the resultstrng with the given string from 0 to iterator value concatenated with iterator value +1 to the length of the given string.
  • Break the For loop using the break keyword.
  • Print the Result.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'hellothisisbtechgeeks'
# Give the character as static input and store it in another variable.
gvnchar = 'e'
# Calculate the length of the string using the len() function.
strnglength = len(gvnstrng)
# Loop in the characters of the string using the For loop.
for i in range(strnglength):
  # Check if the iterator character is equal to the given character
  # using the if conditional statement and == operator.
    if(gvnstrng[i] == gvnchar):
      # Initialize the resultstrng with the given string
      # from 0 to iterator value concatenated
      # with iterator value +1 to the length of the given string.
        reesultvalu = gvnstrng[0:i] + gvnstrng[i + 1:strnglength]
        # Break the For loop using the break keyword.
        break
# Print the Result.
print(
    'The Given string after removing first occurence of the character [', gvnchar, '] is', gvnstrng)
print(
    'The Given string after removing first occurence of the character [', gvnchar, '] is', reesultvalu)

Output:

The Given string after removing first occurence of the character [ e ] is hellothisisbtechgeeks
The Given string after removing first occurence of the character [ e ] is hllothisisbtechgeeks

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Give the character as user input using the input() function and store it in another variable.
  • Calculate the length of the string using the len() function.
  • Loop in the characters of the string using the For loop.
  • Check if the iterator character is equal to the given character using the if conditional statement and == operator.
  • Initialize the resultstrng with the given string from 0 to iterator value concatenated with iterator value +1 to the length of the given string.
  • Break the For loop using the break keyword.
  • Print the Result.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvnstrng = input('Enter some random given string = ')
# Give the character as user input using the input() function and store it in another variable.
gvnchar = input('Enter some random character = ')
# Calculate the length of the string using the len() function.
strnglength = len(gvnstrng)
# Loop in the characters of the string using the For loop.
for i in range(strnglength):
  # Check if the iterator character is equal to the given character
  # using the if conditional statement and == operator.
    if(gvnstrng[i] == gvnchar):
      # Initialize the resultstrng with the given string
      # from 0 to iterator value concatenated
      # with iterator value +1 to the length of the given string.
        reesultvalu = gvnstrng[0:i] + gvnstrng[i + 1:strnglength]
        # Break the For loop using the break keyword.
        break
# Print the Result.
print(
    'The Given string after removing first occurence of the character [', gvnchar, '] is', gvnstrng)
print(
    'The Given string after removing first occurence of the character [', gvnchar, '] is', reesultvalu)

Output:

Enter some random given string = goodmorningthisisbtechgeekspython
Enter some random character = s
The Given string after removing first occurence of the character [ s ] is goodmorningthisisbtechgeekspython
The Given string after removing first occurence of the character [ s ] is goodmorningthiisbtechgeekspython

Related Programs:

Python Program to Remove the First Occurrence of Character in a String Read More »

Program to Compute all the Permutations of the String

Python Program to Compute all the Permutations of the String

Strings in Python:

A string is a group of alphabets, words, or other characters. It is a primitive data structure that serves as the foundation for data manipulation. Python has a string class called str. Strings in Python are “immutable,” which means they can’t be modified once they’re formed. Because of the immutability of strings, we generate new strings as we go to represent computed values.

Permutations:

The term “permutations” refers to the various ways in which elements can be organized. The elements may be strings, lists, or some other form of data. It is the rearranging of objects in various ways.

Given a string, the task is to print all the possible permutations of the given string in python.

Examples:

Example1:

Input:

string="cold"

Output:

Printing all permutations of the given string cold
cold
codl
clod
cldo
cdlo
cdol
ocld
ocdl
olcd
oldc
odlc
odcl
locd
lodc
lcod
lcdo
ldco
ldoc
dolc
docl
dloc
dlco
dclo
dcol

Example2:

Input:

string="win"

Output:

Printing all permutations of the given string win
win
wni
iwn
inw
niw
nwi

Program to Compute all the Permutations of the String in Python

Below are the ways to compute all the permutations of a string in python:

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Method #1:Using Recursion(NaĂŻve Approach)

To solve this problem, we must first grasp the idea of Backtracking.

Solving this problem using Backtracking algorithm

Let us consider the given string is ‘ABC’.

The Backtracking algorithm :

  • Fix one of the characters in the first place and replace the rest of the characters with the first. In the first iteration, three strings are generated, as in ABC, by swapping A with A, B, and C, respectively.
  • Repeat step 1 for the remaining characters, such as fixing second character B, and so on.
  • Now go back to your previous place. For example, from ABC, we shaped ABC by fixing B again, then we returned to the previous position and swapped B with C. So we now have ABC and ACB.
  • To get all the permutations, repeat these steps for BAC and CBA.

Approach:

  • Scan the given string.
  • Fix one of the characters and swap the others.
  • For the remaining characters, use printPermutations() function.
  • Retrace your steps and swap the characters once more.

Below is the implementation:

# function which prints the permutations
def printPermutations(string, start, end):
    i = 0
    # printing the permutations
    if(start == end-1):
        print(string)
    else:
        for i in range(start, end):

           # Fixing a character and swapping the string
            samstring = list(string)
            # swapping using ,
            samstring[start], samstring[i] = samstring[i], samstring[start]
      # For the remaining characters, call printPermutations() recursively.

            printPermutations("".join(samstring), start+1, end)
            # Fixing a character and swapping the string
            # swapping using ,
            samstring[start], samstring[i] = samstring[i], samstring[start]


# given string
string = "cold"
# calculating the length of string
length = len(string)
print("Printing all permutations of the given string", string)
# passing string and 0th index as it is fixed at the starting
printPermutations(string, 0, length)

Output:

Printing all permutations of the given string cold
cold
codl
clod
cldo
cdlo
cdol
ocld
ocdl
olcd
oldc
odlc
odcl
locd
lodc
lcod
lcdo
ldco
ldoc
dolc
docl
dloc
dlco
dclo
dcol

Method #2:Using itertools permutations function

Using the permutations() function in Python, we may obtain permutations of elements in a list using the built-in module itertools.

We use join() function to join all the characters of the specific function and we store them into list using List Comprehension.

Below is the implementation:

# importing permutations from itertools
from itertools import permutations
# given string
string = "cold"
# Geeting all permutations as a list using comprehension
stringPermutations = [''.join(permutestr)
                      for permutestr in permutations(string)]
print("Printing all permutations of the given string", string)
# print all the permutations of the string
for i in stringPermutations:
    print(i)

Output:

Printing all permutations of the given string cold
cold
codl
clod
cldo
cdol
cdlo
ocld
ocdl
olcd
oldc
odcl
odlc
lcod
lcdo
locd
lodc
ldco
ldoc
dcol
dclo
docl
dolc
dlco
dloc

Related Programs:

Python Program to Compute all the Permutations of the String Read More »

Program to Create a Class in which One Method Accepts a String from the User and Another Prints it

Python Program to Create a Class in which One Method Accepts a String from the User and Another Prints it

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.

Object-Oriented Programming(OOPS):

Object-oriented programming (OOP) is a form of program structure that involves grouping related characteristics and activities into separate objects.

Objects are conceptually similar to system components. Consider a program to be a sort of factory assembly line. A system component processes some material at each step of the assembly line, eventually changing raw material into a finished product.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Python, like other general-purpose programming languages, has always been an object-oriented language. It enables us to create a program with an Object-Oriented approach. Classes and objects are simple to build and utilize in Python.

Using classes and objects, an object-oriented paradigm is used to construct the code. The object is associated with real-world entities such as a book, a house, a pencil, and so on. The oops notion is concerned with building reusable code. It is a common strategy for solving problems by constructing objects.

The task is to write a Python program that creates a class with one method that accepts a string from the user and another that prints it.

Examples:

Example1:

Input:

Enter some random string = btechgeeks

Output:

The string = btechgeeks

Example2:

Input:

Enter some random string = samokestring

Output:

The string = samokestring

Program to Create a Class in which One Method Accepts a String from the User and other Prints it in Python

Below is the full approach for writing a Python program that creates a class with one method that accepts a string from the user and another that prints it.

Approach:

  • Create a class and use the constructor to initialize the class’s values(here it is a string).
  • Create two methods inside the class.
  • getString: which scans the value of the given string.
  • putString: Which prints the value of the given string.
  • Create an object to represent the class.
  • Call both methods with the object created above.
  • Hence the string is scanned and printed.
  • The Exit of the Program.

Below is the implementation:

# creating a class
class stringClass():
  # use the constructor to initialize the class's values(here it is a string).
    def __init__(self):
        self.string = ""
    # Creating two methods inside the class.
    # getString: which scans the value of the given string

    def getString(self):
      # using input() function to scan the value of the string.
        self.string = input("Enter some random string = ")
   # putString: Which prints the value of the given string.

    def putString(self):
      # printing the string
        print("The string  =", self.string)


# Create an object to represent the class.
stringobj = stringClass()
# Call both methods with the object created above.
# calling getString method which scans the value of string
stringobj.getString()
# calling putString method which prints the value of the string
stringobj.putString()

Output:

Enter some random string = btechgeeks
The string = btechgeeks

Explanation:

  • A class called stringClass is created, and the __init__() function is used to set the string’s value to ” “(which is the default constructor in this case).
  • The first method (getString), Scan’s the string’s value from the user using input() function)
  • The second method (putString) is used to print the string’s value.
  • A class object called stringobj is created.
  • The methods getString() and putString() are printed using the object.
  • The string’s value which is scanned using getString is printed using putString.

Related Programs:

Python Program to Create a Class in which One Method Accepts a String from the User and Another Prints it Read More »

Write a Program to Implement Simple Calculator

Python Program to Make a Simple Calculator

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

When it comes to working with numbers and evaluating mathematical equations, the Python programming language is an excellent choice. This quality can be used to create beneficial software.

This tutorial will walk you through creating a simple command-line calculator app in Python 3. While we’ll go over one method for creating this software, there are several ways to modify the code and develop a more sophisticated calculator.

To create our calculator, we’ll employ math operators, variables, conditional statements, functions, and user input.

Program to Implement Simple Calculator

Below are the steps to implement the simple calculator in python:

1)Taking input from user

When a human enters equations for the computer to solve, it works best. We’ll begin developing our program where the human enters the numbers that they want the computer to operate with.

To accomplish this, we’ll use Python’s built-in input() function, which accepts user-generated keyboard input. We can supply a string to prompt the user inside the parenthesis of the input() function. The user’s input will be assigned to a variable.

We want the user to enter two numbers for this application, so make the software prompt for two numbers. We should include a space at the end of our string when asking for input so that the user’s input is separated from the prompting string.

# given two numbers
number1 = input("Enter the first number of which we wan to do perform calculation: ")
number2 = input("Enter the first number of which we wan to do perform calculation: ")

If you run this program a few times with different input, you’ll find that when prompted, you can enter anything you want, including words, symbols, whitespace, or just the enter key. This is due to the fact that input() accepts data as strings and is unaware that we are seeking for a number.

We want to utilize a number in this software for two reasons:

  1. To allow it to execute mathematical calculations.
  2. To ensure that the user’s input is a numerical string.

Depending on the calculator’s requirements, we may want to convert the string returned by the input() function to an integer or a float. We’ll wrap the input() function in the int() method to convert the input to the integer data type, as whole numbers suit our needs.

# given two numbers
number1 = int(input("Enter the first number of which we wan to do perform calculation: "))
number2 = int(input("Enter the first number of which we wan to do perform calculation: "))

2)Defining and implementing mathematical operators

Let’s now add operators to our Calculator software, such as addition, multiplication, division, and subtraction.

Below is the implementation:

# given two numbers
number1 = int(
    input("Enter the first number of which we wan to do perform calculation: "))
number2 = int(
    input("Enter the first number of which we wan to do perform calculation: "))
# adding the given two numbers
print('{} + {} = '.format(number1, number2))
print(number1 + number2)

# subtracting the given two numbers
print('{} - {} = '.format(number1, number2))
print(number1 - number2)

# multiplying the given two numbers
print('{} * {} = '.format(number1, number2))
print(number1 * number2)

# dividing the given two numbers
print('{} / {} = '.format(number1, number2))
print(number1 / number2)

Output:

Enter the first number of which we wan to do perform calculation: 19
Enter the first number of which we wan to do perform calculation: 13
19 + 13 = 
32
19 - 13 = 
6
19 * 13 = 
247
19 / 13 = 
1.4615384615384615

If you look at the result above, you’ll note that as soon as the user enters number 1 as 19 and number 2 as 13, the calculator does all of its operations.
We’ll have to utilize conditional statements and make the entire calculator software a user-choice based operation program if we want to limit the program to only performing one operation at a time.

3)Using conditional statements for user-choice based operation Program

So, to make the user realize what he or she is expected to choose, we’ll start by adding some information at the top of the program, along with a decision to make.

Below is the implementation:

givenChoice = input('''
Please select which type of operation which we want to apply\n
enter + for addition operation\n
enter - for subtraction  operation\n
enter * for multiplication  operation\n
enter / for division  operation\n''')
# given two numbers
number1 = int(
    input("Enter the first number of which we wan to do perform calculation: "))
number2 = int(
    input("Enter the first number of which we wan to do perform calculation: "))
if givenChoice == "+":
    # adding the given two numbers
    print('{} + {} = '.format(number1, number2))
    print(number1 + number2)
elif givenChoice == "-":
    # subtracting the given two numbers
    print('{} - {} = '.format(number1, number2))
    print(number1 - number2)
elif givenChoice == "*":
    # multiplying the given two numbers
    print('{} * {} = '.format(number1, number2))
    print(number1 * number2)
elif givenChoice == "/":
    # dividing the given two numbers
    print('{} / {} = '.format(number1, number2))
    print(number1 / number2)
else:
    print("You have entered the invalid operation")

Output:

Please select which type of operation which we want to apply

enter + for addition operation

enter - for subtraction operation

enter * for multiplication operation

enter / for division operation
+
Enter the first number of which we wan to do perform calculation: 19
Enter the first number of which we wan to do perform calculation: 13
19 + 13 = 
32

Related Programs:

Python Program to Make a Simple Calculator Read More »

Program to Find the Area of a Rectangle Using Classes

Python Program to Find the Area of a Rectangle Using Classes

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Object-Oriented Programming(OOPS):

Object-oriented programming (OOP) is a form of program structure that involves grouping related characteristics and activities into separate objects.

Objects are conceptually similar to system components. Consider a program to be a sort of factory assembly line. A system component processes some material at each step of the assembly line, eventually changing raw material into a finished product.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Given length and breadth, the task is to calculate the area of the rectangle with the given length and breadth using classes.

Examples:

Example1:

Input:

given length of rectangle = 15
given breadth of rectangle = 11

Output:

The area of the rectangle with the given sides 15 , 11 = 165

Example2:

Input:

given length of rectangle = 31
given breadth of rectangle = 19

Output:

The area of the rectangle with the given sides 31 , 19 = 589

Program to Find the Area of a Rectangle Using Classes in Python

Below is the full approach to calculate the area of the rectangle with the given length and breadth using classes in Python.

1)Using Classes(Static Input)

Approach:

  • Give the length and breadth as static input and store it in two variables.
  • Create a class and use a parameterized constructor to initialize its values (length and breadth of the rectangle).
  • Create a method called areaofRect that returns the area with the given length and breadth of the rectangle.
  • Create an object to represent the class.
  • Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
  • Print the area of the rectangle.
  • The exit of the program.

Below is the implementation:

# creating a class
class rectangle():
  # parameterized constructor with breadth and length as arguments
  # parameterized constructor is used to initialize its values (length and breadth of the rectangle).
    def __init__(self, rectbreadth, rectlength):
        self.rectbreadth = rectbreadth
        self.rectlength = rectlength
    # Creating a method called areaofRect that returns the area with the given length and breadth of the rectangle

    def areaofRect(self):
        return self.rectbreadth*self.rectlength


# Give the length and breadth as static input and store it in two variables.
rectlength = 31
rectbreadth = 19
# Creating an object to represent the class.
# Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
rectObj = rectangle(rectlength, rectbreadth)
print("The area of the rectangle with the given sides",
      rectlength, ',', rectbreadth, '=', rectObj.areaofRect())

Output:

The area of the rectangle with the given sides 31 , 19 = 589

2)Using Classes(User Input separated by spaces)

Approach:

  • Scan the given length and breadth as user input using a map, int, and split() functions and store them in two variables.
  • Create a class and use a parameterized constructor to initialize its values (length and breadth of the rectangle).
  • Create a method called areaofRect that returns the area with the given length and breadth of the rectangle.
  • Create an object to represent the class.
  • Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
  • Print the area of the rectangle.
  • The exit of the program.

Below is the implementation:

# creating a class
class rectangle():
  # parameterized constructor with breadth and length as arguments
  # parameterized constructor is used to initialize its values (length and breadth of the rectangle).
    def __init__(self, rectbreadth, rectlength):
        self.rectbreadth = rectbreadth
        self.rectlength = rectlength
    # Creating a method called areaofRect that returns the area with the given length and breadth of the rectangle

    def areaofRect(self):
        return self.rectbreadth*self.rectlength


# Scan the given length and breadth as user input using a map, int, 
#and split() functions and store them in two variables.
rectlength, rectbreadth = map(int, input('Enter the length and breadth of the rectangle separated by spaces = ').split())
# Creating an object to represent the class.
# Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
rectObj=rectangle(rectlength, rectbreadth)
print("The area of the rectangle with the given sides",
      rectlength, ',', rectbreadth, '=', rectObj.areaofRect())

Output:

Enter the length and breadth of the rectangle separated by spaces = 7 9
The area of the rectangle with the given sides 7 , 9 = 63

Explanation:

  • The user must provide the length and breadth values.
  • A rectangle class is created, and the __init__() method is used to initialize the class’s values.
  • The area method returns self. length*self. breadth, which is the class’s area.
  • The class’s object is created.
  • Using the object, the method area() is invoked with the length and breadth as the parameters given by the user.
  • The area has been printed.

3)Using Classes(User Input separated by newline)

Approach:

  • Scan the rectangle’s length as user input using the int(input()) function and store it in a  variable.
  • Scan the rectangle’s breadth as user input using the int(input()) function and store it in another variable.
  • Here int() is used to convert the given number to integer datatype.
  • Create a class and use a parameterized constructor to initialize its values (length and breadth of the rectangle).
  • Create a method called areaofRect that returns the area with the given length and breadth of the rectangle.
  • Create an object to represent the class.
  • Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
  • Print the area of the rectangle.
  • The exit of the program.

Below is the implementation:

# creating a class
class rectangle():
  # parameterized constructor with breadth and length as arguments
  # parameterized constructor is used to initialize its values (length and breadth of the rectangle).
    def __init__(self, rectbreadth, rectlength):
        self.rectbreadth = rectbreadth
        self.rectlength = rectlength
    # Creating a method called areaofRect that returns the area with the given length and breadth of the rectangle

    def areaofRect(self):
        return self.rectbreadth*self.rectlength


# Scan the rectangle's length as user input using the int(input()) function and store it in a  variable.
rectlength = int(input('Enter some random length of the rectangle = '))
# Scan the rectangle's breadth as user input using the int(input()) function and store it in another variable.
# Here int() is used to convert the given number to integer datatype.
rectbreadth = int(input('Enter some random breadth of the rectangle = '))
# Creating an object to represent the class.
# Call the method areaofRect() on the object with the length and breadth as the parameters taken from the user as static input.
rectObj = rectangle(rectlength, rectbreadth)
print("The area of the rectangle with the given sides",
      rectlength, ',', rectbreadth, '=', rectObj.areaofRect())

Output:

Enter some random length of the rectangle = 15
Enter some random breadth of the rectangle = 11
The area of the rectangle with the given sides 15 , 11 = 165

Explanation:

  • The user must provide the length and breadth values.
  • A rectangle class is created, and the __init__() method is used to initialize the class’s values.
  • The area method returns self. length*self. breadth, which is the class’s area.
  • The class’s object is created.
  • Using the object, the method area() is invoked with the length and breadth as the parameters given by the user.
  • The area has been printed.

Related Programs:

Python Program to Find the Area of a Rectangle Using Classes Read More »