More results...

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

Binary Additions using Logic Gates

In our previous blog post “from transistors to processors” we found out that the CPU consists of logic gates, which are made using transistors.

In this blog post we are looking at how these logic gates can be combined to create an integrated circuit used by the ALU (Arithmetic and Logic Unit of the CPU) to add two 8-bits binary numbers together.

First let’s recap on how a binary addition works:

Half-Adder Circuit


A half-adder circuit is used to add two bits of data together and is based on the following Truth Table.
half-adder-truth-table

A half-adder circuit consists of two logic gates as follows:
Half-Adder

You can test this circuit by clicking on the picture below:

Full-Adder Circuit


A full-adder circuit is used to add three bits of data together and is based on the following Truth Table.
full-adder-truth-table

A full-adder circuit consists of two half-adder circuits and an OR gate connected as follows:
Full-Adder

You can test this circuit by clicking on the picture below:

Full Binary Addition


By connecting an half-adder circuit with 7 full-adder circuits we can create a circuit to implement a full binary addition of two 8-bits binary numbers:
Binary-addition-truth-table

Full circuit:
Binary-addition-using-binary-adder-circuits

Tagged with: ,

From transistors to micro-processors

Vacuum Tubes are the precursors of transistors

Vacuum Tubes are the precursors of transistors

Vacuum Tubes and Transistors:

Many consider the transistor to be one of the most important inventions of all time.

Though the precursors of the transistor were invented in 1907 (at the time they were not transistors yet, they were vacuum tubes called valves), these were soon replaced by smaller components called transistors. These are still the key components of modern computers nowadays.

So what is a transistor?
A transistor is an electronic component with three pins. Basically, a transistor is a switch (between two of the pins: the collector and the emitter) that is operated by having a small current in the third pin called the base.

Use the checkboxes below this transistor to understand how applying a voltage to the base of a transistor is equivalent to turning on a switch.

transistor-00

Apply voltage to: Base   –    Collector

A transistor acts as a switch, operated by applying a current to the base.

A transistor acts like a switch, operated by applying a small current to the base.

Transistors come in many shapes and sizes

Transistors come in many shapes and sizes

Transistors are made by layering three types of materials: conductorsinsulators and semiconductors.

Logic Gates?


Logic Gates are made by combining transistors. They enable to apply logic to small currents which are either turned on or off and represent binary information inside a computer. Computers are made by combining logic gates together.

Use the tabs below to see how some of the key logic gates are built using transistors:

AND GateOR GATENOT GATENAND GATE
transistor-AND-Gate
transistor-OR-Gate
transistor-NOT-Gate
transistor-NAND-Gate

Integrated Circuits?


An integrated circuit (also referred to as a chip, or a microchip) is a set of electronic circuits on one small flat piece (or “chip”) of semiconductor material, normally silicon. The integration of large numbers of tiny transistors into a small chip results in circuits that are smaller, cheaper, and faster than those constructed of discrete electronic components.

Integrated Circuit 7408: Quad 2-input AND gate

Integrated Circuit 7408: Quad 2-input AND gate

More complex integrated circuits include binary adders (half-adder, full adder used to perform binary additions) and flip-flop circuits used to implement volatile memory.

List of 7400 series integrated circuits:
https://en.wikipedia.org/wiki/List_of_7400_series_integrated_circuits

Mirco-Processors?


A microprocessor is a computer processor which incorporates the functions of a computer’s central processing unit (CPU) on a single integrated circuit (or at most a few integrated circuits). The microprocessor is a multipurpose, clock driven, register based, digital-integrated circuit which accepts binary data as input, processes it according to instructions stored in its memory, and provides results as output.
A microprocessor is a computer processor which incorporates the functions of a computer's central processing unit (CPU) on a single integrated circuit

A microprocessor is a computer processor which incorporates the functions of a computer’s central processing unit (CPU) on a single integrated circuit



5 Generations of Computers

1st Generation computers used Vacuum Tubes

1st Generation computers used Vacuum Tubes

1st Generation Computers: Vacuum Tubes

Back in the 1950s, computers consisted of vacuum tubes called valves (the precursors of transistors). These valves were quite bulky, like electric bulbs, and produced a lot of heat. The installations used to fuse frequently.

Punch cards, paper tape, and magnetic tape were used as input and output devices. 1st Generation Computers were programmed using machine code.

1st Generation Computers were very expensive and only large organisations were able to afford them.


2nd Generation computers used Transistors

2nd Generation computers used Transistors

2nd Generation Computers: Transistors

In the early 1960s, 2nd Generation computers used transistors to replace the vacuum tubes of 1st generation computers. Therefore 2nd Generation computers were cheaper, consumed less power and were more compact in size. They were also more reliable and faster. More transistors could be used to create more complex computers.

Magnetic tape and magnetic disks were used as secondary storage devices as well as punched tapes which were still used.

2nd Generation Computers were programmed using assembly language and high-level programming languages such as FORTRAN or COBOL. 


3rd Generation computers used integrated circuits.

3rd Generation computers used integrated circuits.

3rd Generation Computers: Integrated Circuits

In the second half of the 1960s, integrated circuits were used by 3rd Generation Computers. An integrated circuit has many transistors, resistors, and capacitors along with the associated circuitry. This development made computers smaller in size, more reliable and efficient.

3rd Generation Computers were programmed using High-level languages (FORTRAN, COBOL, PASCAL, BASIC, ALGOL-68 etc.).

Atari 7800 - Motherboard

Atari 7800 – Motherboard


4th and 5th Generation computers use micro-processor chips.

4th and 5th Generation computers use micro-processor chips.

4th Generation Computers: Micro-Processors

In the 1970s, Computers of 4th generation used Very Large Scale Integrated (VLSI) circuits. VLSI circuits having about 5,000 transistors on a single chip called a micro-processor.

Fourth generation computers became more powerful, compact, reliable, and affordable. They started the Personal Computer (PC) revolution.


5th Generation Computers: Nowadays

The period of fifth generation is 1980-to date. In the fifth generation, VLSI technology became ULSI (Ultra Large Scale Integration) technology, resulting in the production of microprocessor chips having ten million electronic components.


Moore’s Law


The rate at which transistor counts have increased generally follows Moore’s law, which observed that the transistor count doubles approximately every two years. As of 2016, the largest transistor count in a commercially available single-chip processor was over 7.2 billion.

Tagged with: ,

Air Flight Route Planner

plane-globeFor this challenge you will use a graph data structure to create an Air Fligh Route Planner for a fictitious airline company offering flights across Europe.

Here is a map showing all the direct flights offered by this airline company:
European-Airports-Graph

Your task consists of implementing a graph data structure to store all the airports and connections for the above map using Python.

You will then use a range of algorithms to let the user choose an origin and a destination (e.g. From Dublin to Athens) and your program will:

  • Inform the user if there is a direct fight to match the user requirements,
  • If not, inform the user of the shortest route between the two airports, indicating all the stops between both airports.

Tip: To complete this challenge, we recommend you to be familiar with graph data structures (and how to implement them in Python) and key algorithms used with graphs (including shortest path algorithm) by reading our blog post: London Underground Journey Planner.

Complete the code using Python


unlock-access

Solution...

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

The Social Network

social-network

Six Degrees of Separation


The Six degrees of separation is an idea that was originally set out by Frigyes Karinthy in 1929 and that can be applied to Social Networks such as Facebook.

It is based on the idea that all human beings in the world are six or fewer steps away from each other so that a chain of “a friend of a friend” statements can be made to connect any two people in a maximum of six steps.

Using a Graph:


In order to verify this concept, we are going to use a graph data structure where all the nodes of the graph will represent the members of a small social network that contains 100 members.

social-network-graph
The connections between the nodes will represent the friendship relationships between two members.

We will then ask the end-user to enter 2 names and use an algorithm to find out the shortest friendship chain between these two members (if it exists).

Using Graphs in Python


Most programming languages do not necessary provide direct support for graphs as a data type. Python for instance does not have a graph data structure. However it is possible to create a graph data structure in python using any of the following two methods:

  • Method 1: Adjacency Matrix: Using a 2D array (or list of lists in Pyhon)
  • Method 2: Us: Using a hash table (dictionary) of lists

Let’s investigate both approaches.

Method #1: Implementing a graph using an adjacency matrix

An adjacency matrix is a 2D array that has the same number of rows and columns: 1 row and 1 column per node of the graph.

Eshan Sonia Jackson Naomi Zheng Kamal Oliver May
Eshan
Sonia
Jackson
Naomi
Zheng
Kamal
Oliver
May

Here is how we could implement this adjacency matrix in Python:

members =    ["Eshan","Sonia","Jackson","Naomi","Zheng","Kamal","Oliver","May"]

#Adjacency Matrix: (2D array to store friendship data)
friendship = [[False , True  , False   , False , False , False , False  , True ], #Eshan
              [True  , False , True    , False , False , False , False  , False], #Sonia
              [False , True  , False   , True  , False , False , False  , False], #Jackson
              [False , False , True    , False , False , True  , False  , True ], #Naomi
              [False , False , False   , False , False , False , False  , False], #Zheng
              [False , False , False   , True  , True  , False , True   , False], #Kamal
              [False , False , False   , False , True  , True  , False  , False], #Oliver
              [True  , False , False   , True  , False , False , False  , False]  #May
             ]

Now that we have saved this data into our code, we can create a small program to query this data. For instance, let’s write a program that asks the user to enter the names of two members of our social network and output whether these two members are friends or not.

Note that using an adjacency matrix is not recommended for very large graphs where you have two many nodes. This is because, for a graph of n nodes the resulting 2D array would contain n2 values. This is can quickly be too demanding in terms of memory requirements (O(n2) Big O Notation)

Method #2: Implementing a graph using a hash table

An alternative approach to implement a graph is to use a hash table where each node of the graph is a key, and the value for each key is the list of adjacent nodes of this node. For instance, here is the Python code to represent the connections from our friendship graph:

members = {'Naomi': ['Jackson', 'May', 'Kamal'],
'May': ['Eshan', 'Naomi'],
'Jackson': ['Naomi', 'Sonia'],
'Kamal': ['Oliver', 'Naomi', 'Zheng'],
'Eshan': ['Sonia','May'],
'Sonia': ['Eshan','Jackson'],
'Zheng': ['Kamal','Oliver'],
'Oliver': ['Zheng','Kamal']
}

This graph is a hash table (a.k.a dictionary) where the keys are the nodes of the graph. For each key, the corresponding value is a list containing the nodes that are connected by a direct arc from this node.

Let’s see how we can use this graph to complete our friendship checker program:

Shortest Path Algorithm


Two find out the degrees of separations between two members of our social network, we will need to identify the shortest path between these two members (nodes). We will use a shortest path algorithm to do so, using a graph based on a hash table (method #2).

Our shortest path algorithm will be based on a recursive function used to find all the friendship chains/paths that can been found between two members and identify which one is the shortest path (The path that has the smallest number of nodes).

To make this algorithm more effective we also have a stopping condition to stop exploring a path that would be longer than the shortest path found so far.

def find_shortest_path(graph, start, end, shortestLength=-1, path=[]):
  path = path + [start]
  if start == end:
    return path
  if not start in graph:
    return None
  shortest = None
  for node in graph[start]:
    if node not in path:
      if shortestLength==-1 or len(path)<(shortestLength-1):
        newpath = find_shortest_path(graph, node, end, shortestLength, path)
        if newpath:
          if not shortest or len(newpath) < len(shortest):
            shortest = newpath
            shortestLength = len(newpath)  
  return shortest

Python Code


Check the code below used the find_shortest_path() algorithm to find the shortest path between two members. It is then used to calculate the degree of separation (based on the length of the chain).


unlock-access

Solution...

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

Estimating Pi using the Monte Carlo Method

pi-3-14159One method to estimate the value of π (3.141592…) is by using a Monte Carlo method. This methods consists of drawing on a canvas a square with an inner circle. We then generate a large number of random points within the square and count how many fall in the enclosed circle.
estimating-pi-monte-carlo-method

The area of the circle is πr2,
The area of the square is width2 = (2r)2 = 4r2.

If we divide the area of the circle, by the area of the square we get π/4.

The same ratio can be used between the number of points within the square and the number of points within the circle.

Hence we can use the following formula to estimate Pi:

π ≈ 4 x (number of points in the circle / total number of points)

Python Turtle Simulation


Run the code below to estimate Pi using the Monte Carlo Method.

Note: You may reach a better estimate of Pi by:

  • Increasing the radius of the circle. (e.g. radius = 1000) as it will give you a circle with a “higher resolution”.
  • Increasing the number of dots. (e.g. total = 5000)

Extension


You can find out more about the Monte Carlo method and its applications.
unlock-access

Solution...

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

Space Invaders – 3D Pixel Art

space-invaders-pixel-artIn this blog post we will use Glowscript to create a 3D animation of a space invader.

2D Graphics used in retro arcade games consist of pixels. A 2D graphic can be described as a grid of pixels of different colours.
space-invaders-pixels

In programming we can use a 2D array data structure to represent a graphic. In Python, 2D arrays are implemented using a list of lists.

In our code (see below) we have declared a 2D array called pixels to store the value of each pixel used to represent one of the space invaders.

pixels   =   [[0,0,1,0,0,0,0,0,1,0,0]]
pixels.append([0,0,0,1,0,0,0,1,0,0,0])
pixels.append([0,0,1,1,1,1,1,1,1,0,0])
pixels.append([0,1,1,0,1,1,1,0,1,1,0])
pixels.append([1,1,1,1,1,1,1,1,1,1,1])
pixels.append([1,0,1,1,1,1,1,1,1,0,1])
pixels.append([1,0,1,0,0,0,0,0,1,0,1])
pixels.append([0,0,0,1,1,0,1,1,0,0,0])

Using a 2 nested loops we then looped through each row and each column of this array to retrieve the value of each pixel in order to create the cubes needed to create a 3D model of a space invader.

We then create a compound object to join these cubes together in a single object. Finally using an infinite while loop we animate/rotate our invader around itself.

Here is our 3D animation: (Use Google Chrome to preview this animation)


Right Click on the animation to change the view point (rotate camera angle).

Find out more…


To learn more about all the instructions you can use in GlowScript/VPython, use this on-line documentation.

Your task:


space-invaders
Create and animate all the different Space Invaders.

From 2D to 3D: Crossy Road Chicken


This technique of creating 2D graphics can also be used for 3D graphics. In this case a 3D array is used to store the pixels alongside 3 dimensions: x, y and z.

Let’s look at the code below used to create a 3D model of the chicken from the Crossy Road game:
crossy-road-chicken

Check in the code below to see how a list of lists of lists is used in Python to create a 3D array.

Also look at how, using 3 nested loops we can iterate through each “pixel” of the 3D array.

We have also used a 1D array called palette to store all the colours to be used in our 3D model.

Can you think of other games that might use 3D arrays?
mine-craft-block

Tagged with: , , , , ,

London Underground – Journey Planner

london-underground-signThe aim of this Python challenge is to investigate how graphs can be used in Computer Science and investigate the key algorithms used when manipulating graphs in Python such as an algorithm to find the shortest path between two nodes of a graph.

For this challenge we will focus on a graph used to represent the London Underground Map (Zone 1).
tubemap

Access London Tube Map

Most programming languages do provide direct support for graphs as a data type. Python for instance does not have a graph data structure. However, graphs can be built out of lists and dictionaries. For instance, here is a graph to represent some of the connections between a selection of London tube stations:

tubemap = {"Aldgate" : ["Liverpool Street","Tower Hill"],
"Aldgate East" : ["Tower Hill","Liverpool Street"],
"Angel" : ["King's Cross St. Pancras","Old Street"],
"Baker Street" : ["Marylebone","Regent's Park","Edgware Road (C)","Great Portland Street","Bond Street"],
"Bank" : ["Liverpool Street","St. Paul's","London Bridge","Moorgate","Waterloo"],
"Barbican" : ["Farringdon","Moorgate"]
#...
}

This graph is a dictionary where the keys are the nodes of the graph. For each key, the corresponding value is a list containing the nodes that are connected by a direct arc from this node.

The full dictionary with all the stations for London Underground can be found in the Python trinkets below.

Find Path Algorithm


Our first algorithm is used to determine if there is a path between two nodes of a graph, and if so it returns one path that can be used to connect both nodes. A path is a list of nodes which are connected to each others.

This algorithm uses a backtracking approach to explore different paths. It does stop as soon as a path has been found. Note that the path that will be found first may not be the shortest path though.

def find_path(graph, start, end, path=[]):
  path = path + [start]
  if start == end:
    return path
  if not start in graph:
    return None
  for node in graph[start]:
    if node not in path:
      newpath = find_path(graph, node, end, path)
      if newpath: return newpath
  return None

Find All Paths Algorithm


This second algorithm is very similar to the find_path() algorithm. The difference is that this time the backtracking algorithm will explore and return all the possible paths between the two nodes as a list of paths. (List of lists).

def find_all_paths(graph, start, end, path=[]):
  path = path + [start]
  if start == end:
    return [path]
  if not start in graph:
    return []
  paths = []
  for node in graph[start]:
    if node not in path:
      newpaths = find_all_paths(graph, node, end, path)
      for newpath in newpaths:
        paths.append(newpath)
  return paths

Find Shortest Path Algorithm


Our final algorithm is probably the most useful algorithm as it will identify amongst all the paths that have been found, which one is the shortest path (The path that has the smallest number of nodes).

To make this algorithm more effective we also have a stopping condition to stop exploring a path that would be longer than the shortest path found so far.

def find_shortest_path(graph, start, end, shortestLength=-1, path=[]):
  path = path + [start]
  if start == end:
    return path
  if not start in graph:
    return None
  shortest = None
  for node in graph[start]:
    if node not in path:
      if shortestLength==-1 or len(path)<(shortestLength-1):
        newpath = find_shortest_path(graph, node, end, shortestLength, path)
        if newpath:
          if not shortest or len(newpath) < len(shortest):
            shortest = newpath
            shortestLength = len(newpath)  
  return shortest

Python Code


We will use the find_shortest_path() algorithm to find the shortest path between two tube stations.

Zone 1 OnlyFull Map (Zone 1 to 10)

With a more complex graph, this algorithm will take longer to find the shortest path.

Extension


A backtracking algorithm can sometimes take a very long time to explore all possible paths. This is due to the complexity of the graph (e.g. tube map) which contains many nodes and connections between nodes, hence the high number of potential routes to explore using a backtracking algorithm.

More advanced algorithms can be implemented to overcome this issue. You may want to explore the following algorithms:

Tagged with: , ,

Insertion Sort Algorithm

Insertion-sort-1-9The Insertion sort algorithm is one of the key sorting algorithms used in Computer Science.

To start with, the algorithm considers the first value of a list as a sorted sub-list (of one value to start with). This iterative algorithm then checks each value in the remaining list of values one by one. It inserts the value into the sorted sub-list of the data set in the correct position, moving higher ranked elements up as necessary.

This algorithm is an O(n2) algorithm which is relatively efficient for small lists and mostly sorted lists, and is often used as part of more sophisticated algorithms.

Python Implementation of an Insertion Sort algorithm


The Python code belows let you visualise how a Insertion sort algorithm with a small set of values (from 1 to 9). The list of values is shuffled every time you run this code.

Tagged with: , ,

Bubble Sort Algorithm

Bubble-sort-1-9The Bubble sort algorithm is one of the key sorting algorithms used in Computer Science. It is a fairly simple algorithm to implement and is particularly useful when you need to find the top x values of a list.

The algorithm starts at the beginning of the data set. It compares the first two value, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent values to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass.

This algorithm’s average and worst-case performance is O(n2), so it is rarely used to sort large, un-ordered data sets. Bubble sort can be used to sort a small number of items and is a lot more effective on data sets where the values are already nearly sorted.

Python Implementation of a Bubble Sort algorithm


The Python code belows let you visualise how a Bubble sort algorithm with a small set of values (from 1 to 9). The list of values is shuffled every time you run this code.

Tagged with: , ,

Backtracking Maze – Path Finder

backtracking-maze-algorithmThe purpose of this Python challenge is to demonstrate the use of a backtracking algorithm to find the exit path of Maze.

Backtracking Algorithm


A backtracking algorithm is a recursive algorithm that attempts to solve a given problem by testing all possible paths towards a solution until a solution is found. Each time a path is tested, if a solution is not found, the algorithm backtracks to test another possible path and so on till a solution is found or all paths have been tested.

The typical scenario where a backtracking algorithm is when you try to find your way out in a maze. Every time you reach a dead-end, you backtrack to try another path until you find the exit or all path have been explored.

Backtracking algorithms can be used for other types of problems such as solving a Magic Square Puzzle or a Sudoku grid.

Backtracking algorithms rely on the use of a recursive function. A recursive function is a function that calls itself until a condition is met.

Python Code

unlock-access

Solution...

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