Found 34487 Articles for Programming

How to generate all permutations of a list in Python?

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

347 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.

How to generate prime twins using Python?

Govinda Sai
Updated on 05-Mar-2020 10:07:04

6K+ Views

Twin primes are pairs of primes which differ by two. The first twin primes are {3,5}, {5,7}, {11,13} and {17,19}. You can generate prime twins in python by running a for loop and checking for primality of the numbers as you do so. exampledef is_prime(n):    for i in range(2, n):       if n % i == 0:          return False    return True def generate_twins(start, end):    for i in range(start, end):       j = i + 2       if(is_prime(i) and is_prime(j)):          print("{:d} and {:d}".format(i, j)) generate_twins(2, 100)OutputThis will give the output −3 and 5 5 and 7 11 and 13 17 and 19 29 and 31 41 and 43 59 and 61 71 and 73

How to use multiple for and while loops together in Python?

Ankith Reddy
Updated on 17-Jun-2020 12:36:21

257 Views

You can create nested loops in python fairly easily. You can even nest a for loop inside a while loop or the other way around. For example,for i in range(5):    j = i    while j != 0:       print(j, end=', ')       j -= 1    print("")This will give the output1, 2, 1, 3, 2, 1, 4, 3, 2, 1,You can take this nesting to as many levels as you like.

How to generate a sorted list in Python?

Lakshmi Srinivas
Updated on 17-Jun-2020 12:35:01

326 Views

The sort method on lists in python uses the given class's gt and lt operators to compare. Most built in classes already has these operators implemented so it automatically gives you sorted list. You can use it as follows:words = ["Hello", "World", "Foo", "Bar", "Nope"] numbers = [100, 12, 52, 354, 25] words.sort() numbers.sort() print(words) print(numbers)This will give the output:['Bar', 'Foo', 'Hello', 'Nope', 'World'] [12, 25, 52, 100, 354]If you don't want the input list to be sorted in place, you can use the sorted function to do so. For example, words = ["Hello", "World", "Foo", "Bar", "Nope"] sorted_words ... Read More

How to use single statement suite with Loops in Python?

karthikeya Boyini
Updated on 17-Jun-2020 12:29:42

239 Views

Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header. Here are the syntax and example of a one-line for loop:for i in range(5): print(i)This will give the output:0 1 2 3 4

Advertisements