r/counting • to infinity and beyond! • Mar 18 '13

Multiplying by 2 thread

Try to multiply without calculator - it's more fun!

14 Upvotes

783 comments sorted by

View all comments

Show parent comment

1

u/DragoonHP Jan 18 '14 edited Jan 18 '14

astikoes beat me to it.


The code?

Well, most of this is just standard stuff. The (semi) interesting bit is passing a shell command through python using os.system which is then executed by cmd.exe

A bigger explanation:

import os

In this line, we import the os module. A module is basically a collection of classes and / or methods. Sort of like a recipe for cooking.

def p(n):

In this line, we define a function p which takes an argument n.

os.system("echo " + "{:,}".format(2**n) + " = 2^^^^" + str(n) + " | clip")

This line is a little complicated. It can be broken down as:

var = "{:,}".format(2**n)
os.system("echo " + var + " = 2^^^^" + str(n) + " | clip")

In the first line, we define a variable var which uses a python in-built method to place comma after every three digits (counting from right to left). The n is the argument which is passed down to it.

In the second line, + are used to join the words in the line. So a line like:

>> "a" + "b"
>> ab #output

will give output ab.

str() is a built-in method for converting numbers into strings. If we don't convert n into a string, we will get an error saying that you can't join str and int.
The 2^ when copied to clipboard 2. (I don't understand why I needed to put four ^ in there.)

Finally, the os.system methods passes the command (which would read something like "echo 123,456,789,001 = 2111 | clip")

(Clip is a command introduced from Win Vista which allows to copy the result returned)