Floating mistakes

Can you see the difference in Python 2 and Python 3 in the following code?

from math import log

def test():
	a = 926941184
	b = 737498881
	print(a/b)
	print(log(a/b, 2))

It is the division operator. In Python 2, the result of the division is 1, therefore the log of the result is 0 while in Python 3 we get a floating number. Keeping that in mind, spot the mistake in the following code. We want to compute whether every number in the iterable A is can be obtained by any element in A by multiplying or dividing by 2. We assume that the given numbers are positive.

from math import log

def isPowerOfTwo(num):
    return int(log(num, 2)) == log(num, 2)

def getAnswer(A):
    max_el = max(A)
    for x in A:
        if not isPowerOfTwo(max_el / x):
            return "NO"
    return "YES"

The code above is correct for Python 3 but not for Python 2.

from __future__ import division

That fixes the issue.

Of course, there are better ways to check whether a number is a power of two (assuming that it is an integer).

def isPowerOfTwo(num):
	return num & (num - 1) == 0

Virtualenv

Problem

You want to install/test a library for Python but you don’t want it to interfere with the rest of the system.

You want different installation of Python and sets of libraries at the same time on your system. You also want the ability to switch from one to the other.

You are a robot (or a mathematical statement) and you have started enumerating all the possible things that you can do with your computer. Present one of those.

All these problems have a common solution.

Solution

Setup

  1. Install virtualenv using your package manager
  2. mkdir ~/virtual_env
  3. virtualenv ~/virtual_env/virt1

You can create more than one virtual environment by choosing different directories.

Activation

  1. source ~/virtual_env/virt1/bin/activate

Now, you use the “special environment” that is described in virt1 dir. It may contain a different version of Python, libraries that do not exist system-wide etc…

Any installation that you do at these point using tools such as pip, easy_install etc affects only this special environment.

For instance:
pip install requests

Deactivation

  • deactivate

How to avoid flunctuations around a threshold

I read the interesting post Checking fluctuating variables using thresholds, the smart way from tzikis. Unfortunately, for some reason I can not post a comment there.

The problem is how to avoid the problem of fluctuations around “soft” thresholds. My solution simply defines a tolerance parameter. If we are “almost” at the same interval as before, we change nothing.

By the way, the bisect module is nice.

import bisect

TOLERANCE = 50
INTERVALS = list(range(0, 1024, 128))


def interval_length(i):
    if i <= 0:
        return 0
    try:
        length = INTERVALS[i] - INTERVALS[i - 1]
    except IndexError:
        length = 0

    return length


def belong(a, current=0):
    """ Always return the index of the right threshold of the interval. """
    if  0 - TOLERANCE <= INTERVALS[current] - a <= interval_length(current) + TOLERANCE:
        return current

    return bisect.bisect_right(INTERVALS, a)


def main():
    a = belong(127)
    print(a)
    a = belong(150, a)
    print(a)
    a = belong(179, a)
    print(a)
    a = belong(560, a)
    print(a)
    a = belong(123, a)
    print(a)
    a = belong(999, a)
    print(a)

if __name__ == '__main__':
    print(INTERVALS)
    main()

Send email using Python 3

A while ago, I had posted a bash script which could spam a friend with a message. It required a computer which was capable of running the mail command, something not true for simple users.

Now, I wanted to send to a friend of mine a message per hour to remind her how old she is (it is her birthday today). I used my gmail account and a few pieces of code.

Because it took me some time to figure out how to make unicode work in the body of the message, I paste here my code for future reference. I found especially useful a blog post: Sending emails via Gmail with Python, which is unfortunately for Python 2. As you can see, the name of the packages and a few details for the unicode have changed.

A tiny detail: I keep a database of quotes using fortune, the unix program. I thought it would be nice to generate a quote and send it via email with each message.

#!/usr/bin/python

import smtplib
import time
from email.mime.text import MIMEText

import os

# authentication
gmail_user = '[email protected]'
gmail_pwd = 'my_super_secret_password'

recipient = "[email protected]"
preable = """A
multiline
message.
"""
end_message = "\n\nRegards,\nΔημήτρης"


def mail(to, subject, text):
    msg = MIMEText(text.encode('utf-8'), 'plain', 'UTF-8')

    msg['From'] = gmail_user
    msg['To'] = to
    msg['Subject'] = subject.encode('utf-8')
    msg.set_charset('utf-8')

    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pwd)
    mailServer.sendmail(gmail_user, to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()


def get_quote():
    """ Generate a random message from a fortune collection. """
    f = os.popen("fortune /home/myle/myle-quotes")
    b = f.read()

    return b


def send_specific_message(counter, quote):
    """ Send a message with a specific structure. """
    topic = "A message (" + str(counter) + ')'
    message = preable + quote + end_message
    mail(recipient,
        topic,
        message)


def main():
    i = 0
    while True:
        i += 1
        quote = get_quote()
        send_specific_message(i, quote)
        time.sleep(60 * 60)


if __name__ == '__main__':
    main()

Encrypted messages (just for fun)

There is no real encryption. It is just for fun. The following program outputs an integer in decimal which has to be “decrypted” to hex and then to ascii in order to display the intended message.


#!/usr/bin/env python3

if __name__ == '__main__':
    a = input('Insert your string please: ')
    hex1 = 0
    for c in a:
        hex1 = 16**2 * hex1 + ord(c)
    secret_message = ''.join(['echo ', str(hex1), 'P | dc' ])
    print(secret_message)

We can display easily the message using a program like dc(1) — an arbitrary precision calculator. The aforementioned program outputs how we can do it for convenience. 

 

Replacing modulo

Let’s build a counter like a clock. We want to start from 0 until 23 and then back to 0.

A first try could be:


def hour():
    i = 0
    while True:
        i += 1
        yield i % 24

def main():
    for i in hour():
        print(i)

if __name__ == '__main__':
    main()
 

Suppose we have already profiled our program and this is its bottleneck. We know that modulo is an expensive operation sometimes. That is why we strive for its replacement by other more elementary operations.

If the hours were a power of 2 (like 16 or 32), we could employ a trick using binary operations which are very efficient since the all numbers are internally represented in the binary system and a computer is so “familiar” with those operations that he can execute them really fast. The following code demonstrates this trick were we suppose that the number of hours in a day is 32 (we wish!).


def hour():
    i = 0
    while True:
        i += 1
        yield i & 31

def main():
    for i in hour():
        print(i)

if __name__ == '__main__':
    main()

Notice that the trick does not work for values which are not powers of 2. Why does it work in these cases? All the magic is due to the & operator which denotes the and operation. The and operation takes as input two binary digits (0 or 1) and outputs a binary digit as follows: 0 & 0 = 0, 0 & 1 = 0, 1 & 0 = 0, 1 & 1 = 0. It is easy to observe that it always outputs 0 unless both its inputs are 1. There are two key observations here.

  1. If an input is always 1, then and outputs the contents of its other input.
  2. If an input is always 0, then and outputs always 0.

In the decimal system, every digit has a weight which is a power of 10. For instance the number 1234 = 1 * 10^3 + 2 * 10^2 + 3 * 10^1 + 4 * 10^0. Similarly, in the binary system every digit has a weight which is a power of 2. 0101 = 0 * 2^3 + 1 * 2^2 + 0 * 2 ^1 + 0 * 2^0 = 5. As we would expect, as a power 10 in the decimal system is an 1 followed by as many zeros as the exponent of that power, the same holds for the binary system. So, 2^5 = 100000 = 32. Now, substracting 1 by 32 would leave us with: 31 = 011111 = 31.

When the Python interpreter executes the statement `i & 31` imagine a procedure like the following:

  1. Find the value of i (it already is in binary form).
  2. Write the number 31 in binary form.
  3. Pad (from the left) with extra zeros if need be.
  4. Execute the and operation

Every digit of i is unaltered by this operation except the highest order digits, since the 5 least significant digits of 31 are all 1. On the other hand, the higher order digits are 0, so the generator hour() can not yield a number larger than 31. Since after 31 is the number 32 which is represented as (100000) and then it is masked (the technical term when we apply the operation and to a number with another known number) with (011111) the result is always (000000). So, the counter start over again.

But what if we would like a more general approach even for numbers which are not a power of 2? Then, we could use a more general approach like:


from math import log
from math import ceil

def almostmodulo(x, y):
    higher_power = 2 ** ceil(log(y, 2)) - 1
    remains = higher_power - y + 1
    if ((x + remains) & higher_power == 0):
        return 0
    else:
        return x + 1
 

The operation of finding the higher power of 2 is relatively simply using a binary operation called shift and is really needed only once throughout the execution of the program. We see that we use the same trick, but use the variable remains to cover the difference with the higher power of two. The catch here is that the control flow costs too much and that is why we do not see this code in practice. We could have removed it if we knew the variable remains contains the number 1 (find out how. ) but then we fall back to the previous case! Be aware that the last code does not work when y is a power of 2, ie, in the cases that the second one works!

So, what is the meaning of this post? Which technique should we use to write super fast code? Well, the answer is trivial. Use your profiler firstly and then decide what you should optimize. Then, if it comes down to such a detail, you should probably consider writing the whole thing in another language like C. The purpose of this post was to demonstrate a few tricks and to give a clue how could the internal representation of a program and its data which are depended on the computer architecture could affect the decision of a programmer. Even though most likely the aforementioned programmer would not be one who uses a high level language, but someone who writes compilers.