Category Archives: IT

Project Euler

I started doing the project Euler exercises as a test of my algorithms. I will be posting here my results.

 

  • sum the numbers betwwen ]0 , 1000[ that are multiples of 3 or 5
my $i =0;
my $total = 0;
while ($i <1000)
{
 if (($i % 3 == 0) || ($i % 5 == 0))
 {
 $total += $i;
 }
 $i++;
}
print $total;
  • sum the even numbers in the fibonacci sequence that do not exceed 4’000’000

 

use Data::Dumper;
my @numbers = (1,2);
my $total = 0;
my $temp = 0;
while ($temp < 4000000)
{
$temp = $numbers[-1] + $numbers[-2];
push @numbers, $temp;
}
foreach my $tmp (@numbers)
{
 $total += $tmp if $tmp % 2 == 0; 
}
print Dumper $total;

Creative Commons

Yesterday, the EPFL library held an event to commemorate the 10th anniversary of Creative commons. This was very interesting, because although I have worked with the Gnu GPL, MIT and BSD licenses, these three are only valid when it comes to programs, even if it includes video games.

There is of course a major difference between Mr. X handing out free copies of THE game, which the users are free to redistribute but not modify not investigate, and Mr. Y, who hands out both a copy of his text managament software along with the source code. This distinguishes thus between freeware (or shareware) and open source software. But, what happens with a picture? A movie? A song? You can’t give the source code to a picture, specially one taken with a 35mm. You can’t hand out the source code to a movie, and you certainly can’t hand out the source code to a song.

Opposing argument #1: Most cameras allow for RAW image filetypes. REBUTTED as this file can be considered and integrate part of the picture, and not a source. #2:  You can hand out the script to a movie. REBUTTED, yes, you can hand out the script for a movie, but there is so much more behind it. Casting, special effects, make-up, sound, you can’t create the same movie without the exact same ingredients.  Argument #  3: You can hand out the score to a song. True, BUT, just in the same way as for #2, it won’t sound exactly the same. Just like no 2 concerts from the same band sound exactly the same.

Enter copyright: The moment you hit save on your file, you have the authority over your document / picture / song / other, with no need to tell any one about it, (simply placing the little copyright logo is enough). This makes sense, if Mr. Doe, decides to write a book, he doesn’t want his neighbor to print it & sell it. After all, it is Mr. Doe’s work. Makes sense, right? But this is where copyright laws resemble the patent system:
Rather than generate a drive for innovation & creation, these laws restrict people’s freedom. Quoting a book becomes virtually illegal, and Mr. Doe’s book is not getting much attention. His neighbor needs to borrow some passages in order to teach his Perl class, as the passages are insanely simple to understand. However, rather than write a new book about a new topic (such as, for example, copyright law), Mr. Doe is busy in court suing his neighbour for every last penny.

Enter Creative Commons: Mr. Doe’s book is not selling very well in his hometown, but a small village in Scandinavia is asking for copies. Mr. Doe decides to sell his book for a small price in electronic format to said village. Feeling that the book truly brings a better education to their children, as well as access to better tools thanks to it, the village decides to buy the book for around $10 per head.

“Whoah” exclaims Mr. Doe. “I can publish the document myself, and all I need to do is state what can and what can’t be done with my content? … Awesome”.

In short, the advantages are the following:
Decide what can and what can’t be done with your workl (can it be reused, rehashed, used in a commercial for the man?)

 

Given the advances of technology, soon interactions will be entirely via computers, and artists are already taking a lead in this bandwagon of collective art creation. Without Creative Commons, the artist would have to ask each individual participant for the authorization to use whatever media it is being created. Win – Win if you ask me.

Why Perl is better than Python

Many people around me go on about how Python is better and easier to read and write than Perl.  I gave it a try with using Invent with Python. The 2nd piece of code made python crash due to a lack of backwards compatibility. Okay, every language does this, every now and then, but the code here was so small that crashing the shell seems as though there was an error.

print('Guess')
input()
import random

guess = 0

print ('What is your name?')
myName = input()

number = random.randint(1, 20)

print ('Well, '+ myName + ', I am thinking of a number between 1 and 20.')

while guess < 5:
    print ('Take a guess.')
    G = int(input())

    guess += 1

    if G < number:
        print ('Too low')
    if G > number:
        print ('Too high')
    if G == number:
        break

if G == number:
    guess = str(guess)
    print ('woo, you found it in '+guess+' turns.')

if G != number:
    number = str(number)
    print ('nope, twas ' + number)

Admittedly, I have had the most experience with Perl and its data structures.  However, experience is not an argument when it comes to comparing programming languages. The main argument I get thrown in favor of Python, is its readability. This in itself separates into the Python BLOCK syntax, as well as its general syntax.  Python doesn’t use curly braces {} to separate blocks, but rather indentation, often 8 spaces although certain schools recommend 4.  Moreover, Python has no instruction separator, other than EOL. Sure, on a script running many hundreds of lines, you’ll be happy the interpreter/compiler doesn’t snap back at you because of a missing “;”. However, you can also create a macro in Vim or Emacs or whichever editor of your choice to add a semicolon if an EOL is encountered outside of certain conditions (single/double quotes, heredocs, etc.).

The second argument of readability, is due to Perl’s capacity of inserting functions within functions.  However, when writing code the second thing to be thinking of is future you debugging said code to figure out WTH line 357 means. If line 357 is within a block, Shouldn’t there be some instruction as to what said block does? The same goes for subroutines and modules. Clutzy coding will ALWAYS lead to headaches. And while you might be writing code for a company where you’re not sure to be kept in order to maintain it, mixing reg-ex with functions can make it difficult if not impossible to understand from day to day.

These are the arguments I received from other programmers, and I feel seem almost religious statements from people who have had little to no hands-on with Perl (not that I have hundreds of hours with either, but Python has caused me more headaches). Why I love Perl:
Intuitive, getting a variable to auto-increment is impossible in python with a ++ operator. For someone coming from a basic C training, the ++ is the easiest way to work with loops.
Functional/Procedural based: Here both languages (sort of) even out. While Python is OO based, it isn’t as cluttered as say Java. However, both languages can be used with a fair amount of ease to create simple scripts. However, Perl has the advantage when it comes to complex functions within functions.  All it takes is one comment, and rather than append methods to the methods of objects, Perl allows for the funk-ception to be readable and fast.
Strict/warnings/diagnostics: When i started with Perl, these were the first lines of code I was told had to be everywhere right after the shebang. Typo’s are everywhere. If you use gcc, it will usually act up with bad variable names. Python may crash as well, but Perl, Perl tells you “hey buddy, you made a mistake on line xy, why don’t you go fix that while I take a nap.” Lazy? No. Everyone makes typos, be it a missing $, a trailing symbol before the EOL, so many reasons to have your interpreter help you out.  Exists in Python? You should be able to create a library for that, but then again, in Perl strict checks not only for declaration, but also for declaration within scope => cleaner programming.

It obviously comes down to personal preference, but IMHO, Perl has the upper hand when it comes to the learning curve, the languages capacity of enforcing good practices (well… I guess indentation might win Python a point there), and general community awesomeness.

Why lists are amazing

When I was working on my linguistics project, I ran into a wall. Perl doesn’t allow for dynamic creation of arrays. I had used this feature/bug of the BASH shell during an internship at a theoretical chemistry lab, as it allowed me to create an array, whose elements were dynamically created arrays, named according to whatever variable I felt like.

For example, in the case of a cyclohexane, I could have a condition (if $atom = ‘C’) and then create my array as follows:

Carbon$number=[x,y,z];
$number++;

In Perl of course, the solution was to feed my input text to a function, and create a hash table with the structure word{wordcount} for my key-value pair. However, as it turns out, there is an even more elegant solution: lists.

  • Lists can be accessed as arrays (check)
  • Elements can be added to lists as arrays (check)
  • Elements can be arrays (check)

Of course, for the use I was intending, lists are absolutely useless. I cannot really go through an array writing $words[$cow[$xvar]], (well, it’s feasible, but slightly useless). On the other hand, for generating a dictionary spell-checker (which is a word-LIST) lists would consume far less memory due to the absence of the value partner (useful in the case of memory intensive lists on older systems).

Lists are fairly awesome in their capacity. I have not yet tested if they can be used to replace the STRUCT vartype from C, but if they can, then that is awesome.

Language Statistical Analysis

For one of my IT based courses, I was required to do a project involving computers and language. Very vague requirements, due to the course being aimed at people who have little to no IT baggage (and as it wasn’t a programming course… even more so!) I decided to enjoy it, and therefore write some code.

My initial project was to take various texts from 3 different time periods (all texts in English) and attempt to find word variations through time. The main challenge here would be finding the algorithm to decide how one word becomes another. A friend told me he had a C++ library which would be suitable for this, so I attempted some OO programming (it did not go well). As it turns out, the library he had thought of was useless to me, so I decided to go functional and write everything in Perl.

So, this was the first time I was working with Perl, (previous experience had been to add “echo” functions in already existing scripts) so first I had to decide what I wanted and could do.

  1. Take text from input file and make everything lowercase
  2. Create a table containing each word, the number of times it appears and other statistical elements.

Unlike BASH, Perl doesn’t allow for the dynamic creation of tables, but this is resolved with hash tabled. I therefore ended up with a Hash table, structured: word{word occurrences}.

The next step was to use the numbers, at first I attempted writing subroutines, but when it took me an hour to write a simple function, I decided to look up packages and how surprising that CPAN had a discrete statistics package. The joy! I no longer needed to learn how to do OO (the package did everything for me), and I had no need to write sub routines, as the package gave me all the tools necessary.

After some 20h of coding (to only get 100 lines of code), the conclusion was that the language’s statistics don’t change significantly, and the main changes are:

  • New vocabulary replacing old (computer vs type-writer)
  • Manner of communication (Twitter will have a reduced vocabulary span with respect to Shakespeare’s works, if comparing type-token ratios).

My Perl verdict: definitely a fun language, although requires a large amount of commenting due to its free variable use and regex creation.  I will definitely continue to explore this language.

Much help obtained from PerlMonks