More results...

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

RISC and CISC Processors

cpu-risc-cisc
RISC and CISC are two computers architectures that are used by CPUs.
Complete this drag and drop activity to highlight the characteristics of RISC & CISC processors.

instructions
several
Complex
Reduced
Software
circuitry
1
Desktop
simpler
Embedded devices
Many
clock cycle

RISC Architecture

  • A RISC ( Instruction Set Computers) processor can only decode a small number of
  • A RISC processor has a design so is easier to design and manufacture.
  • A RISC processor processes one instruction per (= machine cycle).
  • In a RISC processor: 1 instruction = 1 FDE Cycle = Clock Cycle
  • Software is more complex to write with a RISC processor.
  • Typical Use: (e.g. Washing Machines, GPS SatNav, mobile phones etc…)

CISC Architecture

  • A CISC ( Instruction Set Computers) processor can decode a larger number of instructions.
  • A CISC processor has a complex design/.
  • A CISC processor processes one instruction using clock cycles (= machine cycles).
  • In a CISC processor: 1 instruction = 1 FDE Cycle = Clock Cycles
  • is easier to write with a CISC processor.
  • Typical Use: , Laptop

Parallax Scrolling Effect

parallax-scrolling-effect2D arcade video games often use a frame based approach. This means that the screen is refreshed every so often (for instance every 20 milliseconds). This enables to animate the Graphical User Interface of the game making the game more engaging.

When the main character is moving across the screen, a parallax scrolling effect can be used to animate the background according to the speed of the player.

A parallax effect is based on the idea that when your character is moving side to side, the objects closer to the camera appear to move faster, while the objects in the distance appear to move more slowly.

Parallax Effect Animation by Nathaniel Domek.

Parallax Effect Animation by Nathaniel Domek.

A parallax scrolling effect is sometimes used in video games to draw and animate the background. This technique is used for instance in the video games Angry Birds and Flappy Bird. It is based on the idea that the background landscape consists of different layers: the foreground closed to the camera viewpoint, short distance background layers (e.g. trees, buildings) and long distance background layers (e.g. mountains).

You can read more about Parallax Scrolling on this page: https://en.wikipedia.org/wiki/Parallax_scrolling

In this challenge we will draw a background consisting of three mountain ranges each having its own skyline. To create our parallax effect we will animate each skyline to translate horizontally at a different speed.

Parallax Effect in 3D games


Parallax effect algorithms can be a lot more complex especially when applied to 3D video games. Such Parallax effect algorithms will involved a lot of trigonometric calculations!

Parallax Effect in a 3D video game

Parallax Effect in a 3D video game

Parallax Scrolling Effect in Web Design


This technique is now used by web-designer to add a parallax animation effect to a web page when the user scroll down the page. It is based on the idea that different components of the web page (background pictures, pictures and video clips, header & footer sections, navigation bar, etc.) are positioned on different layers which will scroll at a different speed when the user scroll down the page.

Layer Cake using Python Turtle

layer-cakeIn this challenge we will use Python Turtle to create and draw a layer cake.

The code provided at the bottom of this blog post is using a few computing concepts such as:

  • A list to store the parameters of the layers of our cake,
  • A dictionary to match specific colour codes to different ingredients,
  • (x,y) coordinates to position the turtle on the screen.


List?


In Python, a list is used to save a collection of values. For instance, to save all the different days of the week we could declare a variable called “daysOfTheWeek” and assign a list as follows (Notice the use of square brackets):

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

Based on this what do you think len(daysOfTheWeek) would return?
What’s about daysOfTheWeek[0]?
Or daysOfTheWeek[3]?

Looping through a list


It is possible to access each value of a list one at a time using a for loop. Look at the following code to print the seven days of the week.

daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

for day in daysOfTheWeek:
    print(day)

Dictionary?


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"])

Layer Cake Challenge


In this challenge we decided to create a list called layers to store the parameters (height and ingredient) of each layer.

Check the code below and add more layers from line 42. You can use any of the ingredients from the dictionary called ingredients.

layer-cakes

Tagged with: , ,

Computing Operators – Take the Quiz!

While programming with high-level languages such as Python, you will use four different types of operators as follows:

  • The assignment operator ( = ) which is used to assign a value to a variable or a constant.
  • Arithmetic operators ( +, -, *, /, MOD, DIV, ^ ) which are used to perform mathematical calculations.
  • Comparison operators ( >, <, >=, <=, ==, != ) which are used to compare values.
  • Boolean operators ( AND, OR, NOT ) which are often used to complete more than one comparison.

Did you know?


MOD is the remainder of a division. (In Python we used the symbol % instead of MOD). For instance:

    7 MOD 3 = 1

DIV is the quotient of a division. (In Python we used the symbol // instead of DIV). For instance:

    7 DIV 3 = 2

^ means “to the power of”. (In Python we used the symbol **). For instance:

    7^2 = 49

MOD, DIV and ^ are all arithmetic operators.

Take the Quiz!

Understanding Memory Address Modes

There are many ways to locate data and instructions in primary memory and these methods are called “memory address modes”.

Memory address modes determine the method used within the program to access data either from the Cache or the RAM.
In this challenge we will focus on four different memory address modes:

  • Immediate Access
  • Direct Access
  • Indirect Access
  • Indexed Access

We will use LMC programs to see how these modes can impact on the output or flow of a program. Remember, with LMC (or any assembly languages) an instruction consists of an opcode followed by an operand.
For instance:

  • Instruction: ADD 7
  • Opcode (using a mnemonic): ADD
  • Operand: 7

Memory address modes enable us to provide either a hard coded value or a memory location for the operand.

So let’s recap on the difference between these memory address modes.

Immediate AddressingDirect AddressingIndirect AddressingIndexed Addressing

Immediate Addressing


Immediate addressing means that the data to be used is hard-coded into the instruction itself. For instance:

    ADD 7

Nothing needs to be fetched from memory. This instruction means that the value 7 will be added to the value currently stored in the accumulator.

This is the fastest method of addressing as it does not involve fetching anything from the main memory at all.
memory-address-mode-immediate

Direct Addressing


Direct Addressing is a very simple way of addressing memory – it means that the operand of an instruction refers directly to a location in memory.

For example:

    ADD 7

This instruction would not add the value 7 to the accumulator. Instead it would add the value currently stored at memory location 7 (that will be need to be fetched from the Cache/RAM).

The online LMC simulator uses this memory address mode.

This memory address mode is fairly fast (not as fast as immediate addressing though).
memory-address-mode-direct

Indirect Addressing


Indirect addressing means that the address of the data is held in an intermediate location so that the address is first ‘looked up’ and then used to locate the data itself. Fetching the value is a two step process: First the indirect address is used to locate an entry into a lookup table (called Vector Table) where the actual address of where the value can be fetched from is stored.
;
So, indirect addressing mode is a two steps process: the operand is an address towards a memory location that contains an address where the value can be fetched from.
memory-address-mode-indirect

Indexed Addressing


Indexed addressing means that the final address for the data is determined by adding an offset to a base address.

This memory address mode is ideal to store and access values stored in arrays. Arrays are often stored as a complete block in memory (A block of consecutive memory locations). The array has a base address which is the location of the first element, then an index is used that adds an offset to the base address in order to fetch the specified element within the array.
memory-address-mode-indexed

Your Challenge


Ok so, we now understand that there are different memory address modes used in Assembly languages.

For a language like LMC, when using the online simulator, we know that only direct addressing is used.

However if we had a choice between several memory address modes, we need to find a way to specify which mode is used by an instruction.

This can be done by using a specific character.
For instance, “#” could be used to represent immediate addressing, “&” could be used to represent direct addressing, “~” for indirect addressing and “[]” for indexed addressing.

In this case there is no room for confusion to understand which memory address mode is used. e.g.

    ADD #7
    ADD &7
    ADD ~7
    ADD 7[2]

In the following challenges, we will use the notation mentioned above. Your task is to predict the output of these short programs.

Note: This notation is not an official notation. It should only be used to solve the challenges listed below.

Challenge #1
LDA &8
ADD #4
OUT
HLT
6
2
10
15
16
17

Output:

Challenge #2
LDA &8
ADD &5
OUT
HLT
6
2
10
15
16
17

Output:

Challenge #3
LDA &8
ADD ~5
OUT
HLT
7
1
10
15
13
22

Output:

Challenge #4
LDA #7
ADD &6
OUT
HLT
6
2
10
15
16
17

Output:

Challenge #5
LDA ~5
ADD ~5
OUT
HLT
7
2
10
15
16
17

Output:

Challenge #6
LDA #5
ADD 7[0]
OUT
HLT
9
3
10
15
16
17

Output:

Challenge #7
LDA #5
ADD 7[2]
OUT
HLT
6
2
10
15
16
17

Output:

Challenge #8
LDA ~5
SUB #5
OUT
HLT
7
2
10
15
16
17

Output:

Tagged with:

Parseltongue Encoder

parseltongueIn the second book of the Harry Potter Series, “The Chamber of Secrets” by J.K. Rowling, Harry Potter finds out that he can communicate with snakes using the Parseltongue language.

In this challenge we will write a Python script to translate English to Parseltongue and vice-versa.

Step 1: Parseltongue Encoder


To encode a message into Parseltongue you need to insert the string sequence “sss” between each character of your message. e.g.

Your message:

I can speak to snakes using Parseltongue.

In Parsletongue:
Isss ssscsssasssnssssssspsssesssasssksss ssstsssosss sssssssnsssasssksssesssssss sssusssssssisssnsssgsss sssPsssasssrssssssslsssessstsssosssnsssgsssusssesss.sss

Step 2: Parseltongue Decoder


To decode a message from Parseltongue remove the “sss” character sequences by only keeping 1 character out of 4 from the encoded message.

Python Code


Check the following code, which uses two subroutines (functions) called encode() and decode() to encode a message in Parseltongue or decode a message from Parseltongue. Both functions use a technique called string concatenation to add one letter at a time to the message or cypher being generated.

Did you know? Encoding and decoding secret messages is a key application of Computer Science called cryptography. An encoded message is called a cipher.

Your Challenge


As a wizard at Hogwarts school of witchcraft and wizardry, Harry Potter often needs to decipher secret messages. In this set of challenges you will write Python subroutines to encode or decode secret messages using a range of techniques.

Task 1: Mumbled Words


The Parseltongue coding technique described above is not very secure. It would be easy for anyone to look at a cipher text and to be able to find a way to decipher it without being told how to in the first instance.

To make this encryption technique more secure we will adapt the encode() function implemented in the trinket above. Instead of adding the string “sss” after each character we will add three random letters.

By completing this challenge, we are going to learn how to use ASCII code when manipulating strings.
You will use the chr() and ord() python instructions to convert characters into ASCII code and vice versa.
For instance:

  • print(chr(97)) would display the letter “a” on screen as 97 is the ASCII code for character “a”.
  • print(ord(“a”)) would display the 97 on screen as 97 is the ASCII code for character “a”.

To complete this challenge, you may want to use our ASCII code helpsheet

The code to generate a random letter is as follows:

import random
randomLetter=chr(randint(97,122))

Use this code to tweak the the encode() function. The decode() function should not need to be updated and should still work with this new encryption technique.

Test your code. Do you find the cipher text to be more secure?

Task 2: Reversi Formula


Using this encryption techniques the cipher message is based on the actual message with the letters of the message appearing in reverse order. e.g.
Your message:
Welcome to Hogwarts School

Cipher:
loohcs strawgoH ot emocleW

Using this encryption technique, the same function can be used to both encode and decode a message.

Your task is to implement one function used to encode/decode a message, applying the “Reversi formula”.

Task 3: Intertwined Messages


Create two new functions to encode and decode two messages at the same time by intertwining each letter of these messages. Your encode() function will take two parameters, message1 and message2, and generate a cipher by intertwining each letter of both messages, one letter at a time.

intertwined-messages

Task 4: Caesar Cypher


In cryptography, a Caesar cipher, also known as shift cipher, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the message to encrypt is replaced by a letter some fixed number of positions down the alphabet.

You will find out more about this technique by following this link.

Task 5: Your Turn


Can you think of any other approach you could use to encrypt a message? You may combine several of the techniques listed above, as combining several techniques will make your cipher more difficult to decode hence it will be a lot more secure!

Automatic Petrol Pump Algorithm

petrol-pumpIn this challenge we will implement an algorithm to be used in an Automatic Petrol Pump to interact with the customer and calculate the total cost of filling up their vehicle.

The fuel options and tariffs at this petrol station are as follows:

  • Unleaded: £1.17 per litre,
  • Super Unleaded: £1.27 per litre,
  • Diesel: £1.21 per litre,
  • Diesel Premium: £1.34 per litre,

The petrol pump will interact with the customer by asking the following questions:

  • What fuel do you require?
  • Do you want to fill up (full tank capacity) and if not how many litres of fuel do you require?

The petrol pump will use this information provided by the customer as well as the tariffs provided above to calculate the total cost of this order.

To simulate a real life situation, we will assume that the customer’s vehicle has a tank capacity of 55 litres.
We will also assume that when the customer reaches the petrol station, the vehicle still has some fuel left. To simulate this we will generate a random number between 0 and 55. This number will represent the number of litres left in the tank before filling up.

If the customer requires a full tank, the algorithm will calculate the quantity needed as follows:

Quantity Needed = Full Tank Capacity – Current Fuel Level

If the customer specifies a desired quantity (in litres), the algorithm will fill up the tank with the required quantity. However, if the required quantity combined with the current level of fuel in the tank exceeds the full tank capacity, the required quantity will be replaced to just the quantity that is needed using the same formula as mentioned above.

Petrol Pump Algorithm: Pseudocode


The suggested pseudocode for our Automatic Petrol Pump is as follows:

currentFuelLevel = RANDOM NUMBER BETWEEN 1 AND 55
OUTPUT "You have " + currentFuelLevel + " litres left in your tank."
 
tankCapcacity = 55 
unleadedPrice = 1.17
superUnleadedPrice = 1.27
dieselPrice = 1.21
dieselPremiumPrice = 1.34

OUTPUT " ---- Our Tariffs ----"
OUTPUT "A - Unleaded: £" + unleadedPrice + " per litre"
OUTPUT "B - Super Unleaded: £" + superUnleadedPrice + " per litre"
OUTPUT "C - Diesel: £" + dieselPrice + " per litre"
OUTPUT "D - Diesel Premium: £" + dieselPremiumPrice + " per litre"

fuelChoice =  INPUT("What fuel do you need?")
pricePerLitre = 0
IF fuelChoice == "A" THEN
	pricePerLitre = unleadedPrice
ELSEIF fuelChoice == "B" THEN
	pricePerLitre = superUnleadedPrice
ELSEIF fuelChoice == "C" THEN
	pricePerLitre = dieselPrice
ELSEIF fuelChoice == "D" THEN
	pricePerLitre = dieselPremiumPrice
ELSE
	OUTPUT "Invalid Option"
END IF

fullTank = INPUT "Would you like to fill up to a full tank?"
IF fullTank == "Yes" THEN
	quantityNeeded = tankCapacity – currentFuelLevel
ELSE
	quantityNeeded = INPUT("How many litres do you need?")
	IF (currentFuelLevel + quantityNeeded) > tankCapacity THEN
		quantityNeeded = tankCapacity – currentFuelLevel
	END IF
END IF

cost =  quantityNeeded * pricePerLitre

OUTPUT "Fuel Choice: " + fuelChoice
OUTPUT "Quantity: " + quantityNeeded + " litres."
OUTPUT "Total Cost: £" + cost

Your task is to use this pseudocode to implement this algorithm using Python.

Extension Task


Add some input validation to ensure that, if the user does not provide a valid answer, the same question is being asked again.

You should use:

  • A Lookup Check to check that the user is answering either A, B, C or D when being asked about their fuel choice?
  • A Lookup Check to check that the user is answering either Yes or No to the question: Would you like to fill up to a full tank?
  • A Type Check to ensure that the user is entering a valid positive number when asked about the number of litres they do require.

Pseudocode for Lookup validation

fullTank = INPUT "Would you like to fill up to a full tank?"
WHILE fullTank NOT IN ["Yes", "No"]
	OUTPUT "Invalid Answer. Please answer the question with Yes or No"
	fullTank = INPUT "Would you like to fill up to a full tank?"
END WHILE

petrol-station

unlock-access

Solution...

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

ATM Algorithm

debit-cardsAn ATM, a.k.a. Cash Withdrawal Machine, uses a computer program to interact with the customer and count the number of banknotes to dispense based on the customer’s requested amount.

In the UK, ATM’s tend to only stock £20 banknotes and £10 banknotes and apply the following rules:

  • The minimal amount that can be withdrawn is £10,
  • The maximal amount that can be withdrawn is £200,
  • The amount to be withdrawn must be a multiple of 10 e.g. £10, £20, £30, £40, … £180, £190, £200.

Quotient (DIV) and Remainder (MOD)


To calculate how many £20 banknotes and how many £10 banknotes correspond to the requested amount, the ATM program uses two arithmetic operators called DIV and MOD.

The quotient (DIV) returns the result of the whole division. For instance:

70 DIV 20 = 3

The remainder (MOD) returns the remainder of the whole division. For instance:

70 MOD 20 = 10

By using these operators we can deduct that £70 pounds will result in:

  • 70 DIV 20 = 3 banknotes of £20
  • 70 MOD 20 = 10 (= 1 banknote of £10)

Note that in Python the DIV operator is // whereas the MOD operator is %.
For instance:

  • quotient = 70 // 20
  • remainder = 70 % 20

Also to find out if a number is a multiple of 10, we can check if number MOD 10 == 0. Effectively, if the remainder of dividing this number by 10 is null, we can conclude that this number is a multiple of 10.

ATM Algorithm: Pseudocode


The suggested pseudocode for our ATM is as follows:

WHILE TRUE
   DISPLAY "Welcome to Python Bank ATM - Cash Withdrawal"
   amount = INPUT "How much would you like to withdraw today?"
   IF (amount MOD 10) != 0 THEN
      DISPLAY "You can only withdraw a multiple of ten!"
   ELSE
      IF amount<10 OR amount>200 THEN
         DISPLAY "You can only withdraw between £10 and £200"
      ELSE
         notes20 = amount DIV 20
         notes10 = (amount MOD 20) / 10
         DISPLAY "Collect your money: "
         DISPLAY "    >> £20 Banknotes: " + notes20
         DISPLAY "    >> £10 Banknotes: " + notes10
         DISPLAY "Thank you for using this Python Bank ATM."
         DISPLAY "Good Bye."
      END IF
   END IF
END WHILE

Your task is to use this pseudocode to implement this algorithm using Python.

Extension Task 1


The bank reloads the ATM to its full capacity every morning. The ATM has a full capacity of £1,000.
Adapt this code so that:

  1. When you run the code, the ATM starts with a full capacity of £1,000.
  2. After each withdrawal, take away the amount withdrawn from the ATM total capacity.
  3. If the ATM is empty a message is displayed to inform that the ATM is not operational.
  4. If the ATM is not empty, change your code to check that it contains enough cash left to meet the amount requested by a customer before dispensing the banknotes.
  5. If the customer requested amount cannot be met, inform the customer of the maximum amount that is still available to withdraw.

Extension Task 2


When the bank reloads the ATM, it ensures that the ATM contains exactly:

  • 30 banknotes of £20.
  • 40 banknotes of £10.

Adapt your code to ensure that the ATM checks that there are enough banknotes of £20 or £10 before dispensing the banknotes. Note that if the ATM runs out of £20 banknotes, it may still be able to dispense the requested amount using £10 banknotes instead.

unlock-access

Solution...

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

Maths Homework Generator

maths-operatorsIn this challenge we have created a client-side script using HTML, CSS and JavaScript to help a Maths teacher create homework worksheets for their class.

Our HTML page uses a web form, for the teacher to select various options based on the Maths skills they want to cover and the desired level of difficulty.

The JavaScript code attached to the “Create Worksheet” button is retrieving the user inputs from the various drop down lists. It then uses these to generate list of arithmetic equations and display these on the HTML page.

HTML, CSS & JavaScript Code

See the Pen Maths Homework Generator by 101 Computing (@101Computing) on CodePen.

Your Task


Reverse engineer this JavaScript code to understand how it works. For instance can you identify:

  • The purpose of the getDropDownListValue() function defined on lines 1 to 4?
  • The purpose of lines 7 to 49?
  • The purpose of the switch case on lines 12 to 33?
  • The purpose of the for loop on line 37?
  • The purpose of lines 38, 39 and 40?
  • The purpose of line 42?
  • The purpose of line 44?

Challenge #1: 2 or 3 operands per equation?


Now that you understand how this code works, complete it in order for the Maths teacher to be able to chose the number of operands per equations. For instance, if the Maths teacher chooses two operands it will generate equations such as “2+7”. If the teacher chooses three operands, an example of equation could be “2+4-7”.

Challenge #2: Find the missing operand


Change the code to generate equations with a missing operand. For instance: “2 + ??? = 9”

Challenge #3: Linear Equations


Change the code to generate linear equations. For instance: “3x + 2 = 11”

Challenge #4: Quadratic Equations


Change the code to generate quadratic equations. For instance: “4x2 + 5x + 2 = 0″

Prolog – Sorting Hat Challenge

hogwarts-sorting-hatProlog is a language built around the Logical Paradigm: a declarative approach to problem-solving.

There are only three basic constructs in Prolog: facts, rules, and queries.

A collection of facts and rules is called a knowledge base (or a database) and Prolog programming is all about writing knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and rules which describe some collection of relationships that we find interesting.

So how do we use a Prolog program? By posing queries. That is, by asking questions about the information stored in the knowledge base. The computer will automatically find the answer (either True or False) to our queries.

Source: http://www.learnprolognow.org/

Knowledge Base (Facts & Rules)


Check the following knowledge base used by the Sorting Hat in the Harry Potter story:

/* Facts */
brave(harry).
loyal(harry).
loyal(cedric).
loyal(luna).
fair(harry).
fair(hermione).
patient(cedric).
clever(cedric).
clever(hermione).
curious(luna).

friend(harry,hermione).
friend(harry,ron).
enemy(harry,malfoy).

/* Rules */
belongToGriffindor(X):-brave(X), loyal(X).
belongToGriffindor(X):-friend(harry,X).
belongToHufflepuff(X):-patient(X), loyal(X).
belongToRavenclaw(X):-curious(X).
belongToSlytherin(X):-enemy(harry,X),\+loyal(X).

Note that \+ means NOT

Queries


We can now query this database. For each of the queries listed below, what do you think the computer will return?

True or False Queries:

?-belongToGriffindor(harry).
?-belongToGriffindor(malfoy).
?-belongToGriffindor(hermione).
?-belongToSlytherin(hermione).
?-belongToSlytherin(malfoy).
?-belongToHufflepuff(cedric).

Other Queries:

?-belongToGriffindor(harry).
?-brave(X).
?-fair(X).
?-friend(harry,X).
?-belongToGriffindor(X).
?-belongToSlytherin(X).

Task #1: Try It Online


Test all of the above queries online to see what they return:
https://swish.swi-prolog.org/p/Harry%20Potter%20-%20Sorting%20Hat.pl

Task #2: Griffindor or Ravenclaw?


Can you add a few more facts for a student called “Cho-Chang” who would meet all the requirements to belong to both Griffindor and Ravenclaw.

As a student should only belong to one house, update the rule for belongToRavenclaw() to make sure this rule only returns True for students who are curious but do not already belong to Griffindor.

Extension Task:


Add a few facts and rules to this knowledge base. Create your own queries using the new facts and rules you have added.

Tagged with: