Archive

Posts Tagged ‘JavaScript’

Learning Python and Ruby – Card Object

Let’s work on a personal favorite of mine – Card and Deck objects. This will be the first time I will make an object in Python and Ruby.

The Card object represents a playing card. It has a rank value, a suit value, and a string representation. This will be used later with a Deck object.

JavaScript

function card(rank, suit) {
    this.rank = validateNumber(rank, 12);
    this.suit = validateNumber(suit, 3);
    this.value = cardToString(this.rank, this.suit);
};

function validateNumber(nb, max) {
    if (!isNaN(nb) && nb >= 0 && nb <= max) {
        return nb;
    }

    return Math.floor(Math.random() * (max + 1));
};

function cardToString(rank, suit) {
    var ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'];
    var suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds'];

    return ranks[rank] + ' of ' + suits[suit];
};

Python

import random

class Card:
    """ Defines a Card object """
    def __init__(self, rank=None, suit=None):
        self.rank = validateNumber(rank, 12)
        self.suit = validateNumber(suit, 3)
        self.value = cardToString(self.rank, self.suit)

def validateNumber(nb, maximum):
    """ Validates a number from 0 up to a specified maximum, or a random one """
    try:
        if nb >= 0 and nb <= maximum:
            return nb
    except:
        pass

    return random.randint(0, maximum)

def cardToString(rank, suit):
    """ Returns the string representation of the specified rank and suit """
    ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
    suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']

    return '{0} of {1}'.format(ranks[rank], suits[suit])

Ruby

class Card
    def initialize(rank=nil, suit=nil)
        @rank = validateNumber(rank, 12)
        @suit = validateNumber(suit, 3)
    end

    def value
	cardToString(@rank, @suit)
    end
end

def validateNumber(nb, maximum)
    if nb.is_a?(Numeric) and nb >= 0 and nb <= maximum
        return nb
	end

    rand(maximum)
end

def cardToString(rank, suit)
    ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
    suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']

    "#{ranks[rank]} of #{suits[suit]}"
end

As you can see from the code, you can create a new random card by specifying no argument, or create a specific card with the appropriate arguments (if you know the code). The code handles invalid argument values, in which case it generates a random value. This is probably a bad practice, as it would not yield the expected result, but it’s a pretty simple example, and I’m not into error-handling yet. To create a Card object, you can use new card() in JavaScript, Card() in Python, and Card.new() in Ruby.

Writing the code in JavaScript was pretty straightforward, but I had to do a bit of research in order to implement the Card object in Python and Ruby. I learned that in Python, you usually don’t check for type, but use a try-except to catch the error if the variable wasn’t of the type you wanted. In Ruby, there is a difference between a single-quote string, and a double-quote string – double-quotes are for string that could get some modifications inside, such as the #{} formatting. And, although I am not completely sure why, I had to take the Card’s value property and take it out of the initialize() method. Finally, I noticed that Python and Ruby are more object-oriented than JavaScript.

Categories: Programming Tags: , ,

Learning Python and Ruby – Fibonacci

Oh, the classic Fibonacci.

Just in case: the Fibonacci series is made up of the numbers which are the sum of the two preceding numbers, starting with 0 and 1. The first Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …

JavaScript

// Returns the Fibonacci number at position index. Zero-based.
function getFibonacciNumberByIndex(index) {
    if (index < 0) {
        return null;
    }
    else if (index == 0) {
        return 0;
    }
    else if (index == 1) {
        return 1;
    }
    else {
        var i = 1;
        var prev = 0;
        var cur = 1;
        while (i < index) {
            var temp = prev;
            prev = cur;
            cur += temp;
            i++;
        }

        return cur;
    }
};

/*
Returns the list of all the Fibonacci numbers
up to and including the index argument.
*/
function getFibonacciList(index) {
    if (index < 0) {
        return [];
    }
    else if (index == 0) {
        return [0];
    }
    else if (index == 1) {
        return [0, 1];
    }
    else {
        var list = [0, 1];
        var i = 2;
        while (i <= index) {
            list.push(list[i - 2] + list[i - 1]);
            i++;
        }

        return list;
    }
};

Python

# Returns the Fibonacci number at position index. Zero-based.
def getFibonacciNumberByIndex(index):
    if index < 0:
        return None
    elif index == 0:
        return 0
    elif index == 1:
        return 1
    else:
        i = 1
        prev = 0
        cur = 1
        while i < index:
            temp = prev
            prev = cur
            cur += temp
            i = i + 1

        return cur

"""
Returns the list of all the Fibonacci numbers
up to and including the index argument.
"""
def getFibonacciList(index):
    if index < 0:
        return []
    elif index == 0:
        return [0]
    elif index == 1:
        return [0, 1]
    else:
        list = [0, 1]
        i = 2
        while i <= index:
            list += [list[i-2] + list[i-1]]
            i = i + 1

        return list

Ruby

# Returns the Fibonacci number at position index. Zero-based.
def getFibonacciNumberByIndex index
    if index < 0
        nil
    elsif index == 0
        0
    elsif index == 1
        1
    else
	i = 1
	prev = 0
	cur = 1
	while i < index
	    temp = prev
	    prev = cur
	    cur += temp
	    i = i + 1
	end

	cur
    end
end

=begin
Returns the list of all the Fibonacci numbers
up to and including the index argument.
=end
def getFibonacciList index
    if index < 0
        []
    elsif index == 0
        [0]
    elsif index == 1
        [0, 1]
    else
	list = [0, 1]
	i = 2
	while i <= index
	    list += [list[i-2] + list[i-1]]
	    i = i + 1
	end

	list
    end
end

Right there, I have to admit that Python code looks clean and elegant. I’m sure I will get used to indentation-scopes pretty quickly. JavaScript looks cluttered, but more professional. I’m currently having mixed feelings about Ruby, mostly because of the end that mar the elegant feel it would otherwise have.

Aside from some list operations, I learned about the null equivalents: None in Python, and nil in Ruby. I also learned about comments: // and /* … */ in JavaScript, # and “”” … “”” in Python, and # and =begin … =end in Ruby. The multi-line comments in Ruby look terribly weird, more similar to how you define regions in c#. Also, and I did it by design to show consistency, there are docstring in Python – the first line following a definition can (and should) be a multi-line comment describing what it’s supposed to do.

Categories: Programming Tags: , ,

Learning Python and Ruby – Basic Flow Control

Getting the hang of very basic flow control: branching, for-looping, and while-looping.

JavaScript

if (number > 0) {
    alert('Number is positive.');
}
else if (number == 0) {
    alert('Number is zero.');
}
else {
    alert('Number is negative.');
}

Python

if number > 0:
    print('Number is positive.')
elif number == 0:
    print('Number is zero.')
else:
    print('Number is negative.')

Ruby

if number > 0
    puts 'Number is positive.'
elsif number == 0
    puts 'Number is zero.'
else
    puts 'Number is negative.'
end

Nothing new here, except that the elif and elsif are a bit weird to use. Noteworthy is Ruby’s unless statement – it is exactly like an if statement, but the condition is inverted.

Other branching alternatives include the switch in JavaScript, and the case in Ruby.

 

JavaScript

var list = ['Google', 'Bing', 'Duck Duck Go'];
for (var i in list) {
    alert(list[i]);
}
for (var i = 0; i < list.length; i++) {
    alert(list[i]);
}

Python

list = ['Google', 'Bing', 'Duck Duck Go']
for i in list:
    print i
for i in range(len(list)):
    print list[i]

Ruby

list = ['Google', 'Bing', 'Duck Duck Go']
list.each do |i|
    puts i
end
for i in 0..list.length-1
    puts list[i]
end

The first loop is looping through the objects of a list, while the second is looping through the indexes. It is to be noted that in Javascript, i is not a reference to the current object, but the index in the list. You have to manually get the current object (list[i]) if you want the reference. In python, a for-loop is normally iterating through a list – to iterate through numbers, you can use range(5) to iterate from 0 to 4. The equivalent in Ruby is 0..4, and you iterate through a list by using the .each method of the list.

I think the Javascript for-loop is the most powerful, while the Python’s is the easiest on the eyes. I wish the len() was a list property, though.

 

JavaScript

var i = 0;
while (i < 4) {
    alert(i);
    i++;
}
do {
    alert(i);
    i++;
} while (i < 8);

Python

i = 0
while i < 4:
    print(i)
    i = i + 1

Ruby

i = 0
while i < 4
    puts i
    i = i + 1
end
begin
    puts i
    i = i + 1
end while i < 8

The first loop is a while loop, and the second is a do-while loop. The difference is that the do-while loop does at least one iteration – it goes in before testing the condition. I did not find any do-while loop in Python, which reinforces the belief that Python is a very simple programming language to use. On Ruby’s side, the while loop looks very normal, but the do-while seems to be made from a begin-end scope, with a while condition appended to the end. This looks weird to my eyes. Ruby also has an until statement and modifier, which are exactly like the while and do-while statements, but with the condition inverted.

I tend to avoid these spaghetti code generators if I can, but break and continue can be used in JavaScript to break out of the innermost loop, or stop the current iteration and continue with the next one. What’s available in Python and Ruby? Python has both break and continue. Ruby has break and next, but also has redo which restarts the current iteration (skipping the condition check), and retry which restarts the whole loop, from the beginning. All these (in Ruby only) can be appended a condition, eg. break if i == 7.

I have the feeling that Python is trying to be simple, as Ruby is trying to be more like a spoken language. I’m not used to such programming candies such as, for example, redo and while / until. I use some code to programmatically simulate the if condition of a break. I’m not yet sure if I should be irritated by these, or just be glad and use them.

Categories: Programming Tags: , ,

Learning Python and Ruby – First Impressions

To get first impressions, I’ll start with something really easy. A method that returns the age of a person, in seconds. Given age in years, the algorithm would look like age × 365.242199 days/year × 24 hours/day × 60 minutes/hour × 60 seconds/minute. The number of days per year was given by Google.

JavaScript

function ageInSeconds(age) {
    return age * 365.242199 * 24 * 60 * 60;
}

Python

def ageInSeconds(age):
    return age * 365.242199 * 24 * 60 * 60

Ruby

def ageInSeconds age
    age * 365.242199 * 24 * 60 * 60
end

 

So far, JavaScript is closest to C#, my current language of choice. The lines are clearly delimited with a “;” and the function scope is clear. The variables are weakly-typed, which means that they can change type during the execution of the code. This can be useful, but the source of many errors.

In Python, a “:” indicates the start of a scope. I think it weird that a language using carriage returns for line terminators could not use it here (I’m sure there is a reason, though). There is no scope termination, because the indentations define where the scope will end. To me, this is not only confusing, but illogical. The variables are strongly-typed, but are not declared.

In Ruby, the arguments are just put together like a phrase (which feels weird), there is no line terminator, and what the function returns is actually the last line encountered (this brings back some Crystal Reports nightmares). Like Python, Ruby variables are strongly-typed but are not declared. The scope end is specified by end, which reminds me of old Visual Basic times (not good).

 

This first post was more like an introduction to what I intend to do, and a comparison of the languages’ styles. The next posts will be centered around differences of feel, and differences in implementation.

Categories: Programming Tags: , ,

Learning Python and Ruby

I want to learn Python. Actually, if I recall correctly, I had a quick course on Python at the university, but that was millions of years ago.

So, I want to learn Python. And Django. I plan to make my web site(s) from that. Thing is, I had to choose between Python/Django and Ruby/Ruby on Rails. In the end, Python won over Ruby because 1) it seems more popular, and 2) I like Monty Python. Moot point.

I was flipping through the Python tutorial pages when I had a crazy idea (I must have been too concentrated in my learning).

What if I learned both languages at the same time? You get double the work load, double the brain activity, double the learning curve, and in four years, instead of being a master in one of them, I’ll still be struggling and mixing both. Crazy idea indeed. I like it.

In comparison charts, Python and Ruby are often compared together with PHP. Unless they are comparing the web scripting capabilities, I’m at a loss here. From the little I’ve seen so far, it would be easier to compare Python, Ruby, and EcmaScript. I already know Javascript (which is based on EcmaScript), so I could code and compare functions, and give my comments from there. When I’ll move on to making web pages, I’ll check PHP.

In the following days, weeks, or months, I will compare JavaScript, Python, and Ruby. I will not write tutorials on how to learn these languages, as I assume an easy knowledge of programming (C# or JavaScript will do nicely). That means I will not go into details about operators and other basic stuff that should be fairly easy to learn at a glance.

Categories: Programming Tags: , ,