Different things, different perceptions.

My journey towards learning.

Python Tip #12.5.25 [Data Structures in Python. Strings vs Lists vs Tuples vs Dictionaries]

Skip this paragraph if you want to get straight to the brief tutorial. So for past couple of days I have been trying to learn Python. My love towards this scripting language has slowly grown ever since, even though I was a bit disappointed with the strict indentation that it imposes. Nevertheless, the more I learn about it the more sensible it’s approach becomes or as it’s called  the Pythonian approach. But today we shall be looking at the data structures which is crucial when it comes to storing, manipulating datas.

STRINGS, LISTS, TUPLES, DICTIONARIES. Though there are others out there these  four data structures are the most widely and commonly used in Python.

What is a string?

- This might be the most common data structure one can find in programming language. Strings are nothing but the values written within quotes. In my last post we talked about how we can use triple quote for multi-line strings so with addition we can also use single and double quotes too. The difference between single and double quotes are that they are often interchangeable but has to be consistent with it. In other words,  if we start string with single quote then we must end with single quote regardless of the amount of double quotes used in between.

One important distinction of string in Python with other languages is that strings are immutable, which means that they cannot be changed. They stay constant.

e.g

>>>x = “hello world”

What is a list?

- A list can be viewed as a dynamic array. Unlike arrays in C which must contain only one type for an array, list can have any type i.e. numbers, string functions, objects etc.

e.g.

>>> x = ['hello', 2, 'you']

Lists are mutable. They can be changed.

What are Tuples ?

- In general, tuples are immutable list. Same rule applies to tuples as it did on list too.

e.g.

>>> x = (‘hello’, 2, ‘you’)

Again, tuples are immutable just like strings.

What are Dictionaries?

- Dictionaries are dynamic arrays which has key and value pair and can be either integer, tuple or string. It can compared to the hash table because it behaves like one.

Dictionaries are mutable just like lists.


INITIALIZING

The following are ways to initialize an empty variable for strings, lists, tuples, and dictionaries.

String:- x = ‘’

or

x = “”

or

x = “””

“””

Lists:- y = []

Tuples:- z = ()

Dictionaries:- m = {}


Now that you have created a variable we want to add some values to them. We can achieve this by doing the following:-

INSERTING

Strings:- Like mentioned earlier, strings are immutable. They cannot be changed but that does not mean we cannot insert. There are ways to do it but if you want to be able to keep changing the value then using other data structure is recommended. That being said, here’s one way of inserting values in string.

x = “I need to change”

x = x[:2] + “really” + x[2:] (x = x[:position] + “new variable” + x[position:])

Lists:- Unlike strings lists can be manipulated. Taking the variable “x” from the above we can insert values to list as follows:-

y.append(“add me”) //to add at the end of the list, only one value can be added at a time

y.insert(1,”now”) //to add at the specified index which is 1 in this case, this too can only be done one at a time

y = y + [“or”, “delete”, “me”, 4 , “eva”] //To add multiple values at once at the end of the list

y = y[2:] + [“ignore”,”this”] + y[:2] // To insert multiple values at the index 2

Tuples:-

Tuples, if you read above, are also immutable just like strings. One of the ways to get around this is that  you would first convert it into list an then convert it back to tuple.

Taking the variable from above we can insert values in tuples as following:-

z = list(z)

z.append(“inserting in tuple”)

z = tuple(z)

As you can see we are technically inserting to the list, so anything that can be done on the list as mentioned above can be done in tuple too with the extra conversion step. Again, it is not recommended and not a Pythonian approach to change immutable objects but there are workarounds.

Dictionaries:-

Inserting in dictionaries is a bit different than tuples or lists. Because it also requires key for the value to make a pair so we have to specify key for each value. We specify key on the left and value on the right separated by “:”

e.g.

m = {“fruit”:”apple”,”veggie”:”potato”,”fruit”:”grape”}

or

m[“fruit”] = “apple”

m[“veggie”] = “potato”


Some other operations that can be performed:-

There are numerous operations that can be performed in data structures. The above is just a brief introduction to data structures. You can delete, sort, split and other operations that you can perform in data structures. I will leave that up to you to discover. I might talk about one or two in near future but I will leave Python’s documentation to do the explanation this time. Happy Pythoning.

Image Courtesy of XKCD.com

Python’s Documentation / Reference:-

Strings

Lists

Tuples

Dictionaries

Python tip #[12.17.5]

Skip this paragraph if you are just coming for the tips, everyone else continue. As of today, my summer has officially started and like promised I will be posting daily tips, tricks, and stuffs that I am not familiar with inside the land of computing/programming. Also, if you would like to know about the stuff you would want to let me know in the comments below.

PYTHON AND A MISCONCEPTION ON MULTI-LINE COMMENTS

It it not uncommon to find an abundance of tips and tutorial on single-line comment in Python on web but no one really talks about multi-line comment. It is because Python does not have multi-line comments.

Although some say it can be done with the triple quotes

“”” I am not really a multiple-

line comment “””.

The above actually is a docstring.

What is a docstring?

A docstring acts as a document for the code. It can be called as a comment for the source code but are not stripped away when it is parsed unlike comments. In other words, docstrings are still accessible throughout the runtime of the program.

The above link gives a detailed information on what doc-strings are by providing few examples. But in an overview doc-strings can be accessible with __doc__ attribute on objects.

Example:-

class Module1(object):
    “”"This is class docstring”"”
    def get(self):
        “”"I am getting stuff”"”
        print(“get it”)

Now open your Python interpreter and type

import test (assuming your filename is test.py)
help(test.Module1.__doc__)

or

help(test.Module1.get.__doc__)

The other misconception about Python and triple quotes is that the triple quotes that is assigned to a variable acts as multi-line string-literals.

Example:-

greet = “”"Welcome to the
wonderful world of Python”"”

The above variable greet is holding string literal, not docstring. Triple quotes in string variable are generally used to assign multi-line values. Double quotes and single quotes are however interchangeable.

Play around with the code and let me know if you found something new or just found something horribly wrong with my finding. I am learning just like you are and mistakes can happen. It is only by sharing our knowledge that we can move ahead. With that philosophical statement I shall return with another tip tomorrow, hopefully.

 

Coming in Summer…

This spring has been horrible with college and work, I have got barely time to update my blog. But that will change once in summer after school is over.

This summer I will be posting an interesting but random tips and tutorials on C++ and web development on a daily basis. The topics might cover SFML library, machine learning, PHP, Ruby on Rails, Python, CSS, HTML5 and Dojo but the tutorials will be primarily focus on C++.

Let me know if you want the video tutorials as well in the comment section below. I may not have perfect English but I will try my best to make it comprehendible.

Setting PATH in Windows from command line/console

Skip the next two paragraphs if you don’t want to read my rant about the current situation of our Internet and piracy policies.

2012 has already been a crazy year, The birth of SOPA, PIPA, ACTA, the fall of Megaupload and many other major file sharing sites at the beginning month of the year is just the start of the continuous suppression of the freedom of our Internet. I am not advocating on piracy but destroying the very meaning of Internet is a very worrisome thought.

“The cure is worse than the disease.” is the only thing I can think of when I hear about SOPA, PIPA and ACTA. Trying to censor the Internet is not the solution to piracy. I am just amazed how these legislators does not even ask why people pirate in the first place. Provide a first class service with reasonable charge and I can promise you people will pay for your content. Why do you think people wait endless line to get a decent product? I myself am a very good example of this. I am not a movie person but I pay for Netflix to watch movies just now and then and that has exposed me to the whole library of movie I never thought about watching. I would have never paid a dime to movie industry hadn’t it been for Netflix because once I watch the movie I don’t feel the need to keep the DVDs with me. I could go to cinemas you say? Nope I would rather watch movies in my plasma TV than from some projector. Times has changed and so should our legislators. They have to start realizing that there are new ways to deliver rather than apply the same obsolete way to distribute the content. While piracy can never be stopped better service can definitely bring piracy down and this is a fact.

        Ok, so after that let us get back to learning something new today. If you’re following me in the blog you know that I am working on a Yii project and while working on the project I came across a handy command that you might want to use someday.

When you’re in Windows did you ever have to set the system path just so that it automatically ran from your command line? Well, anyone will say “goto start and right click on computer and advanced settings and click the environment variables and just add the path there”. That is one way to solve the problem but imagine doing the same thing for 20 other computers in your work place. It’s quite cumbersome if you ask me so a handy command for it is

c:/> setx path “%PATH%;c:\path\to\your\file”

This applies for Windows XP SP2 or greater also remember that you can provide a temporary path by just typing. %PATH% are the paths already defined in path variable.

c:/> set path “%PATH%;c:\path\to\your\file”

Setx is a program that comes in Windows, if you don’t have it then you can probably download it from the Internet.

How do I automate this?

Just open up a notepad and type the above command and save it in bat format. E.g. you would save this file as “automate.bat”

Now go crazy with that file but remember don’t apply it more than once, it might throw an error message.

A winter with SFML and others

This post is going to be a little different form other posts. I am not going to teach you quick and dirty tips that I have been posting since last couple of weeks but rather my personal journey and adventures of learning 2d game library called SFML (Simple and Fast Multimedia Library) and a  MVC based PHP framework called yii (Yes it is) for my school project in this winter, the winter of 2011. The 2d game library SFML is my personal project and which I have been meaning to learn ever since I was 19, I am 23 now. No, it does not take four years to learn a 2d gaming library but the things that has been keeping me from actually learning the library were college, my current work, bills (my greatest foe and college is not cheap when you’re living all by yourself, dad?) and the fact that it took me 4 long years to decide on the right gaming library.

So how does this post even relate to you and why should you be reading it? The answer is you don’t have to, really, but for people who are just beginning on programming might get some idea and experiences they might face when they venture on their own journey (Send me a link if you do decide to write one). And also, think of this as a starting line for the upcoming SFML tutorials not just quick and dirty solutions but comprehensive and detailed posts on SFML. I do expect you to know C++ and some OOP concepts but I will be talking about OOP concepts in the future posts as well, as they come along. And if you’re more interested about building a web application on the “not so famous” yii framework then those are coming too. Please do make yourself familiar with PHP and MVC architecture as they will be talked extensively. Now that I have given you a preview of what is coming in future let us now begin our adventure on SFML.

Whenever I think of winter it always sounds like a perfect time to stay inside your home with hot coffee, sitting right next to the monitor while furiously researching on the things you always wanted to do from long time. Well, it was not. First of all winter was no where cold this year (could still walk outside with shorts and shirt) and there was no hot coffee (ashamed that I still don’t know how to make a perfect hot coffee)  and lastly the furious research that I expected to do did not turn out exactly well either. Sometimes the frustration of not being able to find the right answer to the question brought me down and I just gave up and started to aimlessly surf the Internet for stupid stuffs. Sometimes the progress is painstakingly slow. There were times that it took me 3 days to find an answer to the problem. It’s no fun when you are stuck on a problem but do remember that you don’t just quit either. Perseverance is the key of getting better at any things but what nobody tells you is where one should go to look for answers. Luckily we have Internet with us these days and there are tons of people who are ready to help and often times have exactly the same problem as we do. Hours and hours of googling, asking help in irc room, posting the problem in forums are some of the ways you can try to look for the answer. If that fails then there are always those long documents that we avoid like a plague. But everyone should read documentation. Not just for looking up the explanation but also to make one itself. Remember, someday you would have to write a documentation too and it would come very handy if you already have some sense of what to put in the documentation. So those are some of the methods you can try if you are stuck on your future problem. Also, I am always ready to help. I will try my best to find the solutions to your problems. But the point of this whole discussion is if you love something so much, you never give up even if it takes forever. I, at least now have the basic understanding of SFML and can make sense of what is actually happening.

So, why did I chose SFML as my journey to game programming? The answer is pretty simple and very subjective. You can pick any other 2D gaming library too but after years of research on choosing the right library I heard from a numerous people that SFML was a great way to start on game programming and because it is 2D only gaming library which is still updated on a regular basis (judging by their github page) and also because it plays nice with OpenGL (which is my next goal). My initial goal is to first start on 2D platform and after the mastery of the 2D platform continue my journey with  3D/OpenGL. I could easily have picked any other 2D libraries too like Allegro or SDL instead of SFML but I also found that it was easier to find the support for SFML than those two other options but do correct me if I’m wrong, also I think SDL is quite outdated now. With that being said the tutorial(map) that I am following in my adventure is from a Serapth who is a redditor and is constantly posting on r/gamedev. If you don’t have any advance experience with C++ then you might have hard time with his tutorials which is just what I am going to do in my future posts, break the advance C++ into tiny pieces and provide you only with SFML content. I will however try to explain the advance techniques he uses but overall he does a decent job of explaining the concepts.

So this is the start of my journey, expect lot of talks on SFML and yii in the future posts. I’m pretty sure there are going to be tons of problems and questions in the future but I’m excited. Smile

Quick and dirty ways to symbolic link (shortcuts) in Ubuntu.

Skip the next paragraph if you don’t want to read what I have to say and already know what you are doing. 

If you are starting out in Ubuntu, chances are you will want to use terminal very often. And soon you will realize that typing cd to get to your directory or file can be very frustrating. Now you might say… “uhh why don’t you just save it all in your home directory, that way you don’t have to cd all the time. Everything is right there for you.” If you’re one of that person then I will quickly associate you with one of my professor who thinks it’s a great idea to put everything in the desktop. Anyway the point is there are people who would want to organize their files, data and keep different types of files in different locations. But cding through these files can be time consuming. So here’s what you do. I like to call these as hot commands while some people might call it something that is equivalent to shortcut in Windows.

To create your very own symlinks all you have to do is type the following:-

me@pc$ ln –s /my_destination_directory /my_symbol_name

or

me@pc$ ln –-symbolic /my_destination_directory /my_symbol_name

Now just type

me@pc$ cd my_symbolic_name

And there you have your very own working symbolic link.

Although I demonstrated you above to add a directory, you can also add a file/program directly on the symlinks.

To remove your symbolic link just type:-

me@pc$ rm my_symbolic_name

Quick and dirty ways to fstab and recovery.

Edit:- Problem related to fstab not being able to mount the disks every time has been fixed.

Skip the next paragraph if you don’t even want to read about the on what I have to say and you know what you’re doing. And if you’re here just for recovery section then jump straight to BUT. section.

Unlike Windows, Linux does not partition your drives automatically by default for extended drives which is why you would need to install some kind of software or mount the partition yourself manually which is where fstab comes in handy. I am assuming that you know what mounting is and how to do it but if you still have that problem then here it is:- mount /device /destination_folder . So let’s get on with it.

Your fstab file of debian distribution (that means you Ubuntu users) is in :-

/etc/fstab

Open the file fstab in your favourite editor and then be enlightened by the following knowledge:-

The “column” that you see marked by my lovely artistic skill on the picture are the six columns that you will encounter in fstab file. If you look closely at the top of the fstab config file then things get clearer for you to what goes where.

Column 1 – Physical device which is to be mounted.


Edit:-

Instead of just typing /dev/sda4 and such, it is highly recommended that you instead type in your UUID.

What is UUID?

UUID is a unique identification given to each drive. Hence, even if you switch the drive fstab will know exactly which device to mount.

To display UUID of your disk just type:-

me@pc$ ls –l /dev/disk/by-uuid/

The texts that are highlighted/alphanumeric_characters are UUID for your device which is displayed at the end of each line

After you have your UUID for your device just type in UUID=”device_uuid_here”, without the quotes.


Column 2 – Specifies the destination of your mount point.

Column 3 – Specifies the file type (auto, auto detects your file type) , filetype = fat, ext, ext2 etc

Column 4 – Options for specifying what the device  can and cannot do. (rw = read write, user = any user can mount this device , auto = automatically mount device on startup <- THIS IS THE SOLUTION TO OUR PROBLEM EARLIER. , sync/async = sync lets you do the input and output to the filesystem synchronously  meaning that whenever you copy something on that device it happens instantaneously but async may not guarantee that. So sticking with sync is the best option.

Column 5 – If you have a backup system then you should research more about this, leaving it 0 will cause dump to ignore that option.

Column 6 – If you want to specify the order of the device in fsck then you would want to do more research on it. 0 will make fsck ignore this option as well.

There you have it a quick and dirty way to fstab.

BUT.

If you do end up screwing up your fstab and cannot get it to it’s default settings then here’s what you need to do.

So, your fstab is broken and you tried restarting your machine in recovery mode but somehow your editor will not let you edit the fstab file because it is read only.

To change that all you need to do is, type the following:-

me@pc# sudo mount -o remount,rw /

what this does is it remounts your file system into read and write mode instead of just read only mode. Because on recovery mode your file system boots in read only mode.

Now try changing your fstab file and tadaa.. You can freely edit your fstab file without worrying about not being able to boot your linux machine.

The secret of “To do Lists”

To do Lists

Ruby :- Day 1

This series of blog posts will be on Ruby 1.9.2. In this series I will assume that you have at least some idea of programming and OOP(Object Oriented Programming) languages. This is going to be quick overview of Ruby for those who want to pick up Ruby fast. However, if you are new to programming and feel like this is not the place for you, I suggest you rather visit Why’s Poignant Guide to Ruby which is an excellent source for getting started with Ruby and programming language as a whole.

Also, I will not be showing you how to install Ruby in your machine. There are plenty of sites that already do that. If you don’t want to search for one then here is the official ruby download help page.

Let’s get started.

Day 1:-

Ruby is a dynamic, interpreted, object-oriented programming language. What this means is that everything in Ruby is an object (having class) and can be run without having to compile the program. If this is a bit too confusing for you then allow me to elaborate it further, or skip to the next section.

The compiler based languages usually have to go through multiple steps before an actual program can be run. The steps that a normal compiler based programming language takes are as follows:-

Source Code -> Compiler -> Target Code – > Further translation into machine code -> Executable Code

Executable Code takes Input from the user and processes it and gives the output.

While in Interpreting language the steps are different and shown below:-

Source Code takes Input from the user interprets it and gives the output.

Although, the path of interpreter languages seem shorter it is usually considered slower than compiled languages. Also, the advantage of compiler based languages is that you really don’t need to have compiler installed to run your executable program in different machine. That is not so in interpreter language. The advantage of interpreter language, also often called scripting language, is that they are easy to learn, dynamic scoping and dynamic typing and are usually less in size than in compiled programs.

Basics:-

To get your hands on Ruby quick, open your terminal or console window and type irb (Interactive Ruby). A ruby console should come up, if not then you might want to add the path of ruby’s main file to your system. If irb do show up then start typing some number, do some mathematical operation on them. The output is almost instant. Since, everything in ruby is class, the output that you will see (which is denoted by ‘=>’ ) is the return value from that object. Let’s forget the details for now. I shall add tell you the details as we move along the topics.

For now, play with irb console. Here’s a few thing to get you started.

puts 2 + 3
puts "hello world"
puts "hello world \n goodbye world"
puts 'hello world \n goodbye world'

You might already know by now that puts prints the output to screen but do notice that it also adds newline at the end. To get around this use print instead.

print 2 + 3
print "hello world"

Numbers
Integers and floats are the same as it is for other programming languages. Any number that has decimal point in it is called float and without is integer.
You can easily change data types in ruby which is also called dynamically typed. We’ll be talking about type-casting (converting one type to another) a lot later, but now play with the number. Note that the power symbol for Ruby is ‘**’ and every other arithmetic operators are the same.

Strings
Now that you are familiar with numbers let’s go ahead and play with strings.
Strings in ruby are placed between single quotes or double quotes. However, there is a difference between strings between single quotes and double quotes.
As we saw from our previous examples they behave differently. Single quotes return whatever is between the quotes but in double quote special characters are interpolated. Meaning, if you add any special character like say \n in our previous example, this represents a special character and is interpolated into new line.
Lets try our examples again :-

 puts "Hello \t world \n"
puts 'Hello \t world \n"

But what if you want to put single quote inside the string? Simple, you just escape that character with backslash (\). So

 puts 'Ruby\'s Cool'
puts "\\\\ This is double slash"

String Arithmetic
Just like in number there are some arithmetic operator that you can also do in strings.
Concatenation
Usually called concatenation, strings can be added to represent a single term.

puts "Hello" + " world"

Later you will find that not only can you concatenate strings but variables too. If you have done any JavaScript then this should be familiar to you, however PHP developers should note that ‘.’ is not the concatenation in ruby.
Note that you cannot perform arithmetic operations inside quotes. You should know that by now.

Multiplication
This can really be done with loop but is handy when you need to perform quick string repetition.
If you place ‘*’ with any number then ruby repeats that string for you.

puts "echo" * 4
puts 'anyone??' * 4

We shall stop here for today. Play with irb, try different possibilities and have fun with it.

Follow

Get every new post delivered to your Inbox.