Categories
Python Answers

How to create a Caesar cipher function in Python?

Sometimes, we want to create a Caesar cipher function in Python.

In this article, we’ll look at how to create a Caesar cipher function in Python.

How to create a Caesar cipher function in Python?

To create a Caesar cipher function in Python, we can create our own function to map the string characters to the new characters.

For instance, we write:

import string


def caesar(plaintext, shift):
    alphabet = string.ascii_lowercase
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    table = str.maketrans(alphabet, shifted_alphabet)
    return plaintext.translate(table)


print(caesar('foobar', 2))

to define the caesar function that takes the plaintext to encrypt and the shift to specify the number of positions to shift each character in the character set.

We get all the ASCII alphabet characters with string.ascii_lowercase.

Then we shift the alphabet with alphabet[shift:] + alphabet[:shift].

Next, we map each character to the new characters with str.maketrans(alphabet, shifted_alphabet).

And then we return the encrypted string with plaintext.translate(table).

Therefore, the print output should be 'hqqdct' since we shifted each character 3 positions to the right in the alphabet table.

Conclusion

To create a Caesar cipher function in Python, we can create our own function to map the string characters to the new characters.

Categories
Python Answers

How to rewrite multiple lines in the console with Python?

Sometimes, we want to rewrite multiple lines in the console with Python.

In this article, we’ll look at how to rewrite multiple lines in the console with Python.

How to rewrite multiple lines in the console with Python?

To rewrite multiple lines in the console with Python, we can use sys.stdout.write to move up the cursor to delete a line.

For instance, we write:

import sys
import time
from collections import deque

queue = deque([], 3)
for t in range(20):
    time.sleep(0.5)
    s = "update %d" % t
    for _ in range(len(queue)):
        sys.stdout.write("\x1b[1A\x1b[2K")
    queue.append(s)
    for i in range(len(queue)):
        sys.stdout.write(queue[i] + "\n")

We have a for loop and we loop from 0 to 19.

In the loop, we call time.sleep to pause for 0.5 seconds.

Then we loop through from 0 to the length of the queue minus 1 with another for loop and erase the previous line by writing:

sys.stdout.write("\x1b[1A\x1b[2K")

Next, we call queue.append to append the s string.

And then we call sys.stdout.write(queue[i] + "\n") to update the text again.

Conclusion

To rewrite multiple lines in the console with Python, we can use sys.stdout.write to move up the cursor to delete a line.

Categories
Python Answers

How to rank items in an array using Python NumPy, without sorting array twice?

Sometimes, we want to rank items in an array using Python NumPy, without sorting array twice.

In this article, we’ll look at how to rank items in an array using Python NumPy, without sorting array twice.

How to rank items in an array using Python NumPy, without sorting array twice?

To rank items in an array using Python NumPy, without sorting array twice, we can use the argsort method.

For instance, we write:

import numpy

array = numpy.array([4, 2, 7, 1])
order = array.argsort()
ranks = order.argsort()
print(order)
print(ranks)

We create a NumPy array with numpy.array with a list of numbers.

Then we call array.argsort to get the order of each item in the array.

And we call order.argsort to get the ranking of each value in the array.

Therefore, we see:

[3 1 0 2]
[2 1 3 0]

printed.

Conclusion

To rank items in an array using Python NumPy, without sorting array twice, we can use the argsort method.

Categories
Python Answers

How to find common substrings between two strings with Python?

Sometimes, we want to find common substrings between two strings with Python.

In this article, we’ll look at how to find common substrings between two strings with Python.

How to find common substrings between two strings with Python?

To find common substrings between two strings with Python, we can use the difflib module.

For instance, we write:

from difflib import SequenceMatcher

string1 = "apple pie available"
string2 = "come have some apple pies"

match = SequenceMatcher(None, string1,
                        string2).find_longest_match(0, len(string1), 0,
                                                    len(string2))

print(match)
print(string1[match.a:match.a + match.size])
print(string2[match.b:match.b + match.size])

We have 2 strings string1 and string2 that we want to find the common substring that’s in both strings.

To do that, we use the SequenceMatcher class with string1 and string2.

And we call the find_longest_match method with the indexes for both strings to search for.

Finally, we get the substring that matched from the match object, which has the start and index of the matches with match.a and match.a + match.size for the first string and match.b and match.b + match.size for the 2nd string respectively.

As a result, we see:

Match(a=0, b=15, size=9)
apple pie
apple pie

printed.

Conclusion

To find common substrings between two strings with Python, we can use the difflib module.

Categories
Python Answers

How to get a weighted random selection with and without replacement with Python?

Sometimes, we want to get a weighted random selection with and without replacement with Python.

In this article, we’ll look at how to get a weighted random selection with and without replacement with Python.

How to get a weighted random selection with and without replacement with Python?

To get a weighted random selection with and without replacement with Python, we can use NumPy’s random module.

For instance, we write:

import numpy.random as rnd

sampling_size = 3
domain = ['white', 'blue', 'black', 'yellow', 'green']
probs = [.1, .2, .4, .1, .2]
sample = rnd.choice(domain, size=sampling_size, replace=False, p=probs)
print(sample)

We have a list of choices to choose from from the domain list.

probs has the probability of each value being chosen.

Next, we call rnd.choice with the domain, size, replace and p.

size is the number of choices to make.

replace set to False means the chosen item won’t be a choice again.

And p is the probabilities of each item being chosen.

Therefore, sample is something like ['green' 'blue' 'yellow'].

Conclusion

To get a weighted random selection with and without replacement with Python, we can use NumPy’s random module.