More results...

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

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:

Binary Expression Trees

A binary expression tree is a specific kind of a binary tree used to represent expressions. Two common types of expressions that a binary expression tree can represent are algebraic expressions and boolean expressions. These trees can represent expressions that contain both unary and binary operators.

Algebric Expression Trees


An algebric expression such as (3 * 7) + 9 consists of:

  • Operands such as 3, 7, 9 or x, y, z,
  • Binary Operators such as +, – , *, /, DIV, MOD, ^
  • Unary Operators such as –

Algebric expressions can be represented using a binary expression tree where:

  • Each node is an operator,
  • Each leaf is an operand.
algebric-expression-tree-1 Algebric Expression: (view solution)
algebric-expression-tree-2 Algebric Expression: (view solution)
algebric-expression-tree-3 Algebric Expression: (view solution)
expression-tree-question Algebric Expression:
expression-tree-question Algebric Expression:
expression-tree-question Algebric Expression:

Boolean Expression Trees


An Boolean expression such as (A OR B) AND C consists of:

  • Operands such as A, B, C,
  • Binary Operators such as AND, OR, XOR
  • Unary Operators such as NOT

Boolean expressions can be represented using a binary expression tree where:

  • Each node is an operator,
  • Each leaf is an operand.
Boolean-expression-tree-1 Boolean Expression: (view solution)
Boolean-expression-tree-2 Boolean Expression: (view solution)
expression-tree-question Boolean Expression:
expression-tree-question Boolean Expression:
Tagged with:

Traversal of a Binary-Tree

In this blog post we will investigate four key algorithms used to read through the content of a binary tree:

  • Breadth-First Traversal Algorithm
  • Depth-First Algorithms:
    • Pre-Order Traversal
    • In-Order Traversal
    • Post-Order Traversal

Binary Tree?


A Binary Tree is a data structure used in some algorithms to store data. In a binary tree each node can have up to two children.
Binary-Search-Tree

Breadth-First Traversal Algorithm


A Breadth-first traversal consists of accessing each node, one level after the other. On each layer the nodes are accessed as they appear, from left to right.
breadth-first-traversal

Depth-First Traversal Algorithms


There are three depth-first traversal agorithms which are all based on a recursive approach.
depth-first-traversal

Pre-Order Traversal Algorithm:

FUNCTION preorder-traverse(tree)
    IF tree is not empty
         visit root node of tree
         preorder-traverse(left sub-tree)
         preorder-traverse(right sub-tree)
    END IF
END FUNCTION 

In-Order Traversal Algorithm:

FUNCTION inorder-traverse(tree)
    IF tree is not empty
         inorder-traverse(left sub-tree)
         visit root node of tree
         inorder-traverse(right sub-tree)
    END IF
END FUNCTION 

Post-Order Traversal Algorithm:

FUNCTION postorder-traverse(tree)
    IF tree is not empty
         postorder-traverse(left sub-tree)
         postorder-traverse(right sub-tree)
         visit root node of tree
    END IF
END FUNCTION 

Binary Tree #1

Binary-tree-traversal-3
Breadth First: (view solution)
Depth-first Pre-order Traversal: (view solution)
Depth-first In-order Traversal: (view solution)
Depth-first Post-order Traversal: (view solution)

Binary Tree #2

Breadth First: (view solution)
Depth-first Pre-order Traversal: (view solution)
Depth-first In-order Traversal: (view solution)
Depth-first Post-order Traversal: (view solution)

Binary Tree #3

Binary-Search-Tree-2
Breadth First: (view solution)
Depth-first Pre-order Traversal: (view solution)
Depth-first In-order Traversal: (view solution)
Depth-first Post-order Traversal: (view solution)

Binary Tree #4

Binary-Search-Tree-1
Breadth First: (view solution)
Depth-first Pre-order Traversal: (view solution)
Depth-first In-order Traversal: (view solution)
Depth-first Post-order Traversal: (view solution)
Tagged with:

ASCII-Bot Challenge

ascii-bot-challengeIn this challenge we will use the print() instruction in Python to create an ASCII-bot: A robot made of ASCII characters, in other words characters that you can type with a standard QWERTY keyboard.

Python Code


This is what your code will look like:

#ASCII-Bot Challenge - www.101computing.net/ASCII-bot-challenge/

print("         +-+      +")
print("           | +-+  |   +-+")
print("     +-+   |   |  |   |    +--+")
print("       |   |   |  |   |    |")
print("       |   |   |  |   |    |")
print("   +---+---+---+--+---+----+----+")
print("   |                            |")
print("   |   +-------+     +-------+  |")
print("+--+   |       |     |       |  +--+")
print("|  |   |       |     |       |  |  |")
print("|  |   |    +--+     |    +--+  |  |")
print("+--+   |    |--|     |    |--|  +--+")
print("   |   +-------+     +-------+  |")
print("   |             +-+            |")
print("   |             | |            |")
print("   |             +-+            |")
print("   |  +--+               +--+   |")
print("   |    +-----------------+     |")
print("   |                            |")
print("   +----------------------------+")
print("")
print("      ASCII-BOT: Hello World!")

Step 1: ASCII Art


Use asciiflow.com to create your own robot using ASCII characters.

Step 2: Create the Python code


Once your ASCII art is complete click on the export-iconicon to generate the ASCII code. Copy and paste the code in the trinket window below.

Add print(“ at the beginning and “) at the end of each line of your ASCII art and check if your code is working by running the code using the play-code-iconicon.

asciiart

Tagged with:

Italian Takeaway Ordering System

An Italian Takeaway is asking you to write a computer program to facilitate the ordering process and automatically calculate the total cost of an order.

They have stored their menu and all prices into a text file with the following information:

Code;Description;Price;


TextFilefood-menu.txt

When a customer order food, they give the lists of codes they would like order. For instance a customer could order the following: S4,P3,P7,X2,D4,C1,W2

Your program should allow the customer to order as many options from the menu as they need. For each option, it should lookup the price in the text file provided. It should then calculate and output the total cost of the order.

To complete this challenge you will need to read more about how to read through a CSV file.

Complete the Code


Testing


Once you have completed the code check that it produces the expected output by performing the following tests:

Test # Input Values Expected Output Actual Output
#1 S4,P3,P7 £28.89
#2 P10,S1 £16.00
#3 P4,D2,C2 £19.30

Extension Task


Add some input validation routines to your code so that the customer can only enter a valid code from the menu.

Video Tutorial / Solution



unlock-access

Solution...

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

Cinema Booking Challenge

A cinema has created a booking system for their main theatre which consists of 48 seats, organised in 6 rows of 8 seats.

To store information as to whether a seat is booked or available, the program uses a 2-dimensional array (in python a list of lists). Each cell of the array contains the value 1 if the seat is booked or 0 if it is empty:

The following code is used to check whether a specific seat (identified by its row and column number) is already booked or not:

Challenge #1: Booking Options


Add a menu system to this code with 4 otpions:

  • Option 1: Book a seat by row/column
  • Option 2: Book a seat close to the front
  • Option 3: Book a seat close to the back
  • Option X: Exit
View Solution
#Cinema Booking Challenge - www.101computing.net/cinema-booking-challenge
seats = []
seats.append([0,0,1,1,0,1,1,1])
seats.append([0,1,1,0,0,1,0,1])
seats.append([1,0,0,1,0,1,1,0])
seats.append([0,1,1,1,0,0,0,1])
seats.append([0,0,1,1,0,1,0,0])
seats.append([1,0,1,1,0,0,1,1])

def displayBookings():
  #Display Bookings
  print("")
  print("======================================")
  print("")
  for row in seats:
    print(row)
  print("")
  print("======================================")

def checkSeat():
  row = int(input("Enter a row number (between 0 and 5)"))
  column = int(input("Enter a column number (between 0 and 7)"))
  
  if seats[row][column]==1:
    print("This seat is already booked.")
  else:
    print("This seat is empty.")

def bookSeat():
  print("Booking a Seat by Row/Column")
  #....
    
def bookSeatAtFront():
  print("Booking seat at the front")
  #....
  
def bookSeatAtBack():
  print("Booking seat at the back")
  #....
  

#Main Program Starts Here
print("+============================+")
print("+   CINEMA BOOKING SYSTEM    +")
print("+============================+")
print("")
print("1 - Book a seat by row/column")
print("2 - Book a seat at the front")
print("3 - Book a seat at the back")
print("x - Exit")

choice = input("Your Choice?")
if choice=="1":
  bookSeat()
  displayBookings()
elif choice=="2":
  bookSeatAtFront()
  displayBookings()
elif choice=="3":
  bookSeatAtBack()
  displayBookings()
elif choice=="x":
  print("Good Bye!")
else:
  print("Invalid Menu Option")
  print("Good Bye!")

Option 1:

Let the user enter a row and column number. If the seat is available, book it by changing the corresponding value in the array to a 1. If it’s not available carry on asking for a row and column number until a free seat is found.

View Solution
def bookSeat():
  booked = False
  while booked == False:
    row = int(input("Enter a row number (between 0 and 5)"))
    column = int(input("Enter a column number (between 0 and 7)"))

    if seats[row][column]==1:
      print("This seat is already booked.")
    else:
      print("This seat is empty.")
      print("Booking seat...")
      seats[row][column]=1
      print("We have now booked this seat for you.")
      booked=True

Option 2:

If the user chooses this option the program should automatically book the first seat available starting from the front row (row 0) from the left (column 0), and scanning each seat one by one until a free seat is found. The program should inform the user which seat (row/column) has been booked.

View Solution
def bookSeatAtFront():
  print("Booking seat at the front")
  for row in range(0,6):
    for column in range(0,8):
      if seats[row][column]==0:
        print("Booking seat...")
        print("Row: " + str(row))
        print("Column: " + str(column))
        seats[row][column]=1
        print("We have now booked this seat for you.")
        #Stop Searching
        return True
  #We scanned the whole theatre without finding an empty seat:
  print("Sorry the theatre is full - Cannot make a booking")
  return False 

Option 3:

If the user chooses this option the program should automatically book the first seat available starting from the back row (row 5) from the right (column 7), and scanning each seat one by one until a free seat is found. The program should inform the user which seat (row/column) has been booked.

View Solution
def bookSeatAtBack():
  print("Booking seat at the back")
  for row in range(5,-1,-1):
    for column in range(7,-1,-1):
      if seats[row][column]==0:
        print("Booking seat...")
        print("Row: " + str(row))
        print("Column: " + str(column))
        seats[row][column]=1
        print("We have now booked this seat for you.")
        #Stop Searching
        return True
  #We scanned the whole theatre without finding an empty seat:
  print("Sorry the theatre is full - Cannot make a booking")
  return False   

Challenge #2: Saving Bookings in a CSV file


Create a CSV file containing the following data:
0,0,1,1,0,1,1,1
0,1,1,0,0,1,0,1
1,0,0,1,0,1,1,0
0,1,1,1,0,0,0,1
0,0,1,1,0,1,0,0
1,0,1,1,0,0,1,1

  • When the program starts, the seats array should be initialised by reading the content of the CSV file.
  • View Solution
    def loadBookings():
      file = open("seats.csv","r")
      row = 0
      for line in file:
        data = line.split(",")
        if len(data)==8: #Only process lines which contain 8 values
           for column in range (0,8):
              seats[row][column] = int(data[column])
           row = row + 1
      file.close()
  • When the user exit the program (option X), the content of the CSV file should be replaced with the content of the seats array.
  • View Solution
    def saveBookings():
      file = open("seats.csv","w")
      for row in range(0,6):
        line=""
        for column in range(0,8):
          line = line + str(seats[row][column]) + ","
        line = line[:-1] + ("\n") #Remove last comma and add a new line
        file.write(line)    
      file.close()

To complete this challenge you will need to read more about how to read through a CSV file.

Challenge #3: Resetting the Array


Add an extra menu option (option 4). If this option is chosen, the seats array should automatically be reset so that all seats are reset to 0.

Challenge #4: Improvements


Can you think of any other features that could be useful to improve this cinema booking system? This could include:

  • A login screen so that only authorised staff can access the booking system,
  • An option to cancel a booking,
  • A message to inform the end-user of how many seats are left,
  • A message to inform the end-user when the theatre is full (all the seats have been booked),
  • Input validation (e.g. row number between 0 and 5, column number between 0 and 7),
  • Multiple bookings where the computer can identify if the user wants to book several (e.g. 2 or 3) consecutive seats on the same row,
  • etc.
unlock-access

Solution...

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

Top 10 Challenge


In this challenge, you will create a computer program to ask the end-user to try to guess the top 10 largest countries per area.

To do so you will use a list in Python, containing the top 10 countries as follows:

#Top 10 largest countries in the world per area
largestCountries = ["Russia","Canada","USA","China","Brazil","Australia","India","Argentina","Kazakhstan","Algeria"]

Using this list, what do you think would be the values of:

  • largestCountries[0],
  • largestCountries[2],
  • largestCountries[9]?

We have started the code by asking the user to enter the name of a country and checking whether or not this country is in the top ten list.

Your aim is to tweak this code to allow the user to name as many countries as they wish. Each time they get one country from the top 10 list, they score one point. The end-user should not need to list the ten countries in the right order. However the user should not score additional points by naming the same country more than once.

The program should stop if the user has guessed all 10 countries or when the user presses “x” to quit the game.

Extension Task


Use the time library and use a timer to give a maximum of 60 seconds for the user to guess all ten countries.
unlock-access

Solution...

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

Planets Top Trumps

For this challenge we will create a variant of the game of Top Trumps using 9 cards, one for each of planet of our Solar System.

We will store all the cards and data about the planets in a list of lists, equivalent to a two-dimensional array, called planets. The “array” will contain 9 rows (from 0 to 8) and 5 columns (0 to 4) with the following columns/fields:

  • Name of the planet,
  • Distance from the Sun (in million km),
  • Size (Diameter) in km,
  • Orbital Period in days,
  • Number of Moons.

We will then be able to access a single piece of data using indexes as follows:
planets-list-of-list

Game Rules


We will write a python program based on the planets array (list of lists) which:

  1. Randomly picks a planet/card from the deck and display all its data on screen,
  2. Randomly picks a planet for the computer, without displaying it on the screen,
  3. Asks the end-user which criteria to compare for this round: (1-Distance from the Sun, 2-Size, 3-Orbital Period,4-Number of Moons),
  4. Compares both cards using the chosen criteria,
  5. Tells the player whether they won, drew or lost,
  6. Gives the computer or the player points: 3pts for a win, 1pt for a draw,
  7. Displays both the computer and the player’s scores and repeats the whole process until the player or the computer reaches a score of 12 and hence win the game.

Complete The Code


Tagged with:

US Presidents Quiz

american-presidentSince the establishment of the United States of America, in 1789, 45 people have served as president, the first one being George Washington.

For this challenge you will use a text file listing all of these US presidents in chronological order. (See text file below.) You will then write a Python program to randomly pick two presidents from this list of 45 presidents. Your program will display the name of both presidents and ask the end-user who is the most recent president amongst the two presidents being displayed. For instance the program will output the following question:

Who was the most recent president?
A) John F. Kennedy or B) Richard Nixon.

The game carries on as long as the user is correct. For each correct answer the user will score 10 points. The game ends once the user gets a wrong answer.

To complete this challenge you will need to read more about how to read through a CSV file.

The text file we will use contains one line per US President. On each line it stores a number (position from 1 to 45), the name of te president, the year their presidency started, the year it ended as follows:

Number,Name,StartYear,EndYear
TextFileus-presidents.csv

Complete the Code


Extension


When asking the question, give the user the option to ask for a clue (by typing answer C). When the user asks for a clue, the program will output the starting and ending date of the presidency of one of the two presidents. The user will then have to answer the intial question.
unlock-access

Solution...

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

This website will store some information about your preferences on your own computer inside a tiny file called a cookie. A cookie is a small piece of data that a website asks your browser to store on your computer or mobile device. The cookie allows the website to remember your actions or preferences over time.

You can delete all cookies that are already on your computer, and you can set most browsers to prevent them from being placed. However, if you do this, you may have to manually adjust some preferences every time you visit a site, and some services and functionalities may not work.

Most browsers support cookies, but you can set your browser to decline them and can delete them whenever you like. You can find instructions here for how you can do that on various browsers.

This website uses cookies to:

  1. Identify you as a returning user and to count your visits in traffic statistics analysis
  2. Remember your custom display preferences (such as light/dark theme option)
  3. Provide other usability features, including tracking whether you have already given your consent to cookies

Enabling cookies is not strictly necessary for the website to work but it will provide you with a better browsing experience.

The cookie-related information is not used to identify you personally and is not used for any purpose other than those described here.

There may also be other types of cookies created after you have visited this website. This site uses Google Analytics, a popular web analytics service that uses cookies to help to analyse how users use the site. The information generated by the cookie about your use of this website (including your IP address) will be transmitted to and stored by Google on servers in the United States. Google will use this information for the purpose of evaluating your use of other website, compiling reports on website activity, and providing other services relating to website activity and internet usage. Google may also transfer this information to third parties where required to do so by law, or where such third parties process the information on Google’s behalf. Google undertakes not to associate your IP address with any other data held by Google.