More results...

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

Hogwarts Sorting Hat Algorithm

In this challenge, we will implement an algorithm to help the sorting hat at Hogwarts school of witchcraft and wizardry decide which house you would more likely belong to.

When a new student join Hogwarts school, they are assigned to one of the four school houses depending on their personal qualities. The four houses are:

  • Gryffindor values bravery, loyalty and chivalry
  • Ravenclaw values curious minds, creativity and inventiveness
  • Hufflepuff values kindness, friendliness, patience
  • Slytherin values ambition and competitiveness

Now let’s look at our algorithm step by step using a flowchart that we will convert into a Python program.

Our algorithm will work by asking the end-user some yes/no questions to help define their personality and main qualities. Based on the answers provided by the end-user, the algorithm will allocate points to four score variables, one for each house.

At the end, after collecting all the end-user’s answers, the algorithm will find which house scored the most point and inform the end-user of the house that is a best match to their personality.

Step 1: Initialising the Sorting Hat Algorithm

FlowchartPython Code
Flowchart

Python Code

# Hogwarts Sorting Hat Algorithm

# Step 1: Initialise the Sorting Hat
print("~~~~~~~~~~~~~~~~~~~~~~~")
print("~                     ~")
print("~   The Sorting Hat   ~")
print("~                     ~")
print("~~~~~~~~~~~~~~~~~~~~~~~")
print("")
print("Welcome to Hogwarts school of witchcraft and wizardry!")
print("Answer the following questions to be assigned your new house.")
print("")
gryffindor = 0	
hufflepuff = 0
ravenclaw = 0
slytherin = 0

Python Code

Complete the Python code below…

Step 2: Asking Yes/NO Question

Using IF statements
Let’s ask our first question to see if the user is considering themselves as being a brave person. If so we will add one point to their score for Gryffindor as bravery is a trait of the Gryffindor house.

FlowchartPython Code
Flowchart

Python Code

# Step 2: Collect user inputs
brave = input("Are you a brave person?").lower()
if brave=="yes":
  gryffindor = gryffindor + 1
Using IF and ELSE statements
Now let’s consider another question which could lead to two outcomes depending on the user’s answer. For instance let’s ask if the user considers themselves as being patient. If the answer is “yes” we will increase their Hufflepuff score by one however, if their answer is “no” we will increase their Slytherin score by 1 as students from the Slytherin students tends to be rather impatient.

FlowchartPython Code
Flowchart

Python Code

patient = input("Would you describe yourself as being patient?").lower()
if patient=="yes":
  hufflepuff = hufflepuff + 1 
else:
  slytherin = slytherin + 1 

Step 3: Adding more questions

It’s now your turn to work out the Python code needed to add the following 8 questions:

Question 3Question 4Question 5Question 6Question 7Question 8Question 9Question 10

Step 4: Displaying the scores for each house

FlowchartPython Code
Python Code

# Step 4: Display the scores
print("Total Scores:")
print(" - Gryffindor:" + str(gryffindor))
print(" - Ravenclaw:" + str(ravenclaw))
print(" - Hufflepuff:" + str(hufflepuff))
print(" - Slytherin:" + str(slytherin))

Step 5: Selecting the house with the highest score

FlowchartPython Code
Python Code

# Step 5: Select the house with the highest score
if gryffindor>=ravenclaw and gryffindor>=hufflepuff and gryffindor>=slytherin:
   print("You belong to Gryffindor!")
elif ravenclaw>=gryffindor and ravenclaw>=hufflepuff and ravenclaw>=slytherin:
   print("You belong to Ravenclaw!")
elif hufflepuff>=ravenclaw and hufflepuff>=gryffindor and hufflepuff>=slytherin:
   print("You belong to Hufflepuff!")
elif slytherin>=ravenclaw and slytherin>=hufflepuff and slytherin>=gryffindor:
   print("You belong to Slytherin!")

Extension Task

Can you think of any additional questions you could add to your program to take more accurate decisions?

unlock-access

Solution...

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

Structure Diagram for an online-shop

An online-shop or e-commerce website is a complex web-based system that includes many functionalities. In order to design such a complex system. it is essential to think think abstractly to simplify the system we want to create and to break down the system into smaller modules.

Abstraction

An online shop is an abstraction, in other words a simplified model of a real life supermarket.

To define an abstraction, you need to consider which details your system will include and which details will be removed from your system to simplify it.

Online Shop Abstraction
Details to keep Details to remove
The ability to browse through different categories
The ability to pick an item and view its full description and price
The ability to add an item to your shopping basket
The ability to proceed to checkout
The ability to enter your card details and proceed to payment
The physical layout of the supermarket
The building aspect, colour of the walls, width of the aisles, type of floor, etc.
The physical dimensions of your trolley or shopping basket
The ability to pick up an item and manipulate it.
The ability to pay in cash
The need for the cashier to scan every item of your shopping trolley
The presence of other customers in the shop

There are many reasons why we would want to simplify our model:

  • A simplified model will be easier to code
  • You will be able to complete the project in a shorter timeframe
  • The system will not require too much processing power to run smoothly
  • The system will be adapted to the input and output devices available
  • The system will be easier to use

Once you have defined the scope of your abstraction (the details that your system will include) the next step is to break down this system into many sub-modules that can be tackled one at a time. This is what we call decomposition.

Decomposition

Decomposition consists of breaking down a complex system into smaller sub-systems / modules.

The benefits of decomposition is to:

  • Break down a complex system into smaller, more achievable sub-tasks
  • Organise your time and resources more effectively, especially when working as a team. Different team members can work on different sub-tasks.
  • Identify opportunities where you can re-use existing modules that you may already have implemented within other projects. For instance many system will require a login screen, many games will require a leaderboard. You might already have the code for these sub-modules.

Structure Diagrams

Structure diagrams are often use in computer science to help with the decomposition stage of the project. They help you break down your project into smaller sub-systems. And then for each sub-system you can break these down further into smaller modules or sub-tasks.

For instance, use the drag and drop activity below to complete the structure diagram for an online shop such as Amazon:
Structure Diagram – Online ShopOpen in New Window

Abstraction, Decomposition and Structure Diagrams

Any software developer, working on a new project will need to take time to step back and think before going straight into programming mode and writing their first line of code!

Their first step will be to consider their new system as an abstraction of reality: in other words a computer system is a simplified model of a real life situation.

Let’s consider a game of Pong for instance. A game of Pong is an abstraction of a tennis game at Wimbledon or Rolland Garros.

Abstraction

To define an abstraction, you need to consider which details your system will include and which details will be removed from your system to simplify it.

Pong Game Abstraction
Details to keep Details to remove
A bouncing ball
Two rackets/paddles that can move up and down
The net (a line across the screen)
A basic scoring system
The spectators / the stands
The referee
Light and shadow effects
Player and ball movement in 3D
Impact of gravity on the ball
Spin effects applied to the ball
The concept of games and sets
The Texture (grass/clay) and line marking of the court
Sound effects when the player runs or hits the ball
Weather conditions (incl. wind, rain, etc.)

There are many reasons why we would want to simplify our model:

  • A simplified model will be easier to code
  • You will be able to complete the project in a shorter timeframe
  • The system will not require too much processing power to run smoothly
  • The system will be adapted to the input and output devices available
  • The system will be easier to use

Once you have defined the scope of your abstraction (the details that your system will include) the next step is to break down this system into many sub-modules that can be tackled one at a time. This is what we call decomposition.

Decomposition

Decomposition consists of breaking down a complex system into smaller sub-systems / modules.

The benefits of decomposition is to:

  • Break down a complex system into smaller, more achievable sub-tasks
  • Organise your time and resources more effectively, especially when working as a team. Different team members can work on different sub-tasks.
  • Identify opportunities where you can re-use existing modules that you may already have implemented within other projects. For instance many system will require a login screen, many games will require a leaderboard. You might already have the code for these sub-modules.

Structure Diagrams

Structure diagrams are often use in computer science to help with the decomposition stage of the project. They help you break down your project into smaller sub-systems. And then for each sub-system you can break these down further into smaller modules or sub-tasks.

For instance, use the drag and drop activity below to complete the structure diagram of the game of Pong:
Structure Diagram – Pong GameOpen in New Window

OCR – H446 – Computer Science A-Level

H446 Course Overview
The OCR Computer Science A Level (H446 Specification) consists of 3 units of work as follows:
H446/01 - Computer Systems
1.1 – The characteristics of contemporary processors, input, output and storage devices
1.2 – Software and software development
1.3 – Exchanging data
1.4 – Data types, data structures and algorithms
1.5 – Legal, moral, cultural and ethical issues
H446/02 - Algorithms and programming
2.1 – Elements of computational thinking
2.2 – Problem solving and programming
2.3 – Algorithms to solve problems and standard algorithms
H446/03 - Programming Project
3.1 – Analysis of the problem
3.2 – Design of the solution
3.3 – Developing the solution
3.4 – Evaluation

Extra Revision Resources…

OCR – J277 – Computer Science GCSE

J277 Course Overview
The OCR Computer Science GCSE (J277 Specification) consists of 2 units of work as follows:
J277/01 - Computer Systems
1.1 – Systems architecture
1.2 – Memory and storage
1.3 – Computer networks, connections and protocols
1.4 – Network security
1.5 – Systems software
1.6 – Ethical, legal, cultural and environmental impacts of digital technology
J277/02 - Computational thinking, algorithms and programming
2.1 – Algorithms
2.2 – Programming fundamentals
2.3 – Producing robust programs
2.4 – Boolean logic
2.5 – Programming languages and Integrated Development Environments

Extra Revision Resources…

OCR H446/02 – 2.3 Algorithms

2.3 Algorithms - Overview / Checklist
2.3.1 Algorithms
(a) Analysis and design of algorithms for a given situation.
(b) The suitability of different algorithms for a given task and data set, in terms of execution time and space.
(c) Measures and methods to determine the efficiency of different algorithms, Big O notation (constant, linear, polynomial, exponential and logarithmic complexity).
(d) Comparison of the complexity of algorithms.
(e) Algorithms for the main data structures, (stacks, queues, trees, linked lists, depth-first (post-order) and breadth-first traversal of trees).
(f) Standard algorithms (bubble sort, insertion sort, merge sort, quick sort, Dijkstra’s shortest path algorithm, A* algorithm, binary search and linear search).

Recommended Resources

2.3.1 Algorithms
Searching & Sorting Algorithms
Bubble Sort Algorithm – Visualisation Merge Sort Algorithm – Visualisation Quick Sort Algorithm Sorting Algorithms – Visualisation Searching & Sorting Algorithms – Practice Linear Search Functions Binary Search: Guess The Number Linear vs Binary Search: Domain Name Server Challenge Bubble Sort Algorithm – Visualisation Insertion Sort Algorithm – Visualisation Sorting Algorithms – Python Code Shuffling Algorithm (Python Challenge)

Algorithms & Data Structures
– Binary Trees
Breadth-First Traversal of a Binary Tree Binary Search Tree Implementation Prime Factor Tree Algorithm Morse Code using a Binary Tree Huffman Coding Algorithm – Graphs
Air-Flight Route Planner The Social Network Food Chain and Food Web London Underground Journey Planner

– Hash Tables
Airport Lookup Check Chemical Elements Quiz

– 2D and 3D Arrays
Cinema Booking Challenge Laser Maze Game My Weekly Timetable Four in a row Challenge Noughts & Crosses Challenge Battleship Challenge Drone Display Space Invaders 2D/3D Pixel Art

– Stack & Queues
Stacks and Queues using Python The Ice Cream Stack Bracket Validator (using a Stack) Reverse Polish Notation (using a Stack)


Big O Notation

Big O Notation

The question we will try to answer in this blog post is as follows: How can we measure the effectiveness/performance of an algorithm? First let’s consider this quote from Bill Gates (Founder of Microsoft): “Measuring programming progress by lines of … Continue reading


Big O Notation – Quiz

Before completing this quiz, we invite you to revisit the main Big O Notations used to describe the time complexity and space complexity of an algorithm.. The main Big O Notations this quiz will focus on are: Take the Quiz! … Continue reading


Short Path Algorithms

Dijkstra’s Shortest Path Algorithm

Dijkstra’s Shortest Path Algorithm is an algorithm used to find the shortest path between two nodes of a weighted graph. Before investigating this algorithm make sure you are familiar with the terminology used when describing Graphs in Computer Science. Let’s … Continue reading


A* Search Algorithm

The A* Search algorithm (pronounced “A star”) is an alternative to the Dijkstra’s Shortest Path algorithm. It is used to find the shortest path between two nodes of a weighted graph. The A* Search algorithm performs better than the Dijkstra’s … Continue reading


Short Path Algorithm Practice

Before completing this task, you will need to familiarise yourself with the following 2 algorithms used to find the shortest path between two nodes of a weighted graph: Dijkstra’s Short Path Algorithm A* Algorithm Dijkstra’s Short Path Algorithm For each … Continue reading


Air Flight Route Planner London Underground Journey Planner The Social Network

OCR H446/01 – 2.2 Problem solving and programming

2.2 Problem solving and programming - Overview / Checklist
2.2.1 Programming techniques
(a) Programming constructs: sequence, iteration, branching.
(b) Recursion, how it can be used and compares to an iterative approach.
(c) Global and local variables.
(d) Modularity, functions and procedures, parameter passing by value and by reference.
(e) Use of an IDE to develop/debug a program.
(f) Use of object oriented techniques.
2.2.2 Computational methods
(a) Features that make a problem solvable by computational methods.
(b) Problem recognition.
(c) Problem decomposition.
(d) Use of divide and conquer.
(e) Use of abstraction.
(f) Learners should apply their knowledge of:

    backtracking
    data mining
    heuristics
    performance modelling
    pipelining
    visualisation to solve problems.

Recommended Resources

OCR H446/02 – 2.1 Elements of computational thinking

2.1 Elements of computational thinking - Overview / Checklist
2.1.1 Thinking abstractly
(a) The nature of abstraction.
(b) The need for abstraction.
(c) The differences between an abstraction and reality.
(d) Devise an abstract model for a variety of situations.
2.1.2 Thinking ahead
(a) Identify the inputs and outputs for a given situation.
(b) Determine the preconditions for devising a solution to a problem.
(c) The nature, benefits and drawbacks of caching.
(d) The need for reusable program components.
2.1.3 Thinking procedurally
(a) Identify the components of a problem.
(b) Identify the components of a solution to a problem.
(c) Determine the order of the steps needed to solve a problem.
(d) Identify sub-procedures necessary to solve a problem.
2.1.4 Thinking logically
(a) Identify the points in a solution where a decision has to be taken.
(b) Determine the logical conditions that affect the outcome of a decision.
(c) Determine how decisions affect flow through a program.
2.1.5 Thinking concurrently
(a) Determine the parts of a problem that can be tackled at the same time.
(b) Outline the benefits and trade offs that might result from concurrent processing in a particular situation.

Recommended Resources

OCR H446/01 – 1.5 Legal, moral, cultural and ethical issues

1.5 Legal, moral, cultural and ethical issues - Overview / Checklist
1.5.1 Computing related legislation
(a) The Data Protection Act 1998.
(b) The Computer Misuse Act 1990.
(c) The Copyright Design and Patents Act 1988.
(d) The Regulation of Investigatory Powers Act 2000.
1.5.2 Moral and ethical Issues
The individual moral, social, ethical and cultural
opportunities and risks of digital technology:

    Computers in the workforce.
    Automated decision making.
    Artificial intelligence.
    Environmental effects.
    Censorship and the Internet.
    Monitor behaviour.
    Analyse personal information.
    Piracy and offensive communications.
    Layout, colour paradigms and character sets.

Recommended Resources

1.5.1 Computing related legislation

UK Legislation relevant to Computer Science

As a computer scientist, you need to be aware of the legislation that is relevant to the use of Computer Science related technologies. Whether you are designing a new website, creating a computer program or system or just using a … Continue reading


The Apple–FBI Encryption Dispute

This post is part of series of blog posts investigating different impacts of UK legislation relevant to Computer Science with a particular focus on: Data Protection Legislation Intellectual Property Protection (incl. Copyright and Trade Marks legislation) Computer Misuse Act (1990)


Unveiling the World of Ethical Hacking

This post is part of series of blog posts investigating different impacts of UK legislation relevant to Computer Science with a particular focus on: Data Protection Legislation Intellectual Property Protection (incl. Copyright and Trade Marks legislation) Computer Misuse Act (1990)


The MafiaBoy dDoS attack

This post is part of series of blog posts investigating different impacts of UK legislation relevant to Computer Science with a particular focus on: Data Protection Legislation Intellectual Property Protection (incl. Copyright and Trade Marks legislation) Computer Misuse Act (1990)


The Hyperlink Patent Case and the Copyright, Designs and Patents Act

This post is part of series of blog posts investigating different impacts of UK legislation relevant to Computer Science with a particular focus on: Data Protection Legislation Intellectual Property Protection (incl. Copyright and Trade Marks legislation) Computer Misuse Act (1990)


Mickey Mouse Enters the Public Domain

This post is part of series of blog posts investigating different impacts of UK legislation relevant to Computer Science with a particular focus on: Data Protection Legislation Intellectual Property Protection (incl. Copyright and Trade Marks legislation) Computer Misuse Act (1990)


The Cadbury Ruling: Can Colours be Trademarks in the UK?

This post is part of series of blog posts investigating different impacts of UK legislation relevant to Computer Science with a particular focus on: Data Protection Legislation Intellectual Property Protection (incl. Copyright and Trade Marks legislation) Computer Misuse Act (1990)


The Salami Hack & the Computer Misuse Act Legislation

This post is part of series of blog posts investigating different impacts of UK legislation relevant to Computer Science with a particular focus on: Data Protection Legislation Intellectual Property Protection (incl. Copyright and Trade Marks legislation) Computer Misuse Act (1990)


OCR H446/01 – 1.4 Data types, data structures and algorithms

1.4 Data types, data structures and algorithms - Overview / Checklist
1.4.1 Data Types
(a) Primitive data types, integer, real/floating point, character, string and Boolean.
(b) Represent positive integers in binary.
(c) Use of sign and magnitude and two’s complement to represent negative numbers in binary.
(d) Addition and subtraction of binary integers.
(e) Represent positive integers in hexadecimal.
(f) Convert positive integers between binary hexadecimal and denary.
(g) Representation and normalisation of floating point numbers in binary.
(h) Floating point arithmetic, positive and negative numbers, addition and subtraction.
(i) Bitwise manipulation and masks: shifts, combining with AND, OR, and XOR.
(j) How character sets (ASCII and UNICODE) are used to represent text
1.4.2 Data Structures
(a) Arrays (of up to 3 dimensions), records, lists, tuples.
(b) The following structures to store data: linked-list, graph (directed and undirected), stack, queue, tree, binary search tree, hash table.
(c) How to create, traverse, add data to and remove data from the data structures mentioned above. (NB this can be either using arrays and procedural programming or an object-oriented approach).
1.4.3 Boolean Algebra
(a) Define problems using Boolean logic.
(b) Manipulate Boolean expressions, including the use of Karnaugh maps to simplify Boolean expressions.
(c) Use the following rules to derive or simplify statements in Boolean algebra: De Morgan’s Laws, distribution, association, commutation, double negation.
(d) Using logic gate diagrams and truth tables.
(e) The logic associated with D type flip flops, half and full adders.

Recommended Resources

Further Reading…