Found 10784 Articles for Python

How to Calculate the Area of a Triangle using Python?

Lakshmi Srinivas
Updated on 17-Jun-2020 12:42:15

1K+ Views

Calculating the area of a triangle is a formula that you can easily implement in python. If you have the base and height of the triangle, you can use the following code to get the area of the triangle,def get_area(base, height):    return 0.5 * base * height print(get_area(10, 15))This will give the output:75If you have the sides of the triangle, you can use herons formula to get the area. For example,def get_area(a, b, c):    s = (a+b+c)/2    return (s*(s-a)*(s-b)*(s-c)) ** 0.5 print(get_area(10, 15, 10))This will give the output:49.607837082461074

How can we do the basic print formatting for Python numbers?

Ankith Reddy
Updated on 17-Jun-2020 12:39:20

147 Views

You can format a floating number to the fixed width in Python using the format function on the string. For example, nums = [0.555555555555, 1, 12.0542184, 5589.6654753] for x in nums:    print("{:10.4f}".format(x))This will give the output0.5556 1.0000 12.0542 5589.6655Using the same function, you can also format integersnums = [5, 20, 500] for x in nums:    print("{:d}".format(x))This will give the output:5 20 500You can use it to provide padding as well, by specifying the number before dnums = [5, 20, 500] for x in nums:    print("{:4d}".format(x))This will give the output5 20 500The https://pyformat.info/ website is a great resource ... Read More

How to generate statistical graphs using Python?

Ankitha Reddy
Updated on 30-Jul-2019 22:30:22

302 Views

Python has an amazing graph plotting library called matplotlib. It is the most popular graphing and data visualization module for Python. You can start plotting graphs using 3 lines! For example, from matplotlib import pyplot as plt # Plot to canvas plt.plot([1, 2, 3], [4, 5, 1]) #Showing what we plotted plt.show() This will create a simple graph with coordinates (1, 4), (2, 5) and (3, 1). You can Assign labels to the axes using the xlabel and ylabel functions. For example, plt.ylabel('Y axis') plt.xlabel('X axis') And also provide a title using the title ... Read More

How to generate a random 128 bit strings using Python?

Abhinaya
Updated on 05-Mar-2020 10:21:59

2K+ Views

You can generate these just random 128-bit strings using the random module's getrandbits function that accepts a number of bits as an argument. exampleimport random hash = random.getrandbits(128) print(hex(hash))OutputThis will give the output −0xa3fa6d97f4807e145b37451fc344e58c

How to generate all permutations of a list in Python?

Lakshmi Srinivas
Updated on 05-Mar-2020 10:20:55

346 Views

You can use the itertools package's permutations method to find all permutations of a list in Python. You can use it as follows −Exampleimport itertools perms = list(itertools.permutations([1, 2, 3])) print(perms)OutputThis will give the output −[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

How to find time difference using Python?

Ankith Reddy
Updated on 05-Mar-2020 10:19:02

1K+ Views

It is very easy to do date and time maths in Python using time delta objects. Whenever you want to add or subtract to a date/time, use a DateTime.datetime(), then add or subtract date time.time delta() instances. A time delta object represents a duration, the difference between two dates or times. The time delta constructor has the following function signatureDateTime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])¶Note: All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here https://docs.python.org/2/library/datetime.html#timedelta-objectsExampleAn example of using the time ... Read More

How to generate JSON output using Python?

karthikeya Boyini
Updated on 05-Mar-2020 10:16:33

2K+ Views

The json module in python allows you to dump a dict to json format directly. To use it,Exampleimport json my_dict = {    'foo': 42,    'bar': {       'baz': "Hello",       'poo': 124.2    } } my_json = json.dumps(my_dict) print(my_json)OutputThis will give the output −'{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'You can also pass indent argument to prettyprint the json. exampleimport json my_dict = {    'foo': 42,    'bar': {       'baz': "Hello",       'poo': 124.2    } } my_json = json.dumps(my_dict, indent=2) print(my_json)OutputThis will give the output −{    "foo": 42,    "bar":    {       "baz": "Hello",       "poo": 124.2    } }

How to generate XML using Python?

Abhinaya
Updated on 05-Mar-2020 10:14:32

1K+ Views

To generate XML from a python dictionary, you need to install the dicttoxml package. You can install it using −$ pip install dicttoxmlOnce installed, you can use the dicttoxml method to create the xml. examplea = {    'foo': 45,    'bar': {       'baz': "Hello"    } } xml = dicttoxml.dicttoxml(a) print(xml)OutputThis will give the output −b'45Hello'You can also prettyprint this output using the toprettyxml method. examplefrom xml.dom.minidom import parseString a = {    'foo': 45,    'bar': {       'baz': "Hello"    } } xml = dicttoxml.dicttoxml(a) dom = parseString(xml) print(dom.toprettyxml())OutputThis will give the output −    45           Hello    

How to generate a 24bit hash using Python?

George John
Updated on 05-Mar-2020 10:11:26

383 Views

A random 24 bit hash is just random 24 bits. You can generate these just using the random module. exampleimport random hash = random.getrandbits(24) print(hex(hash))OutputThis will give the output0x94fbee

How to generate sequences in Python?

Samual Sam
Updated on 05-Mar-2020 10:09:37

2K+ Views

List comprehensions in python are useful for such tasks. These are very powerful expressions that you can use to generate sequences in a very concise and efficient manner. For example, if you want first 100 integers from 0, you can use −Examplea = [i for i in range(100)] print(a)OutputThis will give the output −[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]ExampleWant the squares for first 10 even numbers? You can get it using −a = [i * i for i in range(20) if i % 2 == 0] print(a)OutputThis will give the output −[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]These expressions can get much more powerful once you know how to use them.

Advertisements