javascript and python’s range()

So in python, you can use a function called range() to (conventionally – I know there are other uses) easily iterate over, yknow, a range of numbers or through a list/array/yaddayadda. It works like this:

for i in range(13): # you can also limit it on the lower bound, a la range(7,13), 
    print i         # but be ye wary of yon fenceepostee

While going through some javascript tutorialling, I found a typical learner problem that I found later that I’d been approaching the wrong way, but if you’ll bear with me & restrain thyself from punching angrily through your computer/rotary telephone, COME WITH ME ON THIS JOURNEY:

For a Rock Paper Scissors game, lesson 11 or 12 of the Functions lesson of Codecademy‘s javascript class, it asks the student to use a randomize function (Math.random()) to call “rock” when the first third of the number, “paper” when the second, and “scissors” when the third. My FIRST thought was to use a range function, like if i in range(.33) and if i in range(.34,.66)! So I tried a couple of different syntactial approaches that seemed javascriptey, they didn’t work, so I went a-googlin’ (how you do) and found the following solution:

Array.apply(null, Array(5)).map(function (_, i) {return i;});

I know I’m new to javascript, but that is honestly barely parseable. I’m not here to wail about things that one language does that another doesn’t, but this was a difference that frustrated me – – until (and you patient few, I know you’ve been waiting for this) I realized that there’s another way to solve this problem! And that’s the beautiful thing about programming, particularly learning different languages. I remember using this syntax in other learning situations, back in the day when I first learned Python. The resolution is to use the (javascript) format of:

if (i < .33) {
    return "computer chose rock";
else if (i <= .66) {
    return "computer chose paper";
} else {
    return "computer chose scissors";

which looks (save the curly braces, ;, & s/else_if/elif) nearly the same as pythonic syntax.

MORAL OF THE STORY: there are many ways to do many different things! fabulous!


8 thoughts on “javascript and python’s range()

  1. The more traditional thing to do here:

    switch(Math.floor(i * 3)) {
    case 0:
    return “computer chose rock”;
    case 1:
    return “computer chose scissors”;
    case 2:
    return “computer chose paper”;

    Even better would be:

    var choices = [“rock”, “scissors”, “paper”];
    return “computer chose ” + choices[Math.floor(i * 3)];

    • Cool, I shall have to check out `Math.floor`. I’m also thinking of the python `random` module that would just pick one really nicely for us, even if it’s not ACTUALLY that random πŸ˜‰

      • Check out the First and Second International Computer Rock Scissors Paper Contests, run by a friend of mine a while back. Full of interesting stories.

      • The only thing to remember is that because of the floor (and, in some edge cases, how JavaScript handles floats), this doesn’t give you a uniform distribution. For places that you don’t care too much about that, though, Math.floor(i*3) works fine.

      • How does Javascript handle floats as opposed to Python? And until I’m in production, a weak pseudorandom function is fine for my needs, at which point I will rewatch PO8’s excellent talk from OSBridge on randomness!

        also hi will!

      • Hi Rachel! Neat blog! Python actually does this too (I only just found out). Try this out:

        console.log(.1 + .2 === .3);

        or in Python: print .1 + .2 == .3

        It comes back false! WTF! If we look at exactly what’s going on we see that .1 + .2 actually equals 0.30000000000000004, because reasons:

  2. Pingback: For loops in Javascript | Rachel Learns to Code
  3. Will: The floor() was carefully chosen to give a uniform distribution, up to floating-point error. Note that traditionally 0 <= random() < 1.0, so floor() essentially matches this. There's nothing sensible that can be done about floating point error here unless you can get your hands on the raw bits from the PRNG and use a rejection method. In any case, the PRNG is probably terrible compared to these sources of error anyhow. πŸ™‚

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s