Calculate the slant height for the given cone – Python Program to Find Volume and Surface Area of a Cone

Program to Find Volume and Surface Area of a Cone

Calculate the slant height for the given cone: In the previous article, we have discussed Python Program to Calculate Sum of Series 1³+2³+3³+….+n³
The surface area of a cone : 

Formula to calculate its surface area:
Surface Area = Area of a Cone + Area of a Circle
i.e. Surface Area of cone = πrl + πr²
In which  ‘r’ denotes radius and

‘l’ denotes slant (Length of an edge from the top of the cone to edge of a cone)

If we know the radius and height of a cone, we can use the following formula to calculate its surface area:
Surface Area = πr² +πr √h² + r²
It can also be written as:
Surface Area of a cone =  πr (r+√h² + r²)

Because the radius, height, and slant combine to form a right-angled triangle. So, using Pythagoras’ theorem:

l² = h² + r²
l = √h² + r²

The volume of a cone :

Volume refers to the amount of space inside the Cone. If we know the radius and height of the cone, we can use the following formula to calculate the volume:
The volume of a cone= 1/3 πr²h  (where h = height of a cone)

A Cone’s Lateral Surface Area = πrl

Given the radius and height of a cone, the task is to find the surface area, volume, and lateral surface for a given cone.

Examples:

Example 1:

Input:

Given radius = 6.5
Given height = 10

Output:

The given cone's slant height = 11.927
The given surface Area of a cone with given radius,height[ 6.5 10 ]= 376.283
The given volume of a cone with given radius,height[ 6.5 10 ]= 442.441
The given lateral surface Area of a cone with given radius,height[ 6.5 10 ]= 243.551

Example 2:

Input:

Given radius =  4
Given height = 8

Output:

The given cone's slant height = 8.944
The given surface Area of a cone with given radius,height[ 4 8 ]= 162.663
The given volume of a cone with given radius,height[ 4 8 ]= 134.041
The given lateral surface Area of a cone with given radius,height[ 4 8 ]= 112.397

Program to Find Volume and Surface Area of a Cone

Below are the ways to find the surface area, volume, and lateral surface for a given cone.

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the radius of a cone as static input and store it in a variable.
  • Give the height of a cone as static input and store it in another variable.
  • Calculate the Slant height of a given cone using the above given mathematical formula and math.sqrt() function and store it in another variable.
  • Calculate the surface area of a given cone using the above given mathematical formula and math.pi function
  • Store it in another variable.
  • Calculate the volume of a given cone using the above given mathematical formula and math.pi function
  • Store it in another variable.
  • Calculate the lateral surface area of a given cone using the above given mathematical formula and math.pi function.
  • Store it in another variable.
  • Print the slant height of a given cone.
  • Print the surface area of a given cone.
  • Print the volume of a given cone.
  • Print the lateral surface area of a given cone.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the radius of a cone as static input and store it in a variable.
gvn_rad = 6.5
# Give the height of a cone as static input and store it in another variable.
gvn_heigt = 10
# Calculate the Slant height of a given cone using the above given mathematical formula
# and math.sqrt() function and store it in another variable.
slant_l = math.sqrt(gvn_rad * gvn_rad + gvn_heigt * gvn_heigt)
# Calculate the surface area of a given cone using the above given mathematical formula and math.pi function
# Store it in another variable.
surf_area = math.pi * gvn_rad * (gvn_rad + slant_l)
# Calculate the volume of a given cone using the above given mathematical formula and
# math.pi function
# Store it in another variable.
Vol = (1.0/3) * math.pi * gvn_rad * gvn_rad * gvn_heigt
# Calculate the lateral surface area of a given cone using the above given mathematical
# formula and math.pi function.
# Store it in another variable.
Laterl_surfcarea = math.pi * gvn_rad * slant_l
# Print the slant height of a given cone.
print("The given cone's slant height = %.3f" % slant_l)
# Print the surface area of a given cone.
print(
    "The given surface Area of a cone with given radius,height[", gvn_rad, gvn_heigt, "]= %.3f" % surf_area)
# Print the volume of a given cone.
print(
    "The given volume of a cone with given radius,height[", gvn_rad, gvn_heigt, "]= %.3f" % Vol)
# Print the lateral surface area of a given cone.
print(
    "The given lateral surface Area of a cone with given radius,height[", gvn_rad, gvn_heigt, "]= %.3f " % Laterl_surfcarea)

Output:

The given cone's slant height = 11.927
The given surface Area of a cone with given radius,height[ 6.5 10 ]= 376.283
The given volume of a cone with given radius,height[ 6.5 10 ]= 442.441
The given lateral surface Area of a cone with given radius,height[ 6.5 10 ]= 243.551

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import math module using the import keyword.
  • Give the radius of a cone as user input using the float(input()) function and store it in a variable.
  • Give the height of a cone as user input using the float(input()) function and store it in another variable.
  • Calculate the Slant height of a given cone using the above given mathematical formula and math.sqrt() function and store it in another variable.
  • Calculate the surface area of a given cone using the above given mathematical formula and math.pi function
  • Store it in another variable.
  • Calculate the volume of a given cone using the above given mathematical formula and math.pi function
  • Store it in another variable.
  • Calculate the lateral surface area of a given cone using the above given mathematical formula and math.pi function.
  • Store it in another variable.
  • Print the slant height of a given cone.
  • Print the surface area of a given cone.
  • Print the volume of a given cone.
  • Print the lateral surface area of a given cone.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the radius of a cone user input using the float(input()) function and store it in a variable.
gvn_rad = float(input("Enter some random number = "))
# Give the height of a cone user input using the float(input()) function and store it in another variable.
gvn_heigt = float(input("Enter some random number = "))
# Calculate the Slant height of a given cone using the above given mathematical formula
# and math.sqrt() function and store it in another variable.
slant_l = math.sqrt(gvn_rad * gvn_rad + gvn_heigt * gvn_heigt)
# Calculate the surface area of a given cone using the above given mathematical formula and math.pi function
# Store it in another variable.
surf_area = math.pi * gvn_rad * (gvn_rad + slant_l)
# Calculate the volume of a given cone using the above given mathematical formula and
# math.pi function
# Store it in another variable.
Vol = (1.0/3) * math.pi * gvn_rad * gvn_rad * gvn_heigt
# Calculate the lateral surface area of a given cone using the above given mathematical
# formula and math.pi function.
# Store it in another variable.
Laterl_surfcarea = math.pi * gvn_rad * slant_l
# Print the slant height of a given cone.
print("The given cone's slant height = %.3f" % slant_l)
# Print the surface area of a given cone.
print(
    "The given surface Area of a cone with given radius,height[", gvn_rad, gvn_heigt, "]= %.3f" % surf_area)
# Print the volume of a given cone.
print(
    "The given volume of a cone with given radius,height[", gvn_rad, gvn_heigt, "]= %.3f" % Vol)
# Print the lateral surface area of a given cone.
print(
    "The given lateral surface Area of a cone with given radius,height[", gvn_rad, gvn_heigt, "]= %.3f " % Laterl_surfcarea)

Output:

Enter some random number = 4.5
Enter some random number = 2
The given cone's slant height = 4.924
The given surface Area of a cone with given radius,height[ 4.5 2.0 ]= 133.235
The given volume of a cone with given radius,height[ 4.5 2.0 ]= 42.412
The given lateral surface Area of a cone with given radius,height[ 4.5 2.0 ]= 69.617

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

What can you do with python – What can you do with python: Usage guide | 9 Cool Things to do with Python Programming

What Can You Do With Python Usage Guide

Python Programming Language is a very familiar programming language among developers. It is simple and enjoyable to write scripts to automate and build stuff. A complete guide on what can you do with python is in front of your eyes. Kindly python learners and newbies are recommended to check out this python usage tutorial and learn what others do with python and what you do with python.

Along with this, you may also gain enough knowledge on how to learn python and what python programmers can make by using this easy and simple programming language. In case, you don’t have any idea how python is used in education then make a move and click on the link provided here itself.

This What Can You Do With Python Usage Guide will helo you learn the following stuff: 

Prerequisites

  • You should know python’s basic syntax.
  • You should have Python installed on your machine.

What can you do with Python?

What can you do in python: Python is a general-purpose language. You can use it with any kind of application. You can use it as a scripting language to solve some of your daily problems.

A few of the common use cases are as follows:

  • Creating bots
  • Scraping websites
  • Machine learning, data visualization, and analysis
  • Web Development with frameworks like Django and Flask
  • Game development with Pygame
  • Mobile apps with frameworks like Kivy

Scripting with Python

Things to do with python: Let’s take an example. If you’re like photography, you probably have an issue with image naming. After a long day of shooting, you came back to your studio. You filtered the images and put the selected images in a directory. This directory contains different images with different names.

You need to make your work easier by naming all images in a specific format. Let’s say the image name will consist of the place name and sequence numbers. This makes it easy for you to search for images. By using Python you can create a simple script that will go through all files with type JPEG in this folder and rename it.
Scripting with PythonLet’s see an example:

import os 

def main():
    path = input("Enter folder path: ")
    folder = os.chdir(path)

    for count, filename in enumerate(os.listdir()): 
        dst ="NewYork" + str(count) + ".jpeg"
        os.rename(src, dst) 

if __name__ == '__main__':
    main()

As you can see Python is an efficient tool for automation. It helps drive your focus to important things.

What else you can do with Python? You can have an FTP server with python. Using the command

python3 -m http.server 8000

You can run a python server. The server will be accessible over your local network. You can open your browser from a different device. Type your network ip : 8000 . You will have access to all files in this folder. You can use it to transfer files from different devices in the same network.

Such a simple usage of Python in your daily life will make it easier. Talking about servers that leads us to

Python usage in web-based applications

What can you do with python: Python is very popular in web development with frameworks like Flask and Django. If you want to build your own eCommerce store. You can use the Django framework. After installing it you will have a ready project structure to build your website. Let’s see how easy it is to install Django.

# checking django version 
$ python -m django --version

# if you don't have django installed you can install it using pip
$ python -m pip install Django

Note: if didn’t have pip installed you should follow our article for installing it.

After installing Django Now you can create your project.

$ django-admin startproject my-eCommerce-Website

You will have a project structure like below

my-eCommerce-Website/
    manage.py
    my-eCommerce-Website/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

To proceed with the Django project. You should install your project applications

$ python manage.py startapp store

Inside your Django project, you would have all your apps. Each app will have a different folder.

my-eCommerce-Website/
    manage.py
    my-eCommerce-Website/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

You can learn more about Django in their official documentation. You can that getting started with Python for web development is pretty easy.

Python has different usage in different fields Like Data science, game, and mobile development. we talked in detail about it in the previous article.

How to learn Python?

What can you do with python?: Learning Python is a continuous process. Some people prefer Courses, Others prefer hands-on experience. It really doesn’t matter the source you will learn from. You will need to apply what you learned to build useful Python applications. We’ve talked in our previous article about the various resources to learn it. check it here. If you already know it’s basic syntax. Your focus now should be on learning how to build python’s applications.

It depends on the type of application you want to build.  If you’re looking for building a web-based application. The recommendations will be Flask And Django.

Where you can learn Flask?

  • The Flask documentation has a get stating section. It’s very helpful to learn the basics of Flask.
  • Coursera Just released a new Course to learn Flask. It’ll guide you through all Flask details.
  • The tutorial point has a great organized Flask tutorial.

With all the above resources, you’ll build a Flask application. That will give you hands-on experience with Flask.

Where you can learn Django?

  • Django documentation is a detailed resource for learning Django. With its starting guide.
  • Django is the most popular Python framework. Coursera has created a full specialization to learn it.
  • The tutorial point has created an organized source to learn Django. It’s called the Django tutorial.

Again it doesn’t matter what is the source. You need to try writing code and build a project by yourself. It’ll help you build your portfolio.

If you’re looking for building machine learning projects. Udacity and Coursera are great resources to learn it.

Where you can learn Machine Learning?

  • Udacity has an introductory course on machine learning. It’ll guide you through machine learning and artificial intelligence.
  • Stanford has a great course too on Coursera to learn machine learning. It’s presented by Andrew Ng. He is one of the top in the Machine learning and AI fields.
  • If you’re prefer reading. The Tutorial point has a tutorial about Machine learning. It’ll give you the needed knowledge to know more about Machine learning.

What is the time to learn Python?

Learning Python as basics will not take a lot of time. It can be from two to four weeks to be comfortable with it. Learning other frameworks on top of Python might take time. It depends on the field and the difficulty of the framework. Learning how to build an application with Flask or Django might take 4 to 6 weeks. For Machine learning, it can take longer. Machine learning is a more complicated field. It takes more time to learn. Note that time can differ depends on your learning process. Keep in mind that fields Like Machine learning or Data science will require a mathematical background. This might make it longer to learn.

How Much Python programmers make?

Python is used in different industries. This makes it easy to find a job with it. In terms of Your salary, a lot of factors will control this.

  • Your experience
  • Your country
  • Company business size
  • Type of application you’re building

That’s why the more you learn more about it the more is always better. For Exact numbers about your expected salary that matches your experience. You should check Glassdoor. It’ll help you know the average number in your area based on skills.

9 Cool Things You Can Do Using Python

Here we are trying to include various domains that you can do great stuff with python. Have a look at the list of some interesting functionalities that you can do with Python:

  1. For Web Development
  2. Automation and Scripting
  3. Automating your daily routine tasks
  4. Automatically detects what’s in the image
  5. Web Scraping
  6. Data analysis, manipulation, and visualization
  7. Create games with Python
  8. Data Science and Machine Learning
  9. Building robotics applications

Conclusion

Python has a lot of useful usages. It is based on the type of application you want to build. Learning Python is an ongoing process. The more you learn about python the more applications you can build. It’ll help you get a job faster and increase your salary.

Numpy random.choice – Python NumPy random.choice() Function

NumPy random.choice() Function

Numpy random.choice: The random module is part of the NumPy library. This module includes the functions for generating random numbers. This module includes some basic random data generating methods, as well as permutation and distribution functions and random generator functions.

NumPy random.choice() Function:

np.random.choice(): The choice() function of the NumPy random module is used to generate a random sample from a specified 1-D array.

Syntax:

numpy.random.choice(a, size=None, replace=True, p=None)

Parameters

a: This is required. When an ndarray is specified, a random sample is generated from its elements. If the parameter is an int, the random sample is created as if “a” were np.arange (a).

size: This is optional. It specifies the shape of the output. If the supplied shape is (a, b, c), for example, a * b * c samples are drawn. The default value is None, which results in a single item being returned.

replace: This is optional. A boolean indicating whether the sample is with or without replacement.

p: This is optional. Indicate the probabilities associated with each entry in “a.” If no sample is provided, the sample assumes a uniform distribution over all elements in “a.”

Return Value:

The randomly generated samples are returned.

NumPy random.choice() Function in Python

Example1

Numpy random choice: Here, the random.choice() function is used to produce random samples from a provided list.

Approach:

  • Import numpy module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the above-given list, size(row_size, col_size) as arguments to the random.choice() function to get random samples from the given list.
  • Store it in a variable.
  • Print the random samples from the given list of the size given.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np  
# Give the list as static input and store it in a variable.
gvn_lst = [4, 3, 1, 9, 6]
# Pass the above given list, size(row_size, col_size) as arguments to the 
# random.choice() function to get random samples from the given list.
# Store it in a variable.
rslt = np.random.choice(gvn_lst, (2,2))
# Print the random samples from the given list of the size given.
print(rslt)

Output:

[[4 1]
 [6 3]]

Example2

The replace argument draws a sample with replacement.

Approach:

  • Import numpy module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the above-given list, size(row_size, col_size), and replace as “True” as arguments to the random.choice() function to get random samples from the given list.
  • Store it in a variable.
  • Print the random samples from the given list of the size given.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np  
# Give the list as static input and store it in a variable.
gvn_lst = [4, 3, 1, 9, 6]
# Pass the above given list, size(row_size, col_size) and replace as "True" as arguments to the 
# random.choice() function to get random samples from the given list.
# Store it in a variable.
rslt = np.random.choice(gvn_lst, (2,2), True)
# Print the random samples from the given list of size given.
print(rslt)

Output:

[[1 4]
 [9 9]]

Example3

We can give probability to each entry in the input array or sequence using the p parameter.

Approach:

  • Import numpy module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Give the list of probabilities as static input and store it in another variable.
  • Pass the above-given list, size(row_size, col_size), replace as “True” and probabilities list as arguments to the random.choice() function to get random samples from the given list.
  • Store it in a variable.
  • Print the random samples from the given list of the size given.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np  
# Give the list as static input and store it in a variable.
gvn_lst = [4, 9, 10, 15, 18, 19]
# Give the list of probabilities as static input and store it in another variable.
probity_lst = [0.2, 0.3, 0.1, 0.2 , 0.1, 0.1]
# Pass the above given list, size(row_size, col_size), replace as "True"
# and probabilities list as arguments to the random.choice() function
# to get random samples from the given list.
# Store it in a variable.
rslt = np.random.choice(gvn_lst, (3,3), True, probity_lst)
# Print the random samples from the given list of size given.
print(rslt)

Output:

[[ 9 9 4]
 [ 4 18 9]
 [10 19 15]]

Raw string python – Python Raw Strings With Examples

Raw Strings With Examples

Raw string python: A raw string in Python is formed by prefixing a string literal with ‘r’ or ‘R’. A backslash (\) is treated as a literal character in Python raw string. This is useful when we want to have a string with a backslash in it but don’t want it to be interpreted as an escape character.

This feature allows us to pass string literals that cannot be decoded normally, such as the sequence “\x.”

For example – r”Good morning\tBtechgeeks”

Raw Strings in Python:

# Give the string as static input and store it in a variable.
gvn_str = "Hello this\t is\nbtechgeeks"
# Print the given string
print(gvn_str)

Output:

Hello this	 is
btechgeeks

Because gvn_str is a regular string literal, the sequences “\t” and “\n” will be considered as escape characters.

As a result, when we print the string, the corresponding escape sequences (tab-space and new-line) are generated.

# Give the raw string as static input and store it in a variable.
# Both backslashes(\t,\n) will NOT be escaped in this case.
gvn_rawstr = r"Hello this\t is\nbtechgeeks"
# Print the given string
print(gvn_rawstr)

Output:

Hello this\t is\nbtechgeeks

Python raw string: Because both backslashes are not considered as escape characters in this case, Python will NOT display a tab-space and a new line.

It will just print “t” and “n” literally.
As you can see, the output is identical to the input because no characters are escaped.

Let’s have a look at another situation where raw strings can use, especially when Python strings don’t function.

See the string literal with the sequence “x” below:

# Give the string as static input and store it in a variable.
gvn_str =  "Good morning\xBtechgeeks"
# Print the given string
print(gvn_str)

Output:

 File "/home/jdoodle.py", line 2
gvn_str = "Good morning\xBtechgeeks"
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 12-14: 
truncated \xXX escape

Explanation:

The sequence "x" cannot be decoded using normal Unicode encoding in this case.

This means we can’t even use it as a string literal. What are our options now?

Here’s where the raw string comes in helpful.

By treating the value as a raw string literal, we can easily pass it into a variable.

# Give the string as static input and store it in a variable.
gvn_str =  r"Good morning\xBtechgeeks"
# Print the given string
print(gvn_str)

Output:

Good morning\xBtechgeeks

There is no longer any issue, and we may give this raw string literal as a normal object.

Note: If you print a Python raw string to the terminal, you may receive anything like below in some cases.

Example:

>>> gvn_str =  r"Good morning\xBtechgeeks"

Output:

 'Good morning\\xBtechgeeks'

The double backslash indicates that this is a regular Python string with the backslash escaped. Because the print() method outputs normal string literals, the raw string gets converted to one such string.

Python print bits Python Program to Count Set Bits in a Number

Python Program to Count Set Bits in a Number

Python print bits: Given a number ,the task is to count the set bits of the given number in its binary representation.

Examples:

Example1:

Input:

given number =235

Output:

The total number of set bits in the given number  235  : 
6

Example2:

Input:

given number =8

Output:

The total number of set bits in the given number  8  : 
1

Example3:

Input:

given number =375

Output:

The total number of set bits in the given number  375  : 
7

Program to Count Set Bits in a Number in Python

There are several ways to count set bits in the binary representation of the given number some of them are:

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

Method #1: By checking bit by bit from end using modulus operator

A simple method is to take each bit into consideration in a number (set or unset) and hold an counter to track the set bits.

Approach:

  • Set the variable say count to 0 to count the total number of set bits.
  • We utilize the while loop.
  • We’ll keep going till the number is bigger than zero (Condition of while statement)
  • Using the % operator, we will determine whether the last check bit is set or not.
  • If the check bit is 1, it indicates that the bit is set, and we increment the count.
  • Divide the given number by 2.
  • Print the count.

Below is the implementation:

def countSetBit(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using % operator
            checkbit = numb % 2
            # checking if the check bit is 1 or not
            # if the check bit is 1 then increment the setbitcount
            if(checkbit == 1):
                setbitcount = setbitcount+1
            # divide the number by 2
            numb = numb//2
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

Method #2: By checking bit by bit from end using & operator

A simple method is to take each bit into consideration in a number (set or unset) and hold an counter to track the set bits.

Approach:

  • Set the variable say count to 0 to count the total number of set bits.
  • We utilize the while loop.
  • We’ll keep going till the number is bigger than zero (Condition of while statement)
  • Using the & operator, we will determine whether the last check bit is set or not.
  • If the check bit is 1, it indicates that the bit is set, and we increment the count.
  • Divide the given number by 2.
  • Print the count.

We use n&1 to check whether it is set bit or not.

Below is the implementation:

def countSetBit(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using & operator
            # checking if the check bit is 1 or not
            # if the check bit is 1 then increment the setbitcount
            if(numb & 1):
                setbitcount = setbitcount+1
            # divide the number by 2
            numb = numb//2
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

Method #3: By converting into binary using bin() and using count() function to count set bits

Approach:

  • First we convert the given number into binary using bin() function.
  • Then we count total number of ‘1’s in the binary string using count() function
  • Print the count

Below is the implementation:

def countSetBit(numb):
    # converting given number to binary reepresentatioon using bin()
    binNum = bin(numb)
    # we count total number of '1's in the binary string using count() function
    setbitcount = binNum.count('1')
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

Method #4: By converting into binary using bin() and using sum() function to count set bits

Approach:

  • First we convert the given number into binary using bin() function.
  • We slice from 2 to end of the binary string using slicing (to remove 0b characters from binary string)
  • Convert every character of binary string to integer using map and then convert it to list
  • Then we count total number of ‘1’s in the binary string list using sum() function(because the binary string contains only 0 and 1)
  • Print the count

Below is the implementation:

def countSetBit(numb):
    # converting given number to binary reepresentatioon using bin()
    binNum = bin(numb)
    # We will slice from 2 index to last index of the result returned by binary string
    binNum = binNum[2:]
    # Convert every character of binary string to integer using map
    # and then convert it to list
    binList = list(map(int, binNum))
    # we count total number of '1's in the binary string using sum() function
    setbitcount = sum(binList)
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

Related Programs:

Python add digits of a number – Python Program to Find the Sum of Digits of a Number at Even and Odd places

Program to Find the Sum of Digits of a Number at Even and Odd places

Python add digits of a number: In the previous article, we have discussed Python Program to Check if Product of Digits of a Number at Even and Odd places is Equal
The task is to find the sum of digits of a number at even and odd places given a number N.

Examples:

Example1:

Input:

Given Number = 123456

Output:

The sum of all digits at even places in a given number{ 123456 } = 9
The sum of all digits at odd places in a given number { 123456 } = 12

Example2:

Input:

Given Number = 1787725620

Output:

The sum of all digits at even places in a given number{ 1787725620 } = 23
The sum of all digits at odd places in a given number { 1787725620 } = 22

Program to Count the Number of Odd and Even Digits of a Number at Even and Odd places in Python

Below are the ways to find the sum of digits of a number at even and odd places given a number N.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number to a string using the str() function and store it in another variable.
  • Create a list of digits say “digtslst” using map(),list(),int functions.
  • Store it in another variable.
  • Take a variable say “evn_sum” and initialize it with 0.
  • Take another variable say “od_sum” and initialize it with 0.
  • Loop in the above list of digits until the length of the “digtslst” using the for loop.
  • Check if the iterator value is even or not using the if conditional statement.
  • If the statement is true, then add the iterator value of “digtslst” to the “evn_sum” and store it in the same variable evn_sum.
  • If the statement is false, then add the iterator value of “digtslst” to the “od_sum” and store it in the same variable od_sum.
  • Print “evn_sum to get the sum of even digits in a given number.
  • Print “od_sum to get the sum of odd digits in a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 1787725620
# Convert the given number to string using the str() function.
stringnum = str(numb)
# Create a list of digits say "digtslst" using map(),list(),int functions.
digtslst = list(map(int, stringnum))
# Take a variable say "evn_sum" and initialize it with 0.
evn_sum = 0
# Take another variable say "od_sum" and initialize it with 0.
od_sum = 0
# Loop in the above list of digits until the length of the "digtslst" using the for loop.
for itr in range(len(digtslst)):
    # Check if the iterator value is even or not using
    # the if conditional statement.
    if(itr % 2 == 0):
     # If the statement is true, then add the iterator value of "digtslst" to the "evn_sum"
        # and store it in the same variable evn_sum.
        evn_sum += digtslst[itr]
    else:
        # If the statement is false, then add the iterator value of "digtslst" to the "od_sum"
        # and store it in the same variable od_sum.
        od_sum += digtslst[itr]
# Print "evn_sum" to get the sum of all digits at even places in a given number.
print(
    "The sum of all digits at even places in a given number{", numb, "} =", evn_sum)
# Print "od_sum" to get the sum of all digits at odd places in a given number.
print(
    "The sum of all digits at odd places in a given number {", numb, "} =", od_sum)

Output:

The sum of all digits at even places in a given number{ 1787725620 } = 23
The sum of all digits at odd places in a given number { 1787725620 } = 22

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Convert the given number to a string using the str() function and store it in another variable.
  • Create a list of digits say “digtslst” using map(),list(),int functions.
  • Store it in another variable.
  • Take a variable say “evn_sum” and initialize it with 0.
  • Take another variable say “od_sum” and initialize it with 0.
  • Loop in the above list of digits until the length of the “digtslst” using the for loop.
  • Check if the iterator value is even or not using the if conditional statement.
  • If the statement is true, then add the iterator value of “digtslst” to the “evn_sum” and store it in the same variable evn_sum.
  • If the statement is false, then add the iterator value of “digtslst” to the “od_sum” and store it in the same variable od_sum.
  • Print “evn_sum to get the sum of even digits in a given number.
  • Print “od_sum to get the sum of odd digits in a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
numb = int(input("Enter some random variable = "))
# Convert the given number to string using the str() function.
stringnum = str(numb)
# Create a list of digits say "digtslst" using map(),list(),int functions.
digtslst = list(map(int, stringnum))
# Take a variable say "evn_sum" and initialize it with 0.
evn_sum = 0
# Take another variable say "od_sum" and initialize it with 0.
od_sum = 0
# Loop in the above list of digits until the length of the "digtslst" using the for loop.
for itr in range(len(digtslst)):
    # Check if the iterator value is even or not using
    # the if conditional statement.
    if(itr % 2 == 0):
     # If the statement is true, then add the iterator value of "digtslst" to the "evn_sum"
        # and store it in the same variable evn_sum.
        evn_sum += digtslst[itr]
    else:
        # If the statement is false, then add the iterator value of "digtslst" to the "od_sum"
        # and store it in the same variable od_sum.
        od_sum += digtslst[itr]
# Print "evn_sum" to get the sum of all digits at even places in a given number.
print(
    "The sum of all digits at even places in a given number{", numb, "} =", evn_sum)
# Print "od_sum" to get the sum of all digits at odd places in a given number.
print(
    "The sum of all digits at odd places in a given number {", numb, "} =", od_sum)

Output:

Enter some random variable = 123456
The sum of all digits at even places in a given number{ 123456 } = 9
The sum of all digits at odd places in a given number { 123456 } = 12

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

Parameterization in selenium – How To Do Parameterization In Pytest With Selenium?

How to Do Parameterization In Pytest With Selenium?

Selenium Python – Concept of Parameterization

Parameterization in selenium: Sometimes, we come across situations where we need to execute the same test case, but with every execution, we need to use a different data set. Or sometimes, we need to create test data prior to our test suite execution. To resolve all these requirements, we should be familiar with the concept of parameterization.

Structure

  • Why do we need parameterization
  • What is parameterization
  • Creation of test data file
  • Parameterizing and login logout scenario

Objective

In this chapter, we will learn how we can use a text file to pass data to our tests and run it as many times as rows are available in our file. With this, we will understand the concept of parameterization.

Test data file

Test cases generally need test data for execution. When we write scripts to automate the test, it could be possible that we have hard-coded the test data within the test scripts. The drawback of this approach is if our test data needs to be changed for a test execution cycle, we will need to make changes at the test script level, thus making it prone to errors. So a good test script is when test data is kept outside the code.

To achieve the same, we need to parameterize our tests. In this, we replace the hard code values in the test with variables. At the time of execution, these variables are replaced by values that are picked from external data sources. These data sources could be text files, excel sheets, databases, JSON, XML, and others.

Parameterization and login logout scenario

Selenium doesn’t provide any provision to parameterize the tests. We write the code to parameterize the test using the programming language. In this chapter we will see how we can parameterize our test using a CSV file, and an excel file. The scenario we are going to pick is the login logout scenario, and we will parameterize it using two datasets—the first dataset will be for valid user and password combinations. And the second dataset will be for a bad username and password combination.

The data to be picked for the test is available in a file called login. CSV, which is kept in the dataset folder in the project. Refer to the following screenshot:

Selenium Python - Concept of Parameterization chapter 8 img 1

The dataset file login. CSV has the following data:

bpb@bpb.com, bpb@123
abc@demo.com,demo123

In a CSV file, the data is separated by a comma. The test script provided below reads the data using Python file handling commands and splits it based on a comma. It then passes these values for username and password in the script. The following test iterates twice, which is equal to the number of rows in this file:

from selenium import webdriver
import unitest

class Login(unitest.TestCase):
      def setup(self):
          self.driver = webdriver.chrome(executable_path="D:\Eclipse\BPB\seleniumpython\seleniumpython\drivers\chromedriver.exe")
          self.driver.implicitly_wait(30) 
          self.base_url="http://practice.bpbonline.com/catalog/index.php"

dex test_login(self):
    driver=self.driver
    driver.get(self.base_url)
    file = open("D:\Eclipse\BPB\seleniumpython\seleniumpython\datasets\login.csv", "r")
    for line in file:
         driver.find_element_by_link_text("My Account").click( )
         data=line.spilt(",")
         print(data)
         driver.find_element_by_name("email_address").send_keys(data[0])
         driver.find_element_by_name("password").send_keys(data[1].strip())
         driver.find_element_by_id("tab1").click( )
         if(driver.page_source.find("My Account Information")l=-1):
            driver.find_element_by_link_text("log off").click( )
            driver.find_element_by_link_text("continue").click( )
            print("valid user credentail")
   else:
       print("Bad user credentail")
  file.close( )

def tearDown(self):
    self.driver.quit( )

if_name_=="_main_":
    unitest.main( )

In the preceding program, we have written the scenario of login logout, but it is wrapped around a while loop. This while loop is basically reading file contents, until the end of the file is reached. So the entire script will execute as many times as the number of rows in the file.

As we execute the test, we will see that it passes for the first data set picked from the file, as it is a combination of a valid username and password. But for the second dataset, the test reports a failure. The preceding test will execute for as many rows as available in our login.csv dataset file.

Conclusion

In this chapter we have learned how to use test data for our tests, and the importance of keeping test data separate from the actual tests. We also saw how we can read data from a CSV file or a text-based file, and pass them to our test code.

In our next chapter, we will learn how to handle different types of web elements.

Related Articles:

Remainder function python – Python NumPy remainder() Function

Python NumPy remainder() Function

NumPy remainder() Function:

Remainder function python: In numpy, there is also a function called numpy.remainder() that can be used to do mathematical operations. It returns the element-wise division remainder between two arrays arr1 and arr2, i.e. arr1 percent arr2. When arr2 is 0 and both arr1 and arr2 are (arrays of) integers, it returns 0.

Syntax:

numpy.remainder(l1, l2, out=None)

Parameters:

l1 and l2: (Required)

These are required arguments. These are the arrays that have to be divided, here l1 as dividend and l2 as the divisor.

They must be broadcastable to a common shape if l1.shape!= l2.shape.

out:

This is optional. It is the location where the result will be saved. It must have a shape that the inputs broadcast to if it is provided. If None or not given, a newly allocated array is returned.

Return Value:

The element-by-element remainder of dividing l1 and l2 is returned(l1%l2).

NumPy remainder() Function in Python

Example

Approach:

  • Import NumPy module using the import keyword.
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Create some sample arrays of different shapes to test the remainder() function.
  • Pass the first array and some random number to remainder() function of NumPy module and print the result.
  • Here it divides each element of the array1 with the given random value say 9 and gives the remainder.
  • Pass the first array and second array to remainder() function of NumPy module and print the result.
  • Here it divides second array elements for the first array element and gives the remainder
  • Similarly, test it with other arrays of different shapes.
  • The Exit of the Program.

Below is the implementation:

# Import NumPy module using the import keyword.
import numpy as np
# Pass some random list as an argument to the array() function to create an array.
# Store it in a variable.
arry1 = np.array([[32,64],[95,128],[150,180]])
# Create some sample arrays of different shapes to test the remainder() function.
arry2 = np.array([[10,20]])
arry3 = np.array([[100],[200],[300]])
arry4 = np.array([[55,65],[75,85],[95,105]])
# Pass the first array and some random number to remainder() function of NumPy module and print the result.
# Here it divides each element of the array1 with the given random value say 9 and gives the remainder.
print('Getting remainder value by dividing first array with 9: ')
print(np.remainder(arry1, 9))
# Pass the first array and second array to remainder() function of NumPy module and print the result.
# Here it divides second array elements for the first array element and gives the remainder
print('Getting remainder value by dividing first array with second array: ')
print(np.remainder(arry1, arry2))
# Similarly, test it with other arrays of different shapes.
print('Getting remainder value by dividing first array with third array: ')
print(np.remainder(arry1, arry3))
print('Getting remainder value by dividing first array with fourth array: ')
print(np.remainder(arry1, arry4))

Output:

Getting remainder value by dividing first array with 9: 
[[5 1]
 [5 2]
 [6 0]]
Getting remainder value by dividing first array with second array: 
[[2 4]
 [5 8]
 [0 0]]
Getting remainder value by dividing first array with third array: 
[[ 32 64]
 [ 95 128]
 [150 180]]
Getting remainder value by dividing first array with fourth array: 
[[32 64]
 [20 43]
 [55 75]]

Isoformat python – Python Pandas Timestamp.isoformat() Function

Python Pandas Timestamp.isoformat() Function

What is Timestamp?

Isoformat python: A timestamp is a sequence of characters or encoded information that identifies when a particular event occurred, typically providing the date and time of day, and can be accurate to a fraction of a second.

The timestamp method is used for a variety of synchronization purposes, including assigning a sequence order to a multievent transaction so that the transaction can be canceled if a fault occurs. A timestamp can also be used to record time in reference to a specific starting point in time.

Uses of Timestamp:

Timestamps are used to maintain track of information stored online or on a computer. A timestamp indicates when data was generated, shared, modified, or removed.

Here are some examples of how timestamps can be used:

  • A timestamp in a computer file indicates when the file was last modified.
  • Photographs with digital cameras have timestamps that show the date and time of day they were taken.
  • The date and time of the post are included in social media posts.
  • Timestamps are used in online chat and instant messages to record the date and time that a message was delivered, received, or viewed.
  • Timestamps are used in blockchain blocks to confirm the validity of transactions, such as those involving cryptocurrencies.
  • To secure the integrity and quality of data, data management relies on timestamps.
  • Timestamps are used in digital contracts and digital signatures to signify when a document was signed.

Pandas Timestamp.isoformat() Function:

The Timestamp.isoformat() function of the pandas module converts the specified Timestamp object into the ISO format.

Syntax:

Timestamp.isoformat()

Parameters: It has no arguments

Return Value:

The date-time as a string(ISO format) is returned by the Timestamp.isoformat() function of the pandas module.

Pandas Timestamp.isoformat() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random year, month, day, hour, second, tz =’Asia/Kolkata’ (Timezone) as the arguments to the Timestamp() function of the pandas module to get the Timestamp object
  • Print the above-obtained Timestamp object
  • Apply isoformat() function on the above Timestamp object to convert the given timestamp object to ISO format.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
  
# Pass some random year, month, day, hour, second, tz ='Asia/Kolkata'
# (Timezone) as the arguments to the Timestamp() function of the
# pandas module to get the Timestamp object
time_stamp_obj = pd.Timestamp(year = 2015,  month = 6, day = 26, hour = 7, 
                            second = 35, tz = 'Asia/Kolkata')
  
# Print the above obtained Timestamp object
print("The above obtained Timestamp object:", time_stamp_obj)
# Apply isoformat() function on the above Timestamp object to 
# convert the given timestamp object to ISO format
print("Converting the given timestamp object to ISO format:")
time_stamp_obj.isoformat()

Output:

The above obtained Timestamp object: 2015-06-26 07:00:35+05:30
Converting the given timestamp object to ISO format:
2015-06-26T07:00:35+05:30

Example2

Approach:

  • Import pandas module using the import keyword.
  • Pass some random year, month, day, hour, second, tz =’US/Central'(Timezone) as the arguments to the Timestamp() function of the pandas module to get the Timestamp object
  • Print the above-obtained Timestamp object
  • Apply isoformat() function on the above Timestamp object to convert the given timestamp object to ISO format.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
  
# Pass some random year, month, day, hour, second, tz ='US/Central' 
# (Timezone) as the arguments to the Timestamp() function of the
# pandas module to get the Timestamp object
time_stamp_obj = pd.Timestamp(year = 2020,  month = 8, day = 30, hour = 10, 
                            second = 45, tz = 'US/Central' )
  
# Print the above obtained Timestamp object
print("The above obtained Timestamp object:", time_stamp_obj)
# Apply isoformat() function on the above Timestamp object to 
# convert the given timestamp object to ISO format
print("Converting the given timestamp object to ISO format:")
time_stamp_obj.isoformat()

Output:

The above obtained Timestamp object: 2020-08-30 10:00:45-05:00
Converting the given timestamp object to ISO format:
2020-08-30T10:00:45-05:00

Sort by second element python – Python Program to Sort the List According to the Second Element in Sublist

Program to Sort the List According to the Second Element in Sublist

Sort by second element python: 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.

Given list of lists which contain two elements in every sub list , the task is to sort the lists according to the second element in sub list.

Examples:

Example1:

Input:

given nested list =[['hello', 11], ['this', 1], ['is', 23], ['btechgeeks', 19], ['online', 39], ['platform', 7], ['for', 29]]

Output:

printing the sorted nested list before sorting :
[['hello', 11], ['this', 1], ['is', 23], ['btechgeeks', 19], ['online', 39], ['platform', 7], ['for', 29]]
printing the sorted nested list after sorting :
[['this', 1], ['platform', 7], ['hello', 11], ['btechgeeks', 19], ['is', 23], ['for', 29], ['online', 39]]

Example2:

Input:

[['hello', 46], ['this', 31], ['morning', 29], ['is', 26], ['btechGeeks', 19], ['online', 33]]

Output:

printing the sorted nested list before sorting :
[['hello', 46], ['this', 31], ['morning', 29], ['is', 26], ['btechGeeks', 19], ['online', 33]]
printing the sorted nested list after sorting :
[['btechGeeks', 19], ['is', 26], ['morning', 29], ['this', 31], ['online', 33], ['hello', 46]]

Example3:

Input:

[['sky', 12], ['is', 39], ['blue', 5]]

Output:

printing the sorted nested list before sorting :
[['sky', 12], ['is', 39], ['blue', 5]]
printing the sorted nested list after sorting :
[['blue', 5], ['sky', 12], ['is', 39]]

Program to Sort the List According to the Second Element in Sub list in Python

Python sublist: Below are the ways to sort the given list of lists according to the second element in sub list in python some of them are:

Method #1: Using nested loops and temporary variable(Static Input)

Approach:

  • Take in a list that contains sublists as static input.
  • Using two for loops, sort the sublists using bubble sort based on the second value of the sublist.
  • If the second element of the first sublist is greater than the second element of the second sublist, the complete sublist should be exchanged/swapped.
  • The sorted list should be printed.
  • Exit of program.

Below is the implementation:

# Take in a list that contains sublists as static input.
nestedList = [['hello', 46], ['this', 31], ['morning', 29],
              ['is', 26], ['btechGeeks', 19], ['online', 33]]
# printing the sorted nested list before sorting
print('printing the sorted nested list before sorting :')
print(nestedList)
# Using two for loops, sort the sublists using bubble
# sort based on the second value of the sublist.
for m in range(len(nestedList)):
    for n in range(len(nestedList)-m-1):
      # If the second element of the first sublist is greater than the second element of the second sublist,
      # the complete sublist should be exchanged/swapped using temporary variable
        if(nestedList[n][1] > nestedList[n+1][1]):
            tempo = nestedList[n]
            nestedList[n] = nestedList[n+1]
            nestedList[n+1] = tempo
# printing the sorted nested list after sorting
print('printing the sorted nested list after sorting :')
print(nestedList)

Output:

printing the sorted nested list before sorting :
[['hello', 46], ['this', 31], ['morning', 29], ['is', 26], ['btechGeeks', 19], ['online', 33]]
printing the sorted nested list after sorting :
[['btechGeeks', 19], ['is', 26], ['morning', 29], ['this', 31], ['online', 33], ['hello', 46]]

Method #2: Using nested loops and temporary variable(User Input)

Approach:

  • Take a empty list.
  • Scan the number of elements /number of sublists as user input using int(input()) function.
  • Loop from 1 to given number of elements times using for loop.
  • Scan the list elements using input() and int(input()) functions and append to the empty list using append() function.
  • Using two for loops, sort the sublists using bubble sort based on the second value of the sublist.
  • If the second element of the first sublist is greater than the second element of the second sublist, the complete sublist should be exchanged/swapped.
  • The sorted list should be printed.
  • Exit of program.

Below is the implementation:

# Take a empty list.
nestedList = []
# Scan the number of elements /number of sublists as user input using int(input()) function.
totalsublists = int(input('Enter some random number of sublists ='))
# Loop from 1 to given number of elements times using for loop.
for r in range(totalsublists):
    # Scan the list elements using input() and int(input()) functions and append
    # to the empty list using append() function.
    firsteleme = input('Enter some random first element =')
    secondeleme = int(input('Enter some random second element ='))
    nestedList.append([firsteleme, secondeleme])

# printing the sorted nested list before sorting
print('printing the sorted nested list before sorting :')
print(nestedList)
# Using two for loops, sort the sublists using bubble
# sort based on the second value of the sublist.
for m in range(len(nestedList)):
    for n in range(len(nestedList)-m-1):
      # If the second element of the first sublist is greater than the second element of the second sublist,
      # the complete sublist should be exchanged/swapped using temporary variable
        if(nestedList[n][1] > nestedList[n+1][1]):
            tempo = nestedList[n]
            nestedList[n] = nestedList[n+1]
            nestedList[n+1] = tempo
# printing the sorted nested list after sorting
print('printing the sorted nested list after sorting :')
print(nestedList)

Output:

Enter some random number of sublists =7
Enter some random first element =hello
Enter some random second element =11
Enter some random first element =this
Enter some random second element =1
Enter some random first element =is
Enter some random second element =23
Enter some random first element =btechgeeks
Enter some random second element =19
Enter some random first element =online
Enter some random second element =39
Enter some random first element =platform
Enter some random second element =7
Enter some random first element =for
Enter some random second element =29
printing the sorted nested list before sorting :
[['hello', 11], ['this', 1], ['is', 23], ['btechgeeks', 19], ['online', 39], ['platform', 7], ['for', 29]]
printing the sorted nested list after sorting :
[['this', 1], ['platform', 7], ['hello', 11], ['btechgeeks', 19], ['is', 23], ['for', 29], ['online', 39]]

Explanation:

  • The user must enter a list with numerous sublists.
  • Scan the list elements using input() and int(input()) functions and append to the empty list using append() function.
  • The list is then sorted using bubble sort based on the second member in the sublist.
  • The entire sublist is switched if the second element of the first sublist is bigger than the second element of the second sublist.
  • This step is repeated until the full list has been sorted.
  • After that, the sorted list is printed.

Related Programs: