More results...

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

Logic Gates & Truth Tables

Learning Objectives


In this post you will predict the output of logic gates circuits by completing truth tables. First you need to learn the basic truth tables for the following logic gates:

  • AND Gate
  • OR Gate
  • XOR Gate
  • NOT Gate

First you will need to learn the shapes/symbols used to draw the four main logic gates:

Logic Gate Truth Table
AND-GateAND AND Gate Truth Table
OR-GateOR OR Gate Truth Table
XOR-GateXOR XOR Gate Truth Table
NOT-GateNOT truth-table-not-gate

Your Task


Your task is to complete the truth tables for the following diagrams. You can click on the Truth Tables to change the values in the X column.

Tagged with: , ,

Football Formation

football-team-formationThe purpose of this challenge is to understand how subroutines (functions/procedures) are used in Python to create sections of code that can be called/reused many times within a program. Subroutines mean that a section of code can be identified using a name (identifier). This enables us to add more instructions to the already existing functions used in Python such as print or input.

To create a new subroutine in Python we have to declare it first using the keyword def in Python.

e.g.:

def drawPlayer():

The code for the subroutine is then indented to the right.

A subroutine can also take parameters. In our case, our drawPlayer() subroutine will take four parameters:

  • color: (string value) The color name such as “red” or hexadecimal code such as “#FF0000”.
  • x: (integer value) The x coordinate of the player between -140 to 140,
  • y: (integer value) The y coordinate of the player between -195 to 195,
  • label: (string value) The text (name of player or position) to display.

X and Y coordinates? Quadrant?


xy-coordinates
Check the above picture. Can you state three facts about X and Y coordinates and about quadrants?

The canvas we are drawing on (using Python Turtle) is 400 pixels wide by 400 pixels high.
Look at the canvas below to understand how (x,y) coordinates work:

So to define this function we will now be using the following code with the 4 parameters:

def drawPlayer(color,x,y,label):

We will then be able to position our players by calling the drawPlayer() subroutine as follows:

drawPlayer("red",60,120,"Goal Keeper")

Your task consists of adding all 11 players to your formation using the code provided below. We have already started the formation for you by adding the goal keeper and the two centre-back players.

Your formation should include 11 players including:

  • 1 goal keeper,
  • 2 to 4 fullback players,
  • 2 to 4 midfield players,
  • 2 to 4 forward players.

football-formation

Extension Task #1


Add a parameter to the drawPlayer() subroutine to take the squad number of the player.

Change the content of the subroutine to display the squad number on the circle for the player. The output of your program should look like this:

Extension Task #2


During a football games, players can be issued a yellow card or a red card.

Add two parameters to your subroutine to specify if a player has been given a yellow or red card.

Change the text color of the player name or position to:

  • Yellow for players who have received a yellow card,
  • Red for players who have received a red card,
  • Grey (#CCCCCC) for all other players.
Tagged with: , , , , ,

Acute, Obtuse and Reflex Angles

Angles are often used in Computer Science especially when creating 2D or 3D user interfaces. Angle measurements are given in either radians or degrees. In this blog post we will use degrees. As the angle increase, the name of the angle changes as explained in the pictures and in the table below:

types-of-angles

Type of Angle Description
Acute Angle an angle that is less than 90°
Right Angle an angle that is 90° exactly
Obtuse Angle an angle that is greater than 90° but
less than 180°
Straight Angle an angle that is 180° exactly
Reflex Angle an angle that is greater than 180°

Challenge #1


Write a Python script that will ask the user to enter an angle between 0° and 360°.

The program should find out and output the type of angle (Acute, Right, Obtuse, Straight or Reflex) using the table of values provided above.

Video Tutorial


Test Plan


Once your code is done, complete the following tests to check that your code is working as it should:

Test # Input Values Expected Output Actual Output
#1 Angle: 30 Acute angle
#2 Angle: 90 Right angle
#3 Angle: 105 Obtuse angle
#4 Angle: 180 Straight angle
#5 Angle: 210 Reflex angle
#6 Angle: 420 Please try again with an angle value between 0 and 360 degrees.

Challenge #2: Quiz


Write a Python script that will generate a random angle between 0° and 360°. The program should ask the user to give the name of the angle. If the user gets it right they should score 1 point.

The program should repeat this process ten times and output a final score out of ten.

To complete these two challenges you will need to use some selection statements (IF,ELIF,ELSE statements) as well as some comparison operators and Boolean operators (AND, OR, NOT).

The main comparison operators are:

Comparison Operator Meaning Example
== is equal to 4==4
!= is different from 4!=7
< is lower than 3<5
> is greater than 9>2
<= is lower or equal to 3<=5
5<=5
>= is greater or equal to 9>=2
5>=5
unlock-access

Solution...

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

Variables Terminology

Variables are used in nearly every single computer program. They are an essential concept and can be used and manipulated using many different techniques. The following spider diagram summarises the key computing concepts linked to the use of variables in procedural programming:variables-spider-diagram

Terminology:


Variables vs. Constants
Variables are used to store a value that can be changed within the program (as opposed to constants which remain the same throughout the program).
Identifier
Identifier: the name given to a variable: e.g. score, numberOfLives.
Data Types
Data Type: A variable has a data type such as:

  • Integer
  • Real/Float
  • Boolean
  • String
Declaring a variable
Declare: Some programming languages require variables to be declared first before they can be used. When declaring a variable you give it an identifier (and a data type for some languages) e.g.

int score

Depending on where in your code you declare a variable will have an impact on its scope.

Scope of a variable
Scope of a variable: the extent of a program in which the variable is visible/accessible.

A variable which is declared within a subprogram (e.g. procedure or function) is only available within this subprogram. It is a local variable.

A variable which is declared outside any subprograms becomes accessible to code written anywhere in the program. It is a global variable.

Initialising a variable
Initialise: To give/assign a variable its first value which can be changed later on in the program. e.g.

score = 0

Assigning a value
Assign: To give or change the value of a variable, using the assignment operator (=) e.g.
numberOfLives = 3
Casting
Casting: to convert/change the data type of a variable

e.g. in Python using functions such as int(), str(), float().

Incrementing
Increment: To increase the value a variable by a value (e.g. 1). e.g.:

score += 1

Decrementing
Decrement: To decrease the value a variable by a value (e.g. 1) e.g.

timer -= 1

List and Arrays
List and arrays:

Some more complex data structures such as lists and arrays enable you to store multiple values in a single variable.

e.g.

daysOfTheWeek=[“Monday”,”Tuesday”,“Wednesday”,”Thursday”,”Friday”]

Parameter passing
Passing parameters by value or by address/reference: You can pass a variable or its value to a subroutine (function or procedure). This is done either by value (in this case the value of the variable will not change outside the subroutine) or by address/reference (in this case the subroutine may change the value of the variable).
Tagged with:

Weather Statistics Challenge

Weather Data for Quebec City, Canada


For this challenge we will use a two-dimensional array (in Python a list of lists) to store the average temperature (in Celsius degrees) and the rainfall (in mm) for each of the twelve months of the year for Quebec City, Canada.

We will populate our array called quebec with the following data:

weather-data

Source: https://en.climate-data.org/location/663/

The aim of this challenge is to use a Python script to scan through all this data to calculate and display:

  • The average temperature throughout the year,
  • The hottest month of the year,
  • The total amount of rainfall throughout the year,
  • The average rainfall throughout the year,
  • The coldest month of the year,
  • The difference in rainfall between the wettest and the driest month of the year,
  • The average temperature during the wettest month of the year,
  • The average temperature during the driest month of the year,
  • The average Temperature during the three winter months, December, January, February.

The data provided above can also be represented using an “Average Temperature and Rainfall Chart”. You can use this chart to compare and check the outcomes of your Python script with the information provided on this chart.

Python Code


We have started the code for you. Analyse this code and reuse similar algorithms to complete this challenge.

unlock-access

Solution...

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

Little Man Computer: Factorial Challenge

arithmetic-quiz-calculatorIn Mathematics, the factorial of n is denoted by n! and calculated by the product of integer numbers from 1 to n.

For instance:
factorial-of-5

In this challenge you will write a program using Little Man Computer to ask the user to enter a positive number. In return the program will output the factorial of this number.

Before completing this challenge, we recommend you to have a go at:

Multiplication using LMC


While checking the Little Man Computer Instruction Set (See table at the bottom of this post), you will have noticed that, through there are two instructions for adding (ADD) and subtracting (SUB) numbers, there is no instruction for multiplying two numbers.

The solution to overcome this, is two consider a multiplication as a series of additions. For instance:

5 * 4 = 5 + 5 + 5 + 5

Find out more: Little Man Computer: Multiplication

Iteration using LMC


To apply an iterative approach for this challenge we will use branching options: Little Man Computer: 5 + 4 + 3 + 2+ 1.

This challenge will add a level of complexity as we will be using a nested loop approach: one loop to list all the multiplications to be performed (e.g. 4! = 4 * 3 * 2 * 1) and one loop for implementing each multiplication as a series of additions. (e.g. 4 * 3 = 4 + 4 + 4)

LMC Simulators

Solution


This solution also caters for the fact that 0! = 1. This is the purpose of line 3, 34,35 and 36.

          inp 
          sta final 
          brz oneval
          sub one
          sta iteration
          sta counter
          lda final
          sta num
mult      lda iteration
          brz end
          sub one
          brz end
          lda final
          add num
          sta final
          lda counter
          sub one
          sta counter
          sub one
          brz next
          bra mult
next      lda final
          sta num 
          lda iteration
          sub one
          sta iteration
          sta counter
          sub one
          brz end
          bra mult
end       lda final
          out
          hlt
oneval    lda one
          out
          hlt
final     dat 0
counter   dat 0
one       dat 1
iteration dat 0
num       dat 0
© Solution by Howard C.

LMC Instruction Set


Note that in the following table “xx” refers to a memory address (aka mailbox) in the RAM. The online LMC simulator has 100 different mailboxes in the RAM ranging from 00 to 99.

Mnemonic Name Description Op Code
INP INPUT Retrieve user input and stores it in the accumulator. 901
OUT OUTPUT Output the value stored in the accumulator. 902
LDA LOAD Load the Accumulator with the contents of the memory address given. 5xx
STA STORE Store the value in the Accumulator in the memory address given. 3xx
ADD ADD Add the contents of the memory address to the Accumulator 1xx
SUB SUBTRACT Subtract the contents of the memory address from the Accumulator 2xx
BRP BRANCH IF POSITIVE Branch/Jump to the address given if the Accumulator is zero or positive. 8xx
BRZ BRANCH IF ZERO Branch/Jump to the address given if the Accumulator is zero. 7xx
BRA BRANCH ALWAYS Branch/Jump to the address given. 6xx
HLT HALT Stop the code 000
DAT DATA LOCATION Used to associate a label to a free memory address. An optional value can also be used to be stored at the memory address.
Tagged with: ,

Little Man Computer: Multiplication

calculator-lmcWrite an LMC program to let the user enter two numbers, num1 and num2.
The program should output the results of multiplying these two numbers: num1 x num2.

LMC Simulators

Solution


While checking the Little Man Computer Instruction Set (See table at the bottom of this post), you will have noticed that, through there are two instructions for adding (ADD) and subtracting (SUB) numbers, there is no instruction for multiplying two numbers.

The solution to overcome this, is two consider a multiplication as a series of additions. For instance:

5 * 4 = 5 + 5 + 5 + 5

This is how we will implement our multiplication algorithm:

        INP
        STA NUM1
        INP 
        STA NUM2
LOOP    LDA TOTAL
        ADD NUM1
        STA TOTAL
        LDA NUM2
        SUB ONE
        STA NUM2
        BRP LOOP
        LDA TOTAL
        SUB NUM1
        STA TOTAL
        OUT
        HLT
NUM1    DAT
NUM2    DAT
ONE     DAT 1
TOTAL   DAT 0

LMC Instruction Set


Note that in the following table “xx” refers to a memory address (aka mailbox) in the RAM. The online LMC simulator has 100 different mailboxes in the RAM ranging from 00 to 99.

Mnemonic Name Description Op Code
INP INPUT Retrieve user input and stores it in the accumulator. 901
OUT OUTPUT Output the value stored in the accumulator. 902
LDA LOAD Load the Accumulator with the contents of the memory address given. 5xx
STA STORE Store the value in the Accumulator in the memory address given. 3xx
ADD ADD Add the contents of the memory address to the Accumulator 1xx
SUB SUBTRACT Subtract the contents of the memory address from the Accumulator 2xx
BRP BRANCH IF POSITIVE Branch/Jump to the address given if the Accumulator is zero or positive. 8xx
BRZ BRANCH IF ZERO Branch/Jump to the address given if the Accumulator is zero. 7xx
BRA BRANCH ALWAYS Branch/Jump to the address given. 6xx
HLT HALT Stop the code 000
DAT DATA LOCATION Used to associate a label to a free memory address. An optional value can also be used to be stored at the memory address.
Tagged with: ,

Little Man Computer: 5+4+3+2+1

lmc-numbersWrite an LMC program to let the user enter a number n.

The program should calculate the output n + (n-1) + (n-2) + … + 3 + 2 + 1.

For instance if the user enters the value 5. The program should output the number 15 because:

5 + 4 + 3 + 2 + 1 = 15

LMC Simulators

Solution


LMC Instruction Set


Note that in the following table “xx” refers to a memory address (aka mailbox) in the RAM. The online LMC simulator has 100 different mailboxes in the RAM ranging from 00 to 99.

Mnemonic Name Description Op Code
INP INPUT Retrieve user input and stores it in the accumulator. 901
OUT OUTPUT Output the value stored in the accumulator. 902
LDA LOAD Load the Accumulator with the contents of the memory address given. 5xx
STA STORE Store the value in the Accumulator in the memory address given. 3xx
ADD ADD Add the contents of the memory address to the Accumulator 1xx
SUB SUBTRACT Subtract the contents of the memory address from the Accumulator 2xx
BRP BRANCH IF POSITIVE Branch/Jump to the address given if the Accumulator is zero or positive. 8xx
BRZ BRANCH IF ZERO Branch/Jump to the address given if the Accumulator is zero. 7xx
BRA BRANCH ALWAYS Branch/Jump to the address given. 6xx
HLT HALT Stop the code 000
DAT DATA LOCATION Used to associate a label to a free memory address. An optional value can also be used to be stored at the memory address.
Tagged with: ,

Little Man Computer – Burglar Alarm

burglar-alarm-pin-codeWrite an LMC program to let the user enter a PIN code to deactivate a burglar alarm.

The program should let the user have up to 3 attempts to enter the correct PIN code before starting the alarm.

The correct PIN code is “123”.

If the user gets the right PIN code the program should output value 1.
If the user gets the wrong PIN code the program should output value 9 indicating that they can have another go at entering the PIN code.
If after three attempts the PIN code entered is still incorrect, the program should output value -1.

LMC Simulators

LMC Instruction Set


Note that in the following table “xx” refers to a memory address (aka mailbox) in the RAM. The online LMC simulator has 100 different mailboxes in the RAM ranging from 00 to 99.

Mnemonic Name Description Op Code
INP INPUT Retrieve user input and stores it in the accumulator. 901
OUT OUTPUT Output the value stored in the accumulator. 902
LDA LOAD Load the Accumulator with the contents of the memory address given. 5xx
STA STORE Store the value in the Accumulator in the memory address given. 3xx
ADD ADD Add the contents of the memory address to the Accumulator 1xx
SUB SUBTRACT Subtract the contents of the memory address from the Accumulator 2xx
BRP BRANCH IF POSITIVE Branch/Jump to the address given if the Accumulator is zero or positive. 8xx
BRZ BRANCH IF ZERO Branch/Jump to the address given if the Accumulator is zero. 7xx
BRA BRANCH ALWAYS Branch/Jump to the address given. 6xx
HLT HALT Stop the code 000
DAT DATA LOCATION Used to associate a label to a free memory address. An optional value can also be used to be stored at the memory address.
unlock-access

Solution...

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

Binary Trees – Linked Lists

Binary trees are useful data structures used to solve specific computational problems. They provide a visual representation of how data can be stored and linked.

Computers use linked lists to store the information of binary trees. This blog post will look at how we can convert a binary tree into a linked list.

Binary Tree #1


binary-search-tree-01

Linked List


Memory Address binary-tree-nodeNode Value binary-tree-left-pointerLeft Pointer binary-tree-right-pointerRight Pointer
0 K 4 1
1 T 2 3
2 S 5
3 U
4 A
5 L
6
7

The Tree is accessed using two pointers:

  • RootPointer = 0
  • EndPointer = 6

Each time a new element is added to the tree, the EndPointer increments by 1.

Binary Tree #2


binary-search-tree-02

Linked List


Memory Address binary-tree-nodeNode Value binary-tree-left-pointerLeft Pointer binary-tree-right-pointerRight Pointer
0 T
1 F
2 L
3 B
4 A
5 U
6 C

Complete the linked list above.

What would happen if the next value to be added to the tree was letter S?

Binary Tree #3


The values have been received/stored in the following order:
N,E,T,F,B,V,U,C,Y

Draw the binary search tree on paper and complete the following link list table:

Memory Address binary-tree-nodeNode Value binary-tree-left-pointerLeft Pointer binary-tree-right-pointerRight Pointer

What would happen if the next value to be added to the tree was letter K?

Tagged with: