More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

Binary Converter

Did You Know?

Everything that is stored on a computer is stored as binary code. Binary code is made of bits (0 or 1). We often use Bytes to store data. A Byte is made of eight bits and can be used to store any whole number between 0 to 255. Check it yourself, click on the binary digits to create your own binary number:

1286432168421
11111111

128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255

HTML Tags – Drag & Drop

Complete this drag and drop activity to complete the HTML code used to create the page displayed below:

Open this activity in its own window

HTMLPage

<B>
<FONT color=”#FF0000″>
<H1>
</B>
<U>
<CENTER>
</H1>
</FONT>
<A href=”http://www.101computing.net”>
</A>
</U>
</CENTER>
<IMG src=”logo.png” width=”250″/>


Welcome to my webpage
<P>I created this page to learn about HTML.</P>

<P>I love using colour codes to change the colour of textI can also use a tag to underline text.</P>



<P>Find out more about HTML: Visit 101computing.net</P>

CCTV Camera – Motion Detection

RaspberryPi

Getting Ready…

For this challenge you will need:

  • A Raspberry Pi with Python 2 installed,
  • A PiCamera

Follow the steps described on the following pages to make sure you have plugged the camera in your raspberry pi and that you have enabled it. ALso make sure you have installed the picamera library.

You will also need to setup the Python Imaging Library (PIL) which you can download from http://www.pythonware.com/products/pil/.

Alternatively you can type the following code in a terminal window:
sudo apt-get install python-imaging-tk

How It Works


Before we start


Most burglar alarm systems using motion sensors would use Passive Infrared Sensors. It is possible to buy one for the Raspberry Pi. However in this tutorial we will use an alternative approach without using an infrared sensor.

Note that if you need a tutorial based on using a Passive Infrared Sensor use this tutorial instead.

We are going to use a script that:

  1. Takes a picture and saves it in a buffer,
  2. Takes another picture,
  3. Compares the current picture and the previous picture (buffer) by counting the number of pixels which are different,
  4. If the number of pixels which are different between both pictures is greater than a given threshold, we will assume that the camera has detected some movements.
    • In this case, add the date and time to the current picture and store the picture on file.
  5. Replaces the picture stored in the buffer with the current picture
  6. Repeats all the steps above (from step 2).

To do so we will use the following script, from Claude Pageau: Source: https://github.com/pageauc/pi-motion-orig

To stop this script while it’s running press CTR + “C”. This will terminate the program.

# original script by brainflakes, improved by pageauc, peewee2 and Kesthal
# www.raspberrypi.org/phpBB3/viewtopic.php?f=43&t=45235
# modified by Claude Pageau 4-Mar-2014 to include numbering sequence plus dat/lock files for grive script integration
# also made program independent of path and file names.
# You need to install PIL to run this script
# type "sudo apt-get install python-imaging-tk" in an terminal window to do this

import StringIO
import subprocess
import os
import time
import shutil
from datetime import datetime
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

###########  Motion detection settings:
# find the path of the of this python script and set some global variables
mypath=os.path.abspath(__file__)
baseDir=mypath[0:mypath.rfind("/")+1]
baseFileName=mypath[mypath.rfind("/")+1:mypath.rfind(".")]
progname = os.path.basename(__file__)
starttime = datetime.now()
# rightnow =  "%04d%02d%02d-%02d:%02d:%02d" % (starttime.year, starttime.month, starttime.day, starttime.hour, starttime.minute, starttime.second)

# Threshold - how much a pixel has to change by to be marked as "changed"
threshold = 50

# Sensitivity - how many changed pixels before capturing an image, needs to be higher if noisy view
sensitivity = 100

# ForceCapture - whether to force an image to be captured every forceCaptureTime seconds, values True or False
forceCapture = True
forceCaptureTime = 60 * 60 # Once an hour

# filepath - location of folder to save photos 
filepath = baseDir + "google_drive"
if not os.path.isdir(filepath):
  print "%s - creating photo storage folder %s " % (progname, filepath)
  os.makedirs(filepath)

# filenamePrefix - string that prefixes the file name for easier identification of files.  A dash will be added at end as part of formating. 
filenamePrefix = "Deck"

# Lock File is used to indicate photos are added
createLockFile=True
lockfilepath = baseDir + baseFileName + ".sync"

# Use filename sequence numbering instead of date and time
numsequence = True
countpath =  baseDir + baseFileName + ".dat"
startCount = 1000
maxPhotos = 500
showDateOnImage = True

# diskSpaceToReserve - Delete oldest images to avoid filling disk. How much byte to keep free on disk.
mbToReserve = 200
diskSpaceToReserve = mbToReserve * 1024 * 1024 # Keep 200 mb free on disk

# cameraSettings - "" = no extra settings; "-hf" = Set horizontal flip of image; "-vf" = Set vertical flip; "-hf -vf" = both horizontal and vertical flip
cameraSettings = "-vf -hf"

# settings of the full size photos to save
saveWidth   = 1296
saveHeight  = 972
saveQuality = 15 # Set jpeg quality (0 to 100)

# Test-Image settings
testWidth = 100
testHeight = 75

# this is the default setting, if the whole image should be scanned for changed pixel
testAreaCount = 1
testBorders = [ [[1,testWidth],[1,testHeight]] ]  # [ [[start pixel on left side,end pixel on right side],[start pixel on top side,stop pixel on bottom side]] ]
# testBorders are NOT zero-based, the first pixel is 1 and the last pixel is testWith or testHeight

# with "testBorders", you can define areas, where the script should scan for changed pixel
# for example, if your picture looks like this:
#
#     ....XXXX
#     ........
#     ........
#
# "." is a street or a house, "X" are trees which move arround like crazy when the wind is blowing
# because of the wind in the trees, there will be taken photos all the time. to prevent this, your setting might look like this:

# testAreaCount = 2
# testBorders = [ [[1,50],[1,75]], [[51,100],[26,75]] ] # area y=1 to 25 not scanned in x=51 to 100

# even more complex example
# testAreaCount = 4
# testBorders = [ [[1,39],[1,75]], [[40,67],[43,75]], [[68,85],[48,75]], [[86,100],[41,75]] ]

# in debug mode, a file debug.bmp is written to disk with marked changed pixel an with marked border of scan-area
# debug mode should only be turned on while testing the parameters above
debugMode = False # False or True

# Capture a small test image (for motion detection)
def captureTestImage(settings, width, height):
    command = "raspistill %s -w %s -h %s -t 200 -e bmp -n -o -" % (settings, width, height)
    imageData = StringIO.StringIO()
    imageData.write(subprocess.check_output(command, shell=True))
    imageData.seek(0)
    im = Image.open(imageData)
    buffer = im.load()
    imageData.close()
    return im, buffer

# Save a full size image to disk
def saveImage(settings, width, height, quality, diskSpaceToReserve):
    keepDiskSpaceFree(diskSpaceToReserve)
    time = datetime.now()
    if numsequence:
        filename = filepath + "/" + filenamePrefix + "-" + fileCount + ".jpg"
        imageTagName = filenamePrefix + "-" + fileCount + "   %04d%02d%02d-%02d:%02d:%02d" % (time.year, time.month, time.day, time.hour, time.minute, time.second)
    else:
        filename = filepath + "/" + filenamePrefix + "-%04d%02d%02d-%02d%02d%02d.jpg" % (time.year, time.month, time.day, time.hour, time.minute, time.second)
        imageTagName = filenamePrefix + "-" + "%04d%02d%02d-%02d:%02d:%02d" % (time.year, time.month, time.day, time.hour, time.minute, time.second)
    subprocess.call("raspistill %s -w %s -h %s -t 200 -e jpg -q %s -n -o %s" % (settings, width, height, quality, filename), shell=True)
    if (showDateOnImage):
        writeDateToImage(filename,imageTagName)
    print "%s - %s saved %s" % (progname, imageTagName, filename)
    imageNow= filepath + "/" + filenamePrefix + "_current.jpg"
    shutil.copy(filename,imageNow)

# Keep free space above given level
def keepDiskSpaceFree(bytesToReserve):
    if (getFreeSpace() < bytesToReserve):
        for filename in sorted(os.listdir(filepath + "/")):
            if filename.startswith(filenamePrefix) and filename.endswith(".jpg"):
                os.remove(filepath + "/" + filename)
                print "%s - Deleted %s/%s to avoid filling disk" % (progname,filepath,filename)
                if (getFreeSpace() > bytesToReserve):
                    return

# Write Date to Image
def writeDateToImage(imagename,datetoprint):
    FOREGROUND = (255, 255, 255)
    TEXT = datetoprint
    font_path = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'
    font = ImageFont.truetype(font_path, 24, encoding='unic')
    text = TEXT.decode('utf-8')
    img = Image.open(imagename)
    draw = ImageDraw.Draw(img)
    # draw.text((x, y),"Sample Text",(r,g,b))

    draw.text((500, 930),text,FOREGROUND,font=font)
    img.save(imagename)
    return

# Get available disk space
def getFreeSpace():
    st = os.statvfs(filepath + "/")
    du = st.f_bavail * st.f_frsize
    return du

# Get first image
image1, buffer1 = captureTestImage(cameraSettings, testWidth, testHeight)

# Reset last capture time
lastCapture = time.time()

if numsequence:
    if not os.path.exists(countpath):
        print "%s - Creating New Counter File %s Counter=%i" % (progname, countpath,startCount)
        open(countpath, 'w').close()
        f = open(countpath, 'w+')
        f.write(str(startCount))
        f.close()
 
    with open(countpath, 'r') as f:
        writeCount = f.read()
        f.closed
    currentCount = int(writeCount) + 1
    if (currentCount > startCount + maxPhotos):
        currentCount = startCount

starttime = datetime.now()
rightnow = "%04d%02d%02d-%02d:%02d:%02d" % (starttime.year, starttime.month, starttime.day, starttime.hour, starttime.minute, starttime.second)
print "---------------------------------- Settings -----------------------------------------"
print "    Motion .... Sensitivity=%i Threshold=%i Cam-Settings= %s ForceCapture=%s every %i seconds"  % (sensitivity, threshold, cameraSettings, forceCapture, forceCaptureTime)
print "    Image ..... W=%i H=%i Quality=%i DateOnImage=%s Prefix=%s Path=%s" % (saveWidth, saveHeight, saveQuality, showDateOnImage, filenamePrefix, filepath)
print "    Numbering . On=%s Start=%s Max=%i path=%s Counter=%i" % (numsequence, startCount, maxPhotos, countpath, currentCount)
print "    Sync File . On=%s Path=%s" % (createLockFile, lockfilepath)
print "    DiskSpace . Reserved=%i mb" % (mbToReserve)
print "    Debug ..... On=%s Path=%s/debug.bmp" % (debugMode, filepath)
print "-------------------------------------------------------------------------------------"
print "%s - Waiting for Motion %s ........" % (progname, rightnow)

# Start main motion capture loop
while (True):

    # Get comparison image
    image2, buffer2 = captureTestImage(cameraSettings, testWidth, testHeight)

    # Count changed pixels
    changedPixels = 0
    takePicture = False

    if (debugMode): # in debug mode, save a bitmap-file with marked changed pixels and with visible testarea-borders
        debugimage = Image.new("RGB",(testWidth, testHeight))
        debugim = debugimage.load()

    for z in xrange(0, testAreaCount): # = xrange(0,1) with default-values = z will only have the value of 0 = only one scan-area = whole picture
        for x in xrange(testBorders[z][0][0]-1, testBorders[z][0][1]): # = xrange(0,100) with default-values
            for y in xrange(testBorders[z][1][0]-1, testBorders[z][1][1]):   # = xrange(0,75) with default-values; testBorders are NOT zero-based, buffer1[x,y] are zero-based (0,0 is top left of image, testWidth-1,testHeight-1 is botton right)
                if (debugMode):
                    debugim[x,y] = buffer2[x,y]
                    if ((x == testBorders[z][0][0]-1) or (x == testBorders[z][0][1]-1) or (y == testBorders[z][1][0]-1) or (y == testBorders[z][1][1]-1)):
                        # print "Border %s %s" % (x,y)
                        debugim[x,y] = (0, 0, 255) # in debug mode, mark all border pixel to blue
                # Just check green channel as it's the highest quality channel
                pixdiff = abs(buffer1[x,y][1] - buffer2[x,y][1])
                if pixdiff > threshold:
                    changedPixels += 1
                    if (debugMode):
                        debugim[x,y] = (0, 255, 0) # in debug mode, mark all changed pixel to green
                # Save an image if pixels changed
                if (changedPixels > sensitivity):
                    takePicture = True # will shoot the photo later
                if ((debugMode == False) and (changedPixels > sensitivity)):
                    break  # break the y loop
            if ((debugMode == False) and (changedPixels > sensitivity)):
                break  # break the x loop
        if ((debugMode == False) and (changedPixels > sensitivity)):
            break  # break the z loop

    if (debugMode):
        debugimage.save(filepath + "/debug.bmp") # save debug image as bmp
        print "%s - Saved Debug to %s/debug.bmp  Changed Pixel=%i" % (progname, filepath, changedPixels)
    # else:
    #     print "%s changed pixel" % changedPixels

    # Check force capture
    if forceCapture:
        if time.time() - lastCapture > forceCaptureTime:
            takePicture = True

    if takePicture:
        lastCapture = time.time()
        if numsequence:
            fileCount = str(currentCount)
        saveImage(cameraSettings, saveWidth, saveHeight, saveQuality, diskSpaceToReserve)
        # increment image counter and reset to start if max reached
        if numsequence:
            currentCount += 1
            if (currentCount > startCount + maxPhotos):
                currentCount = startCount
            writeCount = str(currentCount)
            # write current photo counter to file
            if not os.path.exists(countpath):
                print "%s - Creating %s" % (progname,countpath)
                open(countpath, 'w').close()
            f = open(countpath, 'w+')
            f.write(str(writeCount))
            f.close()
        # write a lock file so sync script knows when there are files to process for grive
        if createLockFile:
            if not os.path.exists(lockfilepath):
                print "%s - Creating %s" % (progname, lockfilepath)
                open(lockfilepath, 'w').close()
            f = open(lockfilepath, 'w+')
            f.write("Photos available to sync with grive using sync shell script")
            f.close()

    # Swap comparison buffers
    image1  = image2
    buffer1 = buffer2

Understanding the code


Answer the following questions to gain a better understanding of how this code actually works:

At which line (line number) does the main motion loop start?
What is the purpose of the variable called pixdiff?
What is the purpose of the variable called threshold?
What is the purpose of the variable called takePicture?
What is the purpose of the variables called forceCapture and forceCaptureTime?
Tagged with:

Timelapse Video Recording Using a Rapberry Pi

RaspberryPi

Getting Ready…

For this challenge you will need:

  • A Raspberry Pi with Python 2 installed,
  • A PiCamera.

Follow the steps described on the following pages to make sure you have plugged the camera in your raspberry pi and that you have enabled it. Also make sure you have installed the picamera library.

Getting Started


timelapse

First we need to write a Python script to take and store a picture every “x” seconds. We will do this using an infinite loop.

To make sure we can exit the loop we will catch a keyboard interrupt (when the user presses CTRL + “C”. This will terminate the program.

The main variable used in this script is the timeInterval variable. Per default we set it to 5 seconds. You may want to change this depending on what you are recording and how long you intend to record it for.

import picamera, time
#Initailise the camera
camera=picamera.PiCamera()

#This will be used to name the pictures once stored.
filename = "frame_"
timeInterval = 5 # The time interval between two pictures, in seconds

#We have left all the settings in case you need to make some adjustments to improve the picture quality
camera.hflip = True
camera.vflip = True
#camera.sharpness = 0
#camera.contrast = 0
#camera.brightness = 50
#camera.saturation = 0
#camera.ISO = 0
#camera.video_stabilization = False
#camera.exposure_compensation = 0
#camera.exposure_mode = 'auto'
#camera.meter_mode = 'average'
#camera.awb_mode = 'auto'
#camera.image_effect = 'none'
#camera.color_effects = None
#camera.rotation = 0
#camera.crop = (0.0, 0.0, 1.0, 1.0)

i=1
try:
    while True: #Infinite Loop
        camera.capture(filename + str(i) + '.jpg')
        print(filename + str(i) + '.jpg')
        time.sleep(timeInterval)
        i+=1
except KeyboardInterrupt: #Press Ctrl+C to interrupt
    pass

print('All done...')

Final Step


Now that we have all the pictures stored. We need to combine them into a video clip (.avi).

To do so we will use the following script, from Claude Pageau: Source: https://github.com/pageauc/pi-motion-orig

print "initializing ...." 
import StringIO 
import subprocess 
import os 
import time 
import csv 
from datetime import datetime 
import cgi, cgitb 

imageWidth = 1296 
imageHeight = 972 
# Aspect ratio of video eg 4/3 16/9 Etc. 
# Note put value in quotes. 
aspectRatio = "4/3" 
# Video fps (frames per second) vulue usually  between 2 to 30.  I recommend 5 fps to start 
framesPerSec = 5 
# Video output filename. 
# Can also include folder path, othewise file saved to current folder.  
movieName = "./makemovie.avi" 
 
print "makemovie.py" 
print "============" 
print "Creating makemovie.txt file of *jpg files in google_drive folder."  
ls_params = " -t -r ./*jpg > makemovie.txt" 
exit_status = subprocess.call("ls %s " % ls_params, shell=True) 

print "Creating movie file %s using makemovie.txt" % ( movieName ) 
print "Settings = Image W=%s H=%s aspect=%s fps=%s filename=%s" % ( imageWidth, imageHeight, aspectRatio, framesPerSec, movieName ) 

mencoder_params = "-nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=%s:vbitrate=8000000 -vf scale=%s:%s -o %s -mf type=jpeg:fps=%s  mf://@makemovie.txt" % ( aspectRatio, imageWidth, imageHeight, movieName, framesPerSec ) 
print "memcoder_params = %s" % ( mencoder_params ) 
print "Creating Movie. This will take a while ......." 
print "----------------------------------------------" 

exit_status = subprocess.call("mencoder %s" % mencoder_params, shell=True) 
print "makemovie.py" 
print "============" 
print "Finished timelapse movie filename= %s" % ( movieName ) 
Tagged with: ,

Daily Calorie Intake

apple

Did You Know?

Keeping a healthy lifestyle consists of adapting our daily food intake with our level of physical activities. The calories we intake (by eating food) has to roughly match the calories we burn throughout the day.

Your Challenge


For this challenge you are going to write a Python program that asks the user for their gender (Male of Female), their lifestyle (Sedentary, Moderately Active, Active) and their age.
The program will then tell them what their daily calorie intake should be.

The program should make use of the following table of data:


GenderAge (years)SedentaryModerately ActiveActive
Female2 to 3100012001400
4 to 8120014001800
9 to 13160019002200
14 to 18180021002400
19 to 30200022002400
31 to 50180020002200
51+160019002200
Male2 to 3100012001400
4 to 8140017002000
9 to 13180022002600
14 to 18220027003200
19 to 30240027003000
31 to 50220026003000
51+200024002800

Learning Objectives


By Completing this learning challenge you will use:

  • Nested If Statements,
  • Comparison Operators such as ==, !=, <, <=, >, >=,
  • Boolean Operators: AND or OR.

Tip:


Complete this task progressively using the following 3 steps:

Step 1:

    Start by asking the end-user for their gender.
    If their gender is Male display your calorie intake is around 2400 calories for a man, or 2000 for a woman. If you need a reminder on how to use the input, if and print instructions in python check this page.

Step 2:

    Add an input at the beginning to ask the user for their age (in years). Convert this input to an integer using the int() function. Use nested if to display the right daily calorie intake based on both the gender and the age. (Use the data from the first column, “sedentary” at this stage.)

    Remember when using nested if statements to indent your code accordingly.

Step 3:

    You can now use a third question to ask the user if they are “S” – Sedentary, “M” – Moderately Active, “A” Active.
    Use a third level of indentation/nesting to complete this challenge using all the data from the given table.

Your Code:


Extension Task:


Ask the user how many calories they have eaten so far (this day) and return the number of calories they can still have till the end of the day to match their recommended daily calorie intake.

Review…


Complete this fill in the gaps activity to check whether you can use the right computing terminology.

Tagged with: , ,

Find the monster!

door-140 door-140 door-140

Will you dare open one of the three doors above. (Click on a door to open or close it.)

Did you come across any monster? If not carry on opening doors till you find a monster!

Your Challenge

Check the Python code below. This code lets the user open one of the three doors to see if there is a monster behind the selected door.

Your task consists of tweaking this code further to enable the user to carry on opening doors till they find the monster. To do so you will need to use a while loop.

The program should count how many doors the user did open and stop once the user meets the monster.


unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Tagged with: , ,

Revise: If Statements


Complete this drag and drop activity to use the right computing terminology about If Statements, boolean operators and comparison operators.

equal to
False
comparison
elif
OR
!=
boolean
<=

  • == and != are operators,
  • == means “is ?”,
  • means “is not equal to?”, aka “is different from?”
  • Other comparison operators can be used in selection statements such as >, <, , >=,
  • AND and are operators,
  • The result of a comparison is a boolean, which means it is either True or ,
  • In Python we can use the following three instructions: if, and else.

Tagged with: ,

NATO Phonetic Alphabet

Did You Know?


The NATO Phonetic Alphabet is the most widely used spelling alphabet. A spelling alphabet (aka radio alphabet, or telephone alphabet) is a set of words used to stand for the letters of an alphabet in oral communication. Each word in the spelling alphabet typically replaces the name of the letter with which it starts. It is used to spell out words when speaking to someone not able to see the speaker, or when the audio channel is not clear.

Nowadays people may use the NATO Phonetic alphabet when they have to spell their name or their postcode over the phone.

For instance, the name Smith would spell Sierra – Mike – India – Tango – Hotel.

Challenge


This challenge consists of writing a computer program that will ask the end-user to enter their lastname. The program will output their lastname using the NATO Phonetic Alphabet.

To complete this challenge you may want to investigate the use of a dictionary in Python.

Learning Objectives


By completing this challenge we are going to learn about Python dictionaries.
In Python, a dictionary consists of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:
PythonDictionary

myDictionary = {"Red": "#FF0000", "Green": "#00FF00", "Blue": "#0000FF"}
print("The colour code for Green is:")
print(myDictionary["Green"])

btnTryCodeOnline

NATO Phonetic Alphabet

Letter Code
A Alfa
B Bravo
C Charlie
D Delta
E Echo
F Foxtrot
G Golf
H Hotel
I India
J Juliett
K Kilo
L Lima
M Mike
N November
O Oscar
P Papa
Q Quebec
R Romeo
S Sierra
T Tango
U Uniform
V Victor
W Whiskey
X X-ray
Y Yankee
Z Zulu
Dash

Let’s get coding…

Extension


You can use the same approach to create a Morse Code Encoder!

Morse-Code-NATO

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Google Translate

english-frenchHave you ever used Google Translate to translate some text or a full webpage?

For this challenge we are going to try to write a Python script to translate from English to French. However we are only going to translate numbers as follows:

Number English French
7 Seven Sept
24 Twenty-four Vingt-quatre
365 Three hundred and sixty-five Trois cent soixante-cinq
25,642 Twenty-five thousand six hundred and forty-two Vingt-cing mille six cent quarante-deux


From the examples given above we can see that the same rules are used in both English and French to write numbers in full. This means that we can write a simple algorithm here to translate word for word each of the words used from English to French. Note that even though this approach will be quite accurate to translate numbers written in full, it would be very inaccurate to translate full sentences. This is because the English grammar and the French grammar are different and though both languages have a lot of similarities they do not follow exactly the same rules. (Grammar and conjugation)

grammar-conjugation

For our translation algorithm we will focus on a word for word translation. To do so we need an English/French dictionary. We will use a text file containing all the words we need: One, Two, Three… Ten, Eleven, Twelve, … Thirty, Forty, Fifty, … Hundred, Thousand.


TextFiledictionary.txt

Finally we can write our algorithm which will:

  1. Ask the user to enter a number in full English,
  2. Open the dictionary.txt file in read mode,
  3. Loop through each line of the text file
    • Split and extract the data (English and French word)
    • Replace the English word with the French word in the number
  4. Close the text file
  5. Display the translated number on screen

Un, Deux, Trois…


Let’s test this code. You can use the numbers given in the table above to test this code:

Your Task:


Complete this code for the program to:

  1. Ask the user if they want to translate from English to French (Option 1) or from French to English (Option 2),
  2. Allow for the French to English translation using a similar approach as the one used to translate from English to French, using the same dictionary.txt file, without having to change it.
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

Formula 1 Grand Prix

For this challenge we are going to use pseudo-code to analyse the timings of the best two formula 1 drivers of the season, Lewis Hamilton and Sebastian Vettel on four different Grand Prix.

For the purpose of this task we will assume that the drivers are competing against each other on four Grand Prix, each race consisting of ten laps only.

The timings of both drivers will be recorded using pseudo-code. Your task will be to analyse the pseudo-code for each of the four grand prix to decide who of the two drivers won each race!

F1-Melbourne

Race #1: Australian Grand Prix – Melbourne

Here are the timings of the race:

Race Timings

hamiltonTime = 0
vettelTime = 0

for lap in range(1,10):

    hamiltonTime += 100
    vettelTime += 102

    if lap==8:
        hamiltonTime += 18
Running Commentary
Both drivers are on the starting line, ready to push on the accelerator.

Lewis Hamilton has a better start and on average completes each lap in 100 seconds (1 minute and 40 seconds) where Sebastian Vettel completes each laps in 102 seconds (1:42).

We are now on lap 8 and it seems that Lewis Hamilton is going to win this race.

Oh no, Lewis Hamilton is having a technical issue with his car and now needs to stop in the pits to get his car fixed. He has lost 18 seconds! Will he still be able to win the race at the end of lap 10?

Analyse the race above. Can you find out who won this first Grand Prix? Type the name of the winner below:

F1-Silverstone

Race #2: British Grand Prix – Silverstone

Here are the timings of the race:

Race Timings

hamiltonTime = 0
vettelTime = 0

for lap in range(1,10):
    if lap <= 4
       hamiltonTime += 100
       vettelTime += 102
    else:
       hamiltonTime += 103
       vettelTime += 102

    if lap==9:
        hamiltonTime += 18
        vettelTime += 15
Running Commentary
Once again Lewis Hamilton has a better start than Sebastian Vettel and is completing the first 4 laps with an average of 100 seconds (1 minute and 40 seconds) per lap where Sebastian Vettel completes each lap in 102 seconds (1:42).

From lap 5 onwards, however Lewis Hamilton seems to be slowing down a bit and is now completing each lap in 103 seconds while Sebastian Vettel remains at the same speed, completing each lap in 102s. He is progressively reducing the gap and catching with Lewis Hamilton.

We are now on lap 9 and both drivers decide to have a pitstop losing respectively 18 seconds and 15 seconds. Will this 3-second difference have an impact on the final outcome of this race?

Analyse the race above. Can you find out who won this second Grand Prix? Type the name of the winner below:

F1-Monaco

Race #3: French Grand Prix – Monaco

Here are the timings of the race:

Race Timings

hamiltonTime = 0
vettelTime = 0

for lap in range(1,10):

    hamiltonTime += 103
    vettelTime += 101

    if lap==5:
        hamiltonTime +=14
    if lap==4 or lap==7:
        vettelTime += 12
Running Commentary
What a fantastic race from Sebastian Vettel who is taking risks and completing each lap in on average 101 seconds (1:41) whereas Lewis Hamilton is 2 seconds slower on every lap.

During this race, Lewis Hamilton will only stop once in the pits, on lap 5 losing 14 seconds whereas Sebastian Vettel will make two stops losing 12 seconds each time.

This is a very risky strategy. Which of the two drivers will have made the right decision?

Analyse the race above. Can you find out who won this third Grand Prix? Type the name of the winner below:

F1-Monza

Race #4: Italian Grand Prix – Monza

Here are the timings of the race:

Race Timings

hamiltonTime = 0
vettelTime = 0

for lap in range(1,10):

    if lap <= 3
       hamiltonTime += 101
       vettelTime += 101
    elif lap>3 and lap<=8:
       hamiltonTime += 103
       vettelTime += 102
    else:
       hamiltonTime += 100
       vettelTime += 101
Running Commentary
What an exciting start to this race. For 3 full laps both drivers are ex aequo, driving their formula 1 car at exactly the same speed, completing each lap on 101 seconds.

From lap 3, Sebastian Vettel is taking the lead, completing laps in 102 seconds, 1 second quicker than his main opponent, Lewis Hamilton.

Towards the end of the course however Lewis Hamilton is accelerating progressively closing the gap with Sebastian Vettel. Will he have time to catch up with him and overtake him before the finishing line?

Analyse the race above. Can you find out who won this fourth Grand Prix? Type the name of the winner below:

Tagged with: , ,