Python

Arithmetic shift with Python

Posted on Updated on

While reviewing a piece of source code at work I found something like this which I wasn’t very familiar with:

a = (1<<0)
b = (1<<1)
c = (1<<2)
d = (1<<3)
e = (1<<4)
f = (1<<5)
g = (1<<6)
h = (1<<7)
i = (1<<8)
j = (1<<9)
k = (1<<10)

What we have is called shifting, which is shifting integer values either from the left or to the right. In the example above, we shift the integer values on the right, to the left by 1. It’s so easy to understand yet I was confused about this.

To understand what’s going on, lets put our values above into dict, traverse through them in a for loop and print out their values:

>>> for i in sorted(test_dict.items()):
… print i

(‘a’, 1)
(‘b’, 2)
(‘c’, 4)
(‘d’, 8)
(‘e’, 16)
(‘f’, 32)
(‘g’, 64)
(‘h’, 128)
(‘i’, 256)
(‘j’, 512)
(‘k’, 1024)
>>>

The values in our dict looks familiar to me. Yup, its a binary system! (read here for more details: http://www.plcdev.com/plc_basics/number_systems_and_codes/binary_people_learning_your_1s_and_0s )

So why are our values 1 to 10 being printed out in the binary system? because the binary format of our integers are being shifted to the left by 1 place, like so:

>>> test_list = [a, b, c, d, e, f, g, h, i, j, k]
>>> for i in test_list:
… print i

1
2
4
8
16
32
64
128
256
512
1024
>>> for i in test_list:
… print bin(i)

0b1
0b10
0b100
0b1000
0b10000
0b100000
0b1000000
0b10000000
0b100000000
0b1000000000
0b10000000000
>>>

We can have a class file that will read in an integer of … say … 5? 5 will use this new binary system we declared and work out which variables from a to k is true and which are false. For example:

(‘a’, 1) True
(‘b’, 2) False
(‘c’, 4) True
(‘d’, 8) False
(‘e’, 16) False
(‘f’, 32) False
(‘g’, 64) False
(‘h’, 128) False
(‘i’, 256) False
(‘j’, 512) False
(‘k’, 1024) False

One genius way of using shift. I like to know more.
Also this isn’t just in Python, but other programming languages support this, especially C & C++

Advertisements

Django/Python – changing pages

Posted on Updated on

Just learned a new Django trick from my sempai at work. For confidentiality I’ve rewritten new code to show this example. Lets say users want to switch back and forth to 2 different pages or more.. like at a movie theatre. Users order either salt or caramel popcorn. In out views.py, code would look something like this:

def popcorn_test(request, page=1):
    ...
    if request.is_salt_popcorn_lover:
        return render(popcorn_1.html, context)
    elif request.is_caramel_popcorn_lover:
        return _render(popcorn_2.html, context)

It’s not so bad, but if we want to add more crazy flavors we need more pages and eventually our code would grow bigger and might turn into something like this:

def popcorn_test(request, page=1):
    ...
    if request.is_salt_popcorn_lover:
        return render(popcorn_1.html, context)
    elif request.is_caramel_popcorn_lover:
        return _render(popcorn_2.html, context)
    elif request.is_chocolate_popcorn_lover:
        return _render(popcorn_3.html, context)
    elif request.is_toffee_crisp_popcorn_lover:
        return _render(popcorn_4.html, context)

This makes engineers hostile and angry. So to avoid repeating ourselves we can do this instead:

def popcorn_test(request, page=1):
    ...
    if request.is_salt_popcorn_lover:
        return _render(‘popcorn_{}.html'.format(page) context)    

then in our urls.py page, where parameters will be passed in, we change what we had before from this:

url(r'^ popcorn_test/$', 'popcorn_test', name=‘popcorn_page’),

to this:

url(r'^ popcorn_test/$', 'popcorn_test', name=‘popcorn_page’),
url(r'^ popcorn_test/(?P<page>\d+)/$', 'popcorn_test', name=‘popcorn_page’), 

Now we can pass parameters into our views and our new code can determine which page to jump to depending on the choices the user makes.

“Trouble converting string to int in Django/Python”

Posted on Updated on

A little while ago I was browsing on Stackoverflow (great website!) for Django & Python stuff. This was maybe last year or so? What I was trying to do was cast a string to an int but I had all sorts of conversion errors. But then I found this thread ( http://stackoverflow.com/questions/7448531/trouble-converting-string-to-int-in-django-python ) and learned a really great yet stupid trick which is this:

a = int('0' + someString)

Adding a zero in front of a string guaranties me to have at least “0” in the string. Now, to be sure, you may extract all the digits from the “‘0’+someString” with a regular expression.

Brilliant this is useful! blogging so my future self will see.

Fun with Perl #3 – Hashes

Posted on Updated on

Managed to finish my work a bit early so I get to play around with Perl again … for a little bit. I’m trying to get my head around object orientation in this language but it looks … strange still … so I need more time to get used to that first.

Today I looked at Hashes because I never really use this tool in any language. The closest I have ever used is probably a dictionary in Python and/or a map in C++. Basically, a Hash in Perl is a dictionary in Python with a key and value definition but the syntax is a little different. The idea is very easy to understand.

In Perl you make a hash like this:

%hash = ("UK", 1, "HK", 2, "CND", 3);

and in Python a dictionary, which works the same way, is created like this:

names = {“UK”: 1, “HK”: 2, “CND”: 3}

the strings UK, HK and CND are keys, which have int values each. Printing out the Hash/dictionary contents will look like below:

UK - 1
HK - 2
CND - 3

Fun with Perl #2 – Arrays & hard reference

Posted on Updated on

I moved to a new team this week so I haven’t had time to play around with Perl as much as I wanted .. but, I have a bit of free time to at least post something on what I thought was kinda cool but very basic.

$name = 'bill';

above is a reference to a string ‘bill’

$fooref = \$name;

is a hard reference which when run prints the following

SCALAR(0x7fa5d3006ce8)

So that was cool.. what about arrays? thats easy.

@array = ('Benji', 'Daniel', 'Ando');

and thats it. I figured to wrap everything together in 3 different subroutines/methods and run them all at the same time in some order I can see each result at the same time. So I modified my code and my result became the source below.

sub answer { 
	$name = 'bill';
	return \$name;
}

sub reference_answer { 
	$fooref = answer();
        print $fooref, "\n";
}
#! /usr/bin/perl


# サブルーチンの定義
# sub サブルーチン名 { 処理 }
# (sub + 半角スペース + サブルーチン名 + ブロック)

sub answer { 
	$name = 'bill';
	return \$name;
}

sub reference_answer { 
	$fooref = answer();
	print $fooref, "\n";
}

# &amp;amp;array_sub;
sub array_sub {

	# 配列を作る
	@array = ('Benji', 'Daniel', 'Ando');

	# 配列の中身を出力
	foreach $count(@array) {
		print $count, "\n";
	}	

	# 中身のハードリファレンスを出力
	foreach $count(@array) {
		print \@count, "\n";
	}
}

print "reference_answer --", reference_answer();
print "array_sub --" array_sub();

when run:

SCALAR(0x7fa5d3006ce8)
reference_answer -- 1Benji
Daniel
Ando
ARRAY(0x7fa5d300a3e0)
ARRAY(0x7fa5d300a3e0)
ARRAY(0x7fa5d300a3e0)

time to get back to work and stop playing around ..
sorry if my variable names and output results look very messy. Next time I’ll make something cool and easier to read.

Fun with Perl

Posted on Updated on

I’ve been wanting to learn Perl for a long time but never had the chance. So today after finishing my assignment and a bit of time to spare I decided to have a little fun with it and see just what kind of cool things I can do with it.

This is just a simple for loop inside another for loop to print a 10 by 10 grid. Useful for later if I want to iterate then print out a 2D array.

#!/usr/local/bin/perl
my $count;
 
$count;
$new_count;
 
for ($count = 0; $count &lt; 10; $count++) {
        print $count;
    for ($new_count = 0; $new_count; 10; $new_count++) {
        print $new_count;
    }
    print "\n";
}