Skip to main content

Hurrah-ndom inventions



Like humans, robots need to be intelligent.  Rational.  Trustworthy.

But that sounds way too complicated, and more importantly, extremely boring.  So let’s make them do random stuff instead, and learn a bit about programming on the Pi along the way.

Here, we’ll write a little Python program to allow Rosie to make random suggestions.  Specifically, we want her to tell us what we should be inventing next.

You will need to have these:

  • Raspberry Pi 3, and Raspbian running on SDHC card
  • A computer from which you are connecting to the Raspberry Pi remotely 

You will need to have done these things:

  1. I’ve got Pi(3) brain
  2. Why-Fi-ght the Wi-Fi?

You will need to do this:

  • Create a Python application and use the random module
  • Populate your lists with words (be creative!)
  • Run the application and (possibly) be amused by the results

What do you get after all this?

We learnt previously that Operating Systems - in our case the Linux-based Raspbian OS - allow us to interact with hardware.  But the OS alone won't provide Rosie with any real intelligence.  She'll in fact just sit there, unloved.. doing nothing.  Zero.  Nada.

Now, drum roll please...  Enter the real guardians of the entire galaxy.  Computer Programs (or code, or scripts, or software, or applications, or whatever else people like to call them).  These things contain rules and logic - described in computer languages - that allow us to process input, and afterwards, provide (hopefully useful) output.

Like actual languages (English, español, 日本語, русский + hundreds more), there are many different Programming Languages which are ways in which to write programs.  They all have strange names, like C, C++, PHP and Java.  We will use one called Python for Rosie.  It's widely used.  It's powerful.  And - rather helpfully - it's already there on Raspbian OS, ready to be used.

And just to prove that we can start to make use of Rosie's brain, we will create an amazingly useful program.  Actually, let's not.  Let's create a silly little program - and it really is little with less than 20 lines of code - that randomly selects words from some lists and presents them back to us as a world-changing suggestion.  Is it actually of any use?  Most likely not.


But on second thoughts… Rosie might actually need to make random choices sometimes.  Like where to go if she’s stuck or bored.  Or what shapes to throw on the dance floor.  In a way, just like humans.

This is simply too much detail:

As they say, let's cut to the chase.  This is the Python code that we will attempt to run on the Pi:


But hang on a second.  WHERE?  HOW?

Python applications consist of files that contain - guess what? - Python code.  So let's get back to the SSH terminal that we started during our previous post and create the Python file that we need.

pwd
...checks that we are in the /home/pi directory (the home directory of the 'pi' user)
cd rosie
...changes to the 'rosie' directory we created previously.  This is where we'd like to store this Python application.
ls
...lists items in this directory.  Anything there?  No, so let's create our Python application file.
touch rosie_random.py
...touch command creates an empty file.  Let's create one called 'rosie_random.py'.  The '.py' extension generally means it is a Python file.
ls
...check that the rosie_random.py file has been created


 
Great!  We now have our file, but it's empty (we did warn you about this).  Let's use our old friend 'nano' to edit it.

nano rosie_random.py
...opens the rosie_random.py file using the nano text editor.  We used this when editing the Wi-Fi configuration file, remember?

Now copy and paste the 16 lines of code from above and paste them into the nano window.  On Putty, a 'right click' on the mouse allows you to paste the text that you have just copied.  If successful, your nano editor should look like this:


Once you're happy with the lines you've just pasted in, save the file and exit nano using control-x (control and x keys pressed together), 'y' key at next prompt and 'enter' when confirming the filename.

We're all set to go.  Let's run the program using Python* and see what happens.

*We will be using Python version 2 (Python 2) in this series.  We'll move onto using the latest and greatest version of Python (Python 3) at the start of the next series.  Python 2 won't be around for much longer.

python rosie_random.py
...runs the application code stored in the rosie_random.py file using Python


Tip: Pressing the 'up' or 'down' arrow keys will allow you to cycle through previous commands you have already executed.  Useful, when you want to quickly see Rosie's other suggestions.

There!  A Python program has suddenly made Rosie very useful.  A 'banana polishing three-wheeled eel' will change lives for the better, and win you the Nobel Prize.

But what was it that we just copied and pasted?  How did the code work?  Let's step through each bit.

from random import randint

We import Python modules and their functions whenever we want to recycle bits of existing code.  Here, we want to use the randint() function from the random module.  Someone has kindly written these modules for us and made them available for use in Python - it would be ungrateful not to use them.

OBJECTS = ["banana", "squirrel", "fire", "ice-cream", "coconut"]
ACTIVITIES = ["munching", "farting", "prodding", "detecting", "polishing"]
GADGETS = [
    "robotic squirrel",
    "mechanical dinosaur",
    "three-wheeled eel",
    "rechargeable owl",
    "battery-powered raccoon"
    ]

Next, we set up three list data structures in which to store our words.  This will be our data.  Feel free to modify and add words as you please.

print("Silly human, invent me a")
print(OBJECTS[randint(0, len(OBJECTS)-1)])
print(ACTIVITIES[randint(0, len(ACTIVITIES)-1)])
print(GADGETS[randint(0, len(GADGETS)-1)])

Lastly, we will use the print() function to display a random word from each list on-screen.  But, actually, there’s a few more things going on here:
  • len() function is used to establish how many words are stored in each list
  • Subtracting one from the len() result is required as 0 actually points to the first position (word) in the list.  Therefore, the last position is number of words - 1.
  • randint() function is then used to generate a random number (also called integer) between the first and last positions of the words in the lists.  This will be the position of the chosen word in the list.
  • And finally, the words are retrieved from the lists using their positions
You may have also spotted the ’#’ symbol whenever we were making comments in the code.  These lines are ignored by Python, but are useful to us humans who quite often forget what we've written (or eaten that morning).

We admit it.  This application is pointless.  It's daft.  We could've come up with those suggestions ourselves.  But we now know how to create a Python application and run it on the Pi.  And this, is making Rosie - and the Pi - ever more useful.

Even more reading:

The Python random function is described in official Python documentation:
https://docs.python.org/3/library/random.html

Comments

  1. Thanks for the fun toot-oreo.

    Python seems so ugly at times like:
    print(OBJECTS[randint(0, len(OBJECTS)-1)])

    I compulsively modified rosie:
    [Code]
    """Module to randomise silly inventions"""

    # Import the randint function from the random module
    from random import randint

    # Populate some lists with words
    OBJECTS = ["banana", "squirrel", "fire", "ice-cream", "coconut"]
    ACTIVITIES = ["munching", "farting", "prodding", "detecting", "polishing"]
    GADGETS = [
    "robotic squirrel",
    "mechanical dinosaur",
    "three-wheeled eel",
    "rechargeable owl",
    "battery-powered raccoon"
    "one-eyed rosie"
    ]

    # Define a randListElement(list)
    def randListElement(sourcelist):
    return sourcelist[randint(0,len(sourcelist)-1)]

    # Randomise the output
    print("Silly human, invent me a")
    print( randListElement(OBJECTS) )
    print( randListElement(ACTIVITIES) )
    print( randListElement(GADGETS) )
    [/code]

    ReplyDelete
  2. and then I "read the manual"...

    from random import choice

    print( choice(OBJECTS) )

    a double thank you - I can be patient... or will be a patient.

    ReplyDelete
    Replies
    1. Hi there. Thanks for this! I never knew there was a choice() function hidden away in the 'random' module. It sure tidies this up a bit.

      Delete

Post a Comment

Popular posts from this blog

Tea minus 30

We're fast approaching Christmas time.  And if robots were to make one simple observation about the human species during the Christmas festivities, it's that they watch a lot of TV.  A LOT.  Often, accompanied by an inappropriate amount of greenhouse gas-producing food.  Stuff you don't normally eat during the remainder of the year - for good reason.

And most so-called shows on TV are boring to robots like Rosie.  After all, why watch a minor subspecies of the human race - celebrities - stumble awkwardly around the dance floor, dressed like a faulty, sparking circuit board?  Such branch of entertainment doesn't require robots to engage any of their proud circuitry.  Their processors remain idle.  Memory under-utilised.

But if robots are to be part of people's homes (and blend in), they need to look at least a little interested in some of this irrational nonsense.  Nobody likes a party pooper.  A killjoy.  And this is where a certain subgenre of TV entertainment co…

Beam me up, Rosie!

How do you get from A to B?

You can't, as As and Bs are just letters in the alphabet. But if A is your house, and B is a meerkat village at your favourite safari park, you'd probably use a device equipped with GPS.  Not to be confused with UPS, who will deliver you your chosen meerkat through the post. And why on Earth would Rosie Patrol need one? Precisely, it's because she is on Earth that she needs one. Because our planet is rather big. Big enough to get lost in. And we don't want to lose our friendly plastic boxes on wheels. And maybe, eventually when she's clever enough, she'll go and defeat baddies on her own. And return home afterwards for a well deserved Earl Grey tea.

Besides, why wouldn't we want to add another three letter acronym to Rosie Patrol's repertoire?
All superheroes need:One Raspberry Pi 3, running Raspbian OSComputer from which you are connecting to the Raspberry Pi Probably the most important bit: a GPS receiver thingmy. …

Raspberry bye, hello

Let us make this very clear from the onset of this exotic excursion.

This is not a case of Raspberry Bye. Our relationship with our favourite single-board computer hasn't at all soured. In fact, we've become wholly inseparable. There's been many months of undeniable fun that's been had with the venerable computer strangely named after an edible fruit. To the extent that our relationship requires a healthy break. And quite frankly, our Pis require a well earned summer holiday to do whatever it is that robots and computers do during their time off. Crash. Burn. Refuel (with questionable toxins). Not at all unlike their human counterparts. And ultimately, it would be nice if they could return to a brand new, adorable pet waiting for them at home, a likeable little companion that they can just get along with.

Well, we visited a pet shop, but couldn't find anything as small and smart as this adorable pup we stumbled up on while searching the Internet for a new, miniat…