OCaml

Hi there,

ocaml

Here is an interesting language I came accross today: OCaml.

What is OCaml? OCaml is a general purpose industrial-strength programming language with an emphasis on expressiveness and safety. It is the technology of choice in companies where a single mistake can cost millions and speed matters, and there is an active community that has developed a rich set of libraries.

Source: https://ocaml.org/learn/

Moreover, I found an interesting article talking about the pros and cons of this language. Esper Tech Blog, the author of the article addressed my next quesiton as well: “who uses OCaml?”

To my surprise, many well-know companies use it such as:

The tools that will get you started are:

The Web-based OCaml compiler makes it easy to jump-start playing around with the language.

Have fun!

@codepyxi

Install Django in a virtualenv

djangoproject

djangoproject

Installing Django in a virtual environment

Django is an open-source MTV (Model Template View) framework written in Python for building web applications.

Get Started:

Step 1) pip

If you already have Python 2 or Python 3 installed in your computer, go ahead and verify you have pip:

In your Terminal run:

$ which pip
/usr/local/bin/pip
$ pip –version
pip 9.0.1 from /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg (python 2.7)

If you do not have pip, the run:

$ sudo easy_install pip

Step 2) virtual environment

Install the virtual environment

$ sudo pip install virtualenv

mac_terminal_pip_install_virtualenv

Done! The virtual environment is installed.

Navigate where you want to test/play with Django

Go to the main directory where you want to work.

Here are some useful commands to navigate in your Terminal:

  • pwd
  • ls
  • cd
  • cd ..
  • clear
  • mkdir

I decided to work from the Desktop:

~ $ cd Desktop

Create a directory where you want test/play with Django

Next, create a directory where you want to work from:

:Desktop $ mkdir DjangoVM

Name your virtual environment

It is time to name your brand new virtual environment:

DjangoVM $ virtual sandbox

I decided to name my virtual environment “sandbox” but you can name it whatever you like.

Congrats! Your virtual environment is now installed.

mac_terminal_virtualenv_name

See it for yourself:

:DjangoVM $ cd sandbox
:sandbox $ ls
bin                 lib
include        pip-selfcheck.json

Entering the Virtual Environment

enter_virtual_environment

$ source bin/activate
(sandbox)  :sandbox $

That’s it.

The name sounds cooler than what we just got. I mean, we had much more going on while installing pip or even virtualenv. Well, again, that is it.

Step 3) django

Before installing Django, let us check which version of Python we have. That way, we will pick the right Django version.

(sandbox)  :sandbox $ python -V
Python 2.7.10

If you want to take a break, read this WTF Moment.

python_django_versions

Here we are! The moment of truth. Let us run this command and install django.

(sandbox)  :sandbox $ pip install django==1.11
Collecting django==1.11
Downloading Django-1.11-py2.py3-none-any.whl (6.9MB)
100% |████████████████████████████████| 6.9MB 148kB/s
Collecting pytz (from django==1.11)
Downloading pytz-2017.3-py2.py3-none-any.whl (511kB)
100% |████████████████████████████████| 512kB 1.5MB/s
Installing collected packages: pytz, django
Successfully installed django-1.11 pytz-2017.3
(sandbox) Xis-MacBook-Pro:sandbox xi$

Look at that!

I recommend this YouTube video in case you want to learn more about:

(sandbox)  :sandbox $ pip freeze
Django==1.11
pytz==2017.3
(sandbox)  :sandbox $ pip install django --upgrade

Fun fact!

I met Kojo at PYCONCA 2017. Super cool guy who likes to talk about Django.

Here he is for you to meet:

Happy coding!

@codepyxi

WTF Moment: python -v

Hi there,

While installing Django I typed in the Terminal by mistake

$ python -v

instead of:

$ python -V

and I got the weirdest response :

# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py
import site # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py
import os # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc
import errno # builtin
import posix # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py
import posixpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.py
import stat # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py
import genericpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.py
import warnings # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.py
import linecache # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.py
import types # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py
import UserDict # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.py
import _abcoll # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.py
import abc # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.py
import _weakrefset # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.pyc
import _weakref # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py
import copy_reg # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.py
import traceback # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.py
import sysconfig # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sysconfig.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py
import re # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.py
import sre_compile # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.pyc
import _sre # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py
import sre_parse # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.py
import sre_constants # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_constants.pyc
dlopen(“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so”, 2);
import _locale # dynamically loaded from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py
import _sysconfigdata # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.py
import _osx_support # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.pyc
import encodings # directory /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.py
import encodings # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/__init__.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py
import codecs # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.pyc
import _codecs # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/aliases.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/aliases.py
import encodings.aliases # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/aliases.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py
import encodings.utf_8 # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.pyc
Python 2.7.10 (default, Feb 7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
dlopen(“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/readline.so”, 2);
import readline # dynamically loaded from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/readline.so
>>>

Needless to say, that I said to myself: “WTF just happened there!!!”

I Googled (obviously!) the “error” and could not find anything that explained it. My adrenaline was undoubtedly rising. I thought I downloaded some weird virus or something. At 6am, that is the best shot of coffee you can get 😉

I found an excellent and concise article saying: “All is well. You’re just getting a peak behind the curtain….” that dispelled my scary thoughts.

Keep having fun coding!

@codepyxi

Scratching the Programming Surface

Hi there,

I just finished my first week (or week-0 as it was called) in computer science (a.k.a. CS). The language used was Scratch.

Scratch is a free visual programming language developed by the MIT Media Lab.  […]  It provides a stepping stone to the more advanced world of computer programming. It can also be used for a range of educational  […]  purposes from math and science projects, including simulations and visualizations of experiments, recording lectures with animated presentations, to social sciences animated stories, and interactive art and music.

Scratch allows users to use event-driven programming with multiple active objects called sprites. Sprites can be drawn, as vector or bitmap graphics, from scratch in a simple editor that is part of Scratch, or can be imported from external sources, including webcams.
Source: Wikipedia / Scratch (programming language)

 

When a random person (not a programmer –> ) thinks about programming, the first thing that comes to mind is a black (or white) background with unappelling characters making no sense … or at least that is what one thinks.

Noticing the differnce between Natural languages and Formal languages is useful to understant WHY one might have the impression mentioned above about programming.

 

Formal and natural languages

Natural languages are the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.
Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal lan- guage to represent the chemical structure of molecules. And most importantly:
Programming languages are formal languages that have been designed to express computations.
Source: Allen B. Downey (November 2012). Think Python: How to Think Like a Computer Scientist. Retrieved Green Tea Press

 

Having been there myself, I concur that at first glance programming (a.k.a. coding) can look quite cryptic. Nevertheless, once one starts getting used to the programming language tools (characters, functions, etc) and using them, only then that one becomes fortunate enough to see beauty emerging from it.

Scratch takes away the cryptic part of programming and instead it incorporates the “Natural Language Flow” to programming. It is visually interesting and fun to use.

As you know, I started my programming journey with Python. It took several attemps to find beauty in it. However, in my humble opinion, Scratch is a really nice entry point to finally say:

Hello, world!

So starting next month, February 2017, a serie of three (3) sessions will be offered as an introduction to the programming world.

Here is the format:

  • Session 1) Computer set-up + Vocabulary + say: “Hello, world!” + Intro to Sprites’ costumes and sounds
  • Session 2) Animation1 + Animation2 + Animation3
  • Session 3) Game1 + Game2 + Game3
  • Showcasing and playing a few games from the participants

 

This serie is particularly tailored to adults humble enough to start from Scratch 😉

Two conditions to join:

  1. Respect
  2. Register at the EventBrite page Eventbrite - Scratching the Programming Surface : Session I

 

See ya soon!

 

NOTE: If you are a programmer and would like to volunteer, send an email, then an interview will follow prior to joining.

 

Code Time :: Montreal Espace Confort

Hi there!

If you are in Montreal (Canada) on January 26th and want to code in a relax fun atmosphere, here is where:

Auberge Montreal Espace Confort

Wednesday, January 26th, 2017

From 6:00 p.m. to 8:00 p.m.

Please register via Eventbrite in order to have access to the coding lounge.

Eventbrite - Code Time :: Montreal Espace Confort

 

 

 

Who should attend?

  • if you are a developer (and want to code in a fun atmosphere):
  • then join!
  • elif you are a newbie in the programming world:
  • then say: “hello, world” and join!
  • else:
  • send us an email in order to tell us why you want to join 😉

 

Feel free to bring along any computer science / tech related projects, and questions you want to work on.

Advantages++ :

  1. Code in a relaxed fun atmosphere is really inspiring.
  2. Find answers to your coding questions or at the very least find a path to find an answer. Here is a start:
  3. Stumbling upon a coding wall is frequent in any coding journey. Take this opportunity to overcome these obstacles!
  4. Take a break from the winter wind an sip a cup of coffee with us.

 

You could buy a cup of coffee, pastries and code for two hours with us.

Here is the price list of the Hotel Montréal Espace Confort :

  • Coffee ($3.50)
  • Tea ($2.50)
  • Pastry ($3.50)

 

See you  soon!

Binary Tree

Coursera :: Python for Everybody Specialization

Hi there,

Remember the Coursera class I mentioned on the last post? Well, the course was such a success (for both organizers and students) that there is a second part to it.

This course has been so successful that we have decided to push further and offer an entire five-course Python specialization that covers the entire textbook and adds a project-oriented Capstone at the end of the specialization.

Source: Coursera

The second part of this specialization is about:

All classes are exceptionally well designed. The content is pertinent and everything taught by Professor Charles Severance is  very clear.

The best part: it is very enjoyable. In fact, you might even develop a craving for more Python and especially more data!

Before this class, I never asked myself where to find data. Data: to split, to parse, to format, to clean, to visualize and what not.

So, if you are looking for some data to play with, here are six open data sources:

If you have a favourite one, not listed here, please share.

Cities data sources contain information about restaurants.
Warning: Hypochondriacs, stay away from the restaurant data 😉

Also, for all newfound data troglodytes out there, here is a gem: Quantopian Fetch Method

“Quantopian [has got] a method called Fetcher which basically lets you grab CSV data from anywhere on the Internet: HTTP, HTTPS” — Dr. Jess Stauth

 

If you wonder what you can do with data coming from cities around the world, you might find some inspiration through the NYC Python talks. I once attended a meetup where they presented the ins and outs of NYC subway users. It was fun.

 

Here are some quotes to keep you going:

“It does not matter how slowly you go as long as you do not stop”
Confucius

 

“There is no elevator to success. You have to take the stairs”

Unknown

 

Stairs to Mont-Royal (Montreal, Canada)

Stairs to Mont-Royal (Montreal, Canada)

 

Have fun coding!

Coursera: Programming for Everybody (Summer 2015)

Hi there,

I hope you are getting ready for summer weather (… if you live in the northern hemisphere).

Spring NYC 2015

Spring NYC 2015

 

If you are planning on tackling programming this summer, here are some good news.

Professor Charles Severance‘s class: “Programming for Everybody” at the University of Michigan has just started. As you know, I have tried several ways to learn python. Also, if you remember, when I started I did not know how to open the terminal of my computer. The books and classes I attended all assumed that I knew how to navigate in the Terminal. So, when I was in class they jumped from screen to screen with little opportunity for me to even take notes. Stressful? Yes. Frustrating? Yes. Giving up? Never!

So, in my journey to learn Python, I have secretly hoped to find a teacher or a method that would help me bridge memory (vocabulary) and true understanding. Professor Severance uses tons of analogies to transmit information. That is priceless. Not only it is good for memory but also to grab and truly understand concepts.

 

This is not a regular class. This is a class where you’re supposed to learn something.

 

His teaching approach is quite unique and his pedagogy is among the best I have seen in my years in school. For instance, he emphasizes the human aspect of learning.

 

Accept the fact that you are going to be confused. Relax. Enjoy it. — Charles Severance

 

It is impressive that he succeeds in “connecting” with the audience given that it’s an MOOC (Massive Open Online Course). The last time I attended a MOOC, classes lasted one hour or even a little longer. The camera was at the end of the auditorium and the teacher was giving a monologue. In Programming for Everybody, Professor Severance talks directly to the camera and you will find moments when he asks you to try something (game, video, etc.) during the lecture. There is a pause for you to experiment and then come back to “class”. So, the interactive aspect of the class and the fact that the videos are 30 minutes long or so are definitely a wining combination.

So, if you are new to programming or want to give it another try, here is a great opportunity.

 

Have fun coding and enjoy summer!

 

Dare to begin

Chapter 11: Dictionaries (Notes from Think Python)

Dictionary

Dictionary

 Dictionaries :

It is best to think of a dictionary as an unordered set of  key: value  pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

Source: Python Software Foundation / 5.5 Dictionaries

  • Elements of a dictionary are never indexed.
  • Indices are called “keys”
  • A ” KeyValue ” pair is an Item
  • To add items (Key-Value pairs), we can use [ ] :

>>> eng2span [‘one’] = [‘uno’]
>>> print eng2span
{ ‘one’ : ‘uno’ }   key     value

>>> eng2span = {‘one’:’uno’ , ‘two’:’dos’ , ‘three’:’tres’}

Python uses Keys to look up the corresponding values.

>>> print eng2span [‘two’]
‘dos’

Operators :

  • in : It tells you whether something appears as a Key in the dictionary.
    >>> ‘one’ in eng2span
    True
  • NOTE 1 : Python uses an algorithm called a hashtable for the in operator.
  • NOTE 2 : Hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use integers, called Hash Values, to store and look up Key-Value pairs.
  • TIP : Use Hash with immutable keys.

Built-in functions :

  • len ( ) : works on dictionaries
    >>> len (eng2span)
    3
  • dict ( ) : creates a new dictionary with no items { }

Methods :

  • values ( ) :
    >>> vals = eng2span.values()
    >>> ‘uno’ in vals    #Recall that ‘uno’ is a Value
    True
  • items ( ) : This method returns a list of tuples, where each tuple is a key-value pair.
    >>> d = { ‘a’: 0, ‘b’:1, ‘c’:2}
    >>> t = d.items()
    >>> print t
    [  (‘a’, 0),       (‘b’,1),           (‘c’,2) ]    # List of Tuples
    tuple           tuple             tuple
    key-value     key-value       key-value   #Each pair of key-value is an item.NOTE : The items of the dictionary are in no particular order.

Memo :

In order to keep track of values that have already been computed, we can store them in a dictionary.

[…] A previously computed value that is stored for later use is called a memo.

Source: Think Python by Allen B. Downey

Global Variables :

Variables in _ _main_ _ are sometimes called global because they can be accessed from any function. Unlike local variables, which disappear when their function ends, global variables persist from one function call to the next from any function. They persist from one function call to the next.
Source: Think Python by Allen B. Downey

  • Common use: Use Global Variables for flags, that is, Boolean variables that indicate (“flag”) whether a condition is true.
  • To reassign a Global Variable we have to declare the Global Variable before we use it:
    – been_called = False
    – def example2 ( ):
    – TAB global been_called
    – TAB been_called = TrueNOTE: If the Global Variable is mutable, we can modify it without declaring it.

Dictionaries as a set of counters :

Implentation no1 :
  • Create 26 variables one of each letter of the alphabet.
    – Traverse strings, and chained conditional to increment the corresponding counter.
Implentation no2 :
  • List with 26 elements.
    – Convert each character into a number, using the built-in function ord ( ).
    – Use the number as an index into the list, and increment the appropriate counter.
Implementation no3:
  • Create a dictionary with { character : counters }
    keys            values
  • We could add new items to the dictionary.
  • We could also increment the value of an existing item.

Looping and Dictionaries

  • The for statement traverses the keys of the dictionary.
    – def print_hist (h):   # where variable ‘h’ is a dictionary
    – TAB for c in h :
    – TAB TAB print  c,  h[c]
    key  value

Statements :

  • for

Lookups :

  • Given dictionary ‘d’
  • Given a Key ‘k’
  • Given the corresponding value of k, v   #where variable ‘v’ is a value
  • Forward Lookup : v = d [ k ]
  • No simple syntax to do a Reverse Lookup.

Long integers

>>> fibonacci (50)
12586269025L     #where L stands for Long Integer

Mathematical operators work with long integers, and the functions in the math module, too, so in general any code that works with int will also work with long.

Source: Think Python by Allen B. Downey

Tips for Debugging bigger datasets :

  •  Scale down input
    – Edit the files themselves
    or
    – Modify the program to read only the first n lines
  • Check summaries and types
    – Print summaries of the data: Number of items in a dictionary ; Total of a list of numbers
    – A common cause in runtime errors is a value that is not the right type. TO DEBUG: Print the type of a value
  • Write self-checks
    – Write code to check errors automatically
  • Pretty print the output
    – Formatting debugging output

To finish here is an image to visualize Strings, Lists and Dictionaries.

String / List / Dictionary in Python

String / List / Dictionary in Python

 

Olé to you nonetheless just for having the sheer human love and stubbornness to keep showing up.

Elizabeth Gilbert – TED Talk

 

Follow Logic Versus Be Logic

Hi there,

I read from cover to cover Allen B. Downey’s book “Think Python: How To Think Like a Computer Scientist”. I was able to follow the logic of the book. However, I realized that there is a significant difference between following logic and being logic.

I explain. So, as I was advancing in my reading, I had also been practicing with the examples provided in the book. It was actually not that hard … at the beginning. To answer the questions, I had to re-arrange the examples that were used to illustrate the concepts and then answer the questions. Basically, copy-paste with a slight twist. This strategy seemed to workout until Chapter 8.

The problems in Chapter 8 required me to have a complete list of past code blocks, which was fine. However, I could not just twist them a bit and answer the questions. I was wondering when I would be able to start coding by myself, meaning not using the already built code-blocks from the book.

One day as I was reviewing the book’s exercises with my mentor; he asked me this crucial and yet simple question: “Why do you use a for loop“. “Because this is how the book solves it” I replied.

“Understanding the mechanics of a for loop is part of the basics” my mentor concluded.

I then realized that my pledge for this project was to fully understand the logic and concepts behind Python. There was no point for me to surf the contents of the book if I could not swim in them, create with them.

That day, my mentor and I had a brainstorming session. The goal was to make coding logic part of me. So, we came with this curriculum:

  • Algorithms I
  • Algorithms II
  • Object orientation
  • Project

At all levels, practice will predominate.

For the section “Algorithms I”, I found a website ( CodingBat.com ) that helped me start little and let me build coding confidence.

No cheat-sheet; just the problems and my logic! CodingBat.com tests the code block for you. It is rewarding that after a series of tests, you code works.

Aside from the practice problems that my mentor gives me, I am looking for more practice problems. Let me know if you have some.

Happy coding!

***

NEWS:

 

 

***

 

Blue - Shade no1

Blue – Shade no1

Blue - Shade no2

Blue – Shade no2

Blue - Shade no3

Blue – Shade no3

 

 

 

Chapter 10: Lists

 

Lists illustration

Lists illustration

 

List :

A list is a sequence of values […] The values in a list are called elements or sometimes items.

 

Syntax:

[ 1,  2,  [ ‘three’,  ‘four’ ],  5  ]

  • Lists’ elements can be: int, strings, float, other lists
  • Lists may be nested.
  • Lists are mutable:
    • >>> numbers = [17, 123]
    • >>> numbers [1] = 5
    • >>> print numbers
    • [17, 5]

 

List Assignment :

  • We can assign list values to variables.

>>> cheeses = [‘Brie’, ‘Jarlsberg’, ‘Gouda’]    #Variable cheeses gets a list value
>>> numbers = [17, 123]    #Variable numbers gets a list value
>>> empty = []    #Empty list    #Variable empty gets a list value
>>> print cheeses, numbers, empty

[‘Brie’, ‘Jarlsberg’, ‘Gouda’] [17, 123] []

 

Boolean operators that work with Lists :

  • in
  • is

 

Traversing a list :

  • for loop

for i in cheeses:
TAB print i

 

To write or update the elements on a list :

  •  To write or update the elements in the list, we work with indices:

 

For Loop Traversing List

For Loop Traversing List

 

NOTE: “A For loop over an empty list never executes the body”

 

Python List update

Python List update

 

Operations that apply to lists :

  • + (concatenation)
  • * (multiplication)

 

List slicing :

List slicing

List slicing

 

 

List methods :

 

  • append : adds a new element to the end of a list
    >>> t = [‘a’, ‘b’, ‘c’]
    >>> t.append ( ‘d’ )
    >>> print t
    ‘a’, ‘b’, ‘c’, ‘d’

 

  • extend : takes a list as an argument and appends all of the elements
    >>> t1 = [‘a’, ‘b’, ‘c’]
    >>> t2 = [‘d’, ‘e’]
    >>> t.extend ( t2 )
    >>> print t1
    ‘a’, ‘b’, ‘c’, ‘d’, ‘e’
    NOTE: t2 was left intact/unmodified

 

  • sort : arranges the elements of the list from low to high

 

  • capitalize :

The method capitalize() returns a copy of the string with only its first character capitalized. For 8-bit strings, this method is locale-dependent.

Source: Tutorials Point / Python String capitalize() Method

 

  • split: breaks a string into words

 

  • join:

[The method] join is the inverse of split. It takes a list of strings and concatenates the elements.

[NOTE] join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter.

 

Python split method

Python split method

 

  • pop: “modifies the list and returns the element that was removed”
    It works with indices. If no index, then the pop method deletes and returns the last element.

 

  • remove: This method is useful ” if we know the element we want to remove but not the index”.
    NOTE: The return value of remove is None.

 

del statement :

  • del: modifies the list and returns the elements that were not removed.

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting

Source: http://www.tutorialspoint.com/python/python_lists.htm

 

Built-in functions :

 

  • sum :
    >>> t = [1, 2, 3]
    >>> sum ( t )
    6#6 is the combination of the sequence elements

 

  • list :  breaks a string into individual characters (elements)
    >>> t = ‘happy’
    >>> x = list ( t )
    [‘h’, ‘a’, ‘p’, ‘p’, ‘y’]#6 is the combination of the sequence elements

 

 Conversion :

 

Conversions: Python List - Strings

Conversions: Python List – Strings

 

 Object and Values :

List: Objects and Values

List: Objects and Values

 

To verify whether two variables refer to the same object, we can use the Boolean is operator:

>>> d = [1, 2, 3]

>>> g = [1, 2, 3]

>>> d is g
False

 

Logic:

  • Variable d is equivalent to variable g because they have the same element.
  • Variable d is not identical to variable g because they are not the same object.
  • If two objects are identical, then they are also equivalent.
  • If two objects are equivalent, they are not necessarily identical.

NOTE: An object has a value.

 

Aliasing :

An object with more than one reference has more than one name, so we say the object is aliased.

 

>>> a = [1, 2, 3]

>>> b = a

>>> b is a
True

  • “If the aliased object is mutable, changes made with one alias affect the other”

 

Aliasing

Aliasing

 

Beware, working with mutable objects and aliasing is error-prone. For immutable objects (like strings), aliasing is not much of a problem.

 

***

Acknowledgments :

These notes represent my understanding from the book Think Python: How to Think Like a Computer Scientist written by Allen B. Downey.

Part of the chapter is transcribed and all the quotes unless specified otherwise come directly from his book.

Thank you Professor Downey for making this knowledge available.

 

Also, I would like to thank the open source community for their valuable contribution in making resources on programming available.

Thank you