More results...

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

Murder Mystery

Murder-MysteryDoctor Black has just been found dead in his bedroom. He has been knocked down by a heavy metallic object, most likely the candlestick that was found on the floor next to Doctor Black. When falling down, Doctor Black broke his watch which stopped at 8:14 PM. We can assume that this is the time of death.

Doctor Black’s bedroom is the master bedroom and is located on the first floor.

Our crime scene investigator took some notes to recap the key facts:

cluedo-clipboard

At this time of the day there were only four guests in Doctor Black’s mansion. They are the prime suspects:

  • Miss Scarlett
  • Reverend Green
  • Colonel Mustard
  • Professor Plum

do-not-cross

Our crime scene investigator interviewed all four suspects and gathered some facts about their whereabouts around the time of death.

He has decided to create an algorithm based on these facts to help him solve this murder mystery. To do so he has translated each fact into pseudo code as follows:

Fact:

Miss Scarlett and Professor Plum were playing tennis between 6 and 8PM, so if the murder took place between 6 and 8PM they would both be innocent.

Pseudocode:

IF TimeOfMurder >= 6:00PM AND TimeOfMurder <= 8:00PM THEN
    MissScarlett = "Innocent"
    ProfessorPlum = "Innocent"
END IF

do-not-cross

Below is our crime scene investigator’s full algorithm:

Will it help you solve this crime?

IF TimeOfMurder >= 6:00PM AND TimeOfMurder <= 8:00PM THEN
    MissScarlett = "Innocent"
    ProfessorPlum = "Innocent"
END IF

SELECT CASE LocationOfMurder:
    CASE "1st Floor":
        ReverendGreen = "Innocent"
    CASE "Ground Level":
        MissScarlett = "Innocent"
        ColonelMustard = "Innocent"
    CASE "Garden"
        ProfessorPlum = "Innocent"

IF (MurderRoom == "Kitchen" OR MuderRoom == "Master Bedroom")  AND timeOfMurder >= 8:00PM THEN
    ProfessorPlum = "Innocent"
ELIF MurderRoom == "Bathroom" AND (timeOfMurder >= 8:00PM AND timeOfMurder <= 8:30PM) THEN
    MissScarlett = "Guilty"
END IF

IF MurderWeapon == "Candlestick" OR MurderWeapon == "Rope" THEN
    MurdererGender = "Male"
END IF

And the murderer is …

do-not-cross

Tagged with: ,

Creating Sprites using Pygame

This tutorial is the second tutorial in a series of five Pygame tutorials:

Learning Objectives


In this second tutorial on how to create a retro arcade game using PyGame we are looking at creating our first sprite.
definition-sprite

Consider a sprite as an object. An object can have different properties (e.g. width, height, colour, etc.) and methods (e.g. jump(), hide(), moveForward(), etc.). Like in the industry an object is built from a mould. In computing the mould is called a Class.

So by creating our first sprite we will implement OOP (Object Orientated Programming). We will create our first Class and derive our first object from this class.

Context: Car Racing Game


For this tutorial we are looking at creating a car racing game. The user will be able to control the car and move on the road between lanes by using the left and right arrow keys, accelerate or slow down using the up and down arrow keys.

The main car will be an object called playerCar. It will derive from a Class called Car.

Our first Class


So let’s look at the code for our Car Class:
To start with the first method we will need in our class is the __init__() method. It’s called a constructor. It is used when the object is first created to initalise the main properties of the object (e.g. its x and y position, dimensions, colour, etc.)

import pygame
WHITE = (255, 255, 255)

class Car(pygame.sprite.Sprite):
    #This class represents a car. It derives from the "Sprite" class in Pygame.
    
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()
        
        # Pass in the color of the car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
 
        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])
        
        # Instead we could load a proper pciture of a car...
        # self.image = pygame.image.load("car.png").convert_alpha()
 
        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()

Later on we will add more properties and methods to this class. But before doing so we will look at how we can use it to create our first object: the car of the player (playerCar)

So let’s save our class as a python file called car.py.

Our first Object


Now that we have a Class we can create objects from this Class. (Remember a Class is like a mould. It enables you to create as many objects as you need using the same mould.)

Let’s go back to our main.py file (from previous tutorial) to edit its content.

First let’s add at the top of the code an import statement to import our Car class.

#Let's import the Car Class
from car import Car

Then we need to create our sprite in our main program using the following line of code:

playerCar = Car(RED, 20, 30)

Per dafult your car will be on position (0,0) (top left og the screen). You can change the x and y properties of your car as follows:

playerCar.rect.x = 200
playerCar.rect.y = 300

You can see how easy it would be to create another car:

player1Car = Car(RED, 20, 30)
player1Car.rect.x = 200
player1Car.rect.y = 300
player2Car = Car(PURPLE, 20, 30)
player2Car.rect.x = 400
player2Car.rect.y = 400

However, fir now we do not need to add these two extra cars.

Let’s reuse the code from the first tutorial. We have made a few amendments since to draw the backdrop of our game: A green screen with a grey straight road!

On line 3 notice how we are using the import command to link to our Car Class python file (car.py).

On line 20 we are declaring a list called all_sprites_list that will store all the sprites we will create in our game. (For now just one sprite, the player car.)

On line 22 we are creating our first sprite/object using the Car Class. Notice how when declaring our first object we use the parameters from its constructor (__init__()), in this case, the colour, x, y, width and height of the car we want to create.

Now that we have created our first sprite we need to add it to our list of spites: all_sprites_list. This is what happens on line 27.

Finally, within the main program loop, on line 49 we are refreshing the screen and drawing all the sprites from our list: all_sprites_list.

Here is the full code:

import pygame, random
#Let's import the Car Class
from car import Car
pygame.init()

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
        
SCREENWIDTH=400
SCREENHEIGHT=500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

playerCar = Car(RED, 20, 30)
playerCar.rect.x = 200
playerCar.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(playerCar)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            carryOn=False
                
    #Game Logic
    all_sprites_list.update()

    #Drawing on Screen
    screen.fill(GREEN)
    #Draw The Road
    pygame.draw.rect(screen, GREY, [40,0, 200,300])
    #Draw Line painting on the road
    pygame.draw.line(screen, WHITE, [140,0],[140,300],5)
        
    #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
    all_sprites_list.draw(screen)

    #Refresh Screen
    pygame.display.flip()

    #Number of frames per secong e.g. 60
    clock.tick(60)

pygame.quit()

That’s it… You are now ready to move to our third tutorial to learn how to control your sprites using the arrow keys.
PyGame Tutorial 3/5Control your sprite using the arrow keys

Tagged with: , ,

Minecraft + Python Challenges

Learning Objectives


Another approach to boost your pogramming skills is to learn how to code for Minecraft. Using Python code you can interact with the Minecraft world to for instance move the player or add blocks to build structures.

For this challenge we are using a Raspberry Pi with Minecraft and Python 2 pre-installed.

Let’s see how this works…

Hello Minecraft World


Let’s start by writting a “Hello World” program that will write a welcome message on the Minecraft chat. This is the simplest program and will be useful to make sure we have the required library and can connect to Minecraft.

Here is the Python code:

from mcpi import minecraft, block

mc = minecraft.Minecraft.create()
msg = "Hello Minecraft World from 101 Computing"
mc.postToChat(msg)

So to test this program on your Raspberry Pi you will need to:

  • Type this program in your Python IDE (e.g. IDLE) for Python 2,
  • Launch Minecraft
  • In your IDE run the program
  • Check the Minecraft screen. If everything goes right, a message will appear on screen.

Teleporting your player


minecraft-xyz-coordinatesFor this Python script we are going to write a function to teleport the player up in the sky. We will call this function “jump”. It will take one parameter: the distance (number of blocks) we want the player to jump (up in the sky).

To understand the code below we need to understand how (X,Y,Z) are used in minecraft to retrieve or change the position of a player (and later on the position of blocks).

from mcpi import minecraft, block
import time

def jump(distance):
    #Let's wait 1 second
    time.sleep(1)
    
    #Retrieve the X,Y,Z coordinates of the player
    pos=mc.player.getPos()
    #Change the Y coordinate of the player to position it up in the sky    
    mc.player.setPos(pos.x, pos.y + distance, pos.z)

#Main Program Starts Here:
jump(100)

Building a Tower


minecraft-postThe purpose of this script is to build a ten-block high tower in front of the player. We will be using 3 different methods for you to compare:
  • Method 1: Building the tower one block at a time using sequencing,

  • Method 2: Building the tower one block at a time using iteration (for loop),

  • Method 3: Building the tower in one go using the setBlocks(), method.

Method 1Method 2Method 3
from mcpi import minecraft, block
import time

def createTower():
    #Let's wait 1 second
    time.sleep(1)
    
    #Retrieve the X,Y,Z coordinates of the player
    pos=mc.player.getPos()

    #Create a 10-block high tower, 5 blocks away from the player
    mc.setBlock(pos.x + 5, pos.y, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+1, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+2, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+3, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+4, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+5, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+6, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+7, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+8, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+9, pos.z, block.STONE)
    mc.setBlock(pos.x + 5, pos.y+10, pos.z, block.STONE)

#Main Program Starts Here:
createTower()
from mcpi import minecraft, block
import time

def createTower(numberOfBlocks):
    #Let's wait 1 second
    time.sleep(1)
    
    #Retrieve the X,Y,Z coordinates of the player
    pos=mc.player.getPos()

    #Create a tower 5 blocks away from the player
    for i in range (0, numberOfBlocks):
        mc.setBlock(pos.x + 5, pos.y + i, pos.z, block.STONE)

#Main Program Starts Here:
createTower(10)
from mcpi import minecraft, block
import time

def createTower(numberOfBlocks):
    #Let's wait 1 second
    time.sleep(1)
    
    #Retrieve the X,Y,Z coordinates of the player
    pos=mc.player.getPos()

    #Create a tower 5 blocks away from the player
    mc.setBlocks(pos.x + 5, pos.y, pos.z, pos.x + 5, pos.y + numberOfBlocks, pos.z, block.STONE)

#Main Program Starts Here:
createTower(10)

Challenge #1: Rugby Post


minecraft-rugby-postUse any of the three methods mentioned above and complete the code to create a full rugby post using Python.

Challenge #2: A complex Structure


Build a complex structure using a Python script. Try to identify patterns in your structure to use for loops and hence reduce the number of instructions in your program.

Try to build a Pyramid first starting from a 10 by 10 square base.

Or why not challenge yourself to build a castle like this one:
minecraft-castle

Tagged with: , , ,

Getting Started with Pygame

This tutorial is the first tutorial in a series of five Pygame tutorials:

Learning Objectives


These instructions will guide you through the first few steps required to set up the foundation for a Pygame project.

Now that you have learned the basics of Python you are most likely willing to start creating your own games. Pygame is one of the best libraries to create mainly 2D retro arcade games such as Tetris, PacMan or Space Invaders.

Let’s see what are the first few steps needed to create your first game in Python.

Installing Pygame


Make sure you have access to the Pygame library. If not you will need to download and install it following the instructions provided on the Pygame website: http://www.pygame.org/.

Step 1: Importing and initialising the Pygame library


Your Python code will need to start with the following two lines of code:

# Import the pygame library and initialise the game engine
import pygame
pygame.init()

Note that you will first need to install the Pygame library on your computer. Alternatively you can complete this challenge online using the following Trinket/Pygame IDE

Step 2: Define the colours you will use in your game


You will have to declare a constant for each of the main colours used within your game. To help you identify colour codes you may use a colour picker.

# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)

Step 3: Open a new window


Your game will run in its own window, for which you can decide of a title, a width and a height.

# Open a new window
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My First Game")

Step 4: The main program loop


The main program loop is the key wrapper for your game.

The main program loop will contain 3 main sections:

  • Capturing Events: Used to constantly “listen” to user inputs and react to these. It could be when the user uses the keyboard or the mouse.
  • Implementing the Game Logic. What happens when the game is running? Are cars moving forward, aliens falling from the sky, ghosts chasing you, etc.
  • Refreshing the screen by redrawing the stage and the sprites.

The main program loop will also use a frame rate to decide how often should the program complete the loop (& refresh the screen) per second. To implement this we will use the clock object from the pygame library.

The main program loop will use a timer to decide how many times it will be executed per second.

# The loop will carry on until the user exits the game (e.g. clicks the close button).
carryOn = True

# The clock will be used to control how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while carryOn:
    # --- Main event loop
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
           carryOn = False # Flag that we are done so we can exit the while loop

    # --- Game logic should go here

    # --- Drawing code should go here
    # First, clear the screen to white. 
    screen.fill(WHITE)
    #The you can draw different shapes and lines or add text to your background stage.
    pygame.draw.rect(screen, RED, [55, 200, 100, 70],0)
    pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)
    pygame.draw.ellipse(screen, BLACK, [20,20,250,100], 2)


    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
     
    # --- Limit to 60 frames per second
    clock.tick(60)

#Once we have exited the main program loop we can stop the game engine:
pygame.quit()

Your Challenge


Use the code above to create your first Pygame project.

Complete the code to draw the following background:
pygame-road-layout

Next Step?


Your background is ready? Let’s add the first sprite to your project by completing the next tutorial:
Adding a Sprite using PyGame(Tutorial 2/5)
Tagged with: , ,

Using text files in Python

file-handling

Learning Objectives


In this post you will learn how to code the main file handling operations to manipulate text files as follows:

  • Opening a file
  • Reading from a text file
  • Reading writing to a text file
  • Appending to a text file
  • Closing a file
Open a fileClose a fileReadWriteAppend to
To open a file use the following code:

file = open("myTextFile.txt","r")

Folder name/File name


When opening a text file you need to specify the filename you want to open. If the file is not stored in the same folder as your Python file, you will also need to specify the location (e.g. subfolder) where the text file is saved. E.g.

file = open("myFolder/myTextFile.txt","r")

Access Mode


When opening the file you have to specify the access mode using one of the following codes:

Mode Description
r Opens a file in read only mode. This is the default mode.
r+ Opens a file for both reading and writing.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
w+ Opens a file for both writing and reading. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
a Opens a file for appending. The file pointer is at the end of the file. So new data will be added at the end of the file. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
Once you have finished using your file, make sure that you close this file! It will free up resources and allow other users/processes to access this file if they need to.
Closing a file is extremely easy using the close method.

file.close()
To read a text file, line by line, you will need to:

  1. Open the text file in read mode (either “r” or “r+”),
  2. Loop through the text file, line by line, using a for loop,
  3. Close the text file.

Reading line by line

file = open("myTextFile.txt","r")

for line in file:
  print(line)
  
file.close()

What’s About CSV files?


CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a comma “,”. Sometimes we use other symbols instead of the comma such as a semi-colon “;” or a pipe “|”.
In this case when reading a line of the text file you can use the split() method to then access each field one by one.

file = open("myTextFile.txt","r")

for line in file:
  data = line.split(";")
  print(data[0] + " - " + data[1] + " - " + data[2])
  
file.close()
To write to a text file you will need to:

  1. Open the text file in read mode: “w”,
  2. Write to the file using the write() method,
  3. Close the text file.

Be careful, when using the write command, you are overwriting the content of your file. If instead of overwriting the content of your file you want to append (write at the end of the file) check the next tab: “Append to a text file”.

Note that when opening the text file, if the file specified does not exist, Python will create a new file automatically.

Writing to a text file

file = open("myTextFile.txt","w")

file.write("Hello World\n");
  
file.close()

The “\n” at the end of the text means “new line”. Only use it if you want the next call to the write() method to start on a new line.

The write method will overwrite the content of your file. If instead you want to write at the end of a text file you can use the “Append access mode”:

To append to a text file you will need to:

  1. Open the text file in append mode: “a”,
  2. Write to the file using the write() method,
  3. Close the text file.

Appending to a text file

file = open("myTextFile.txt","a")

file.write("Hello World\n");
  
file.close()

The “\n” at the end of the text means “new line”. Only use it if you want the next call to the write() method to start on a new line.

Practice makes perfect


Try one of these challenges to put into practice what you have learnt about file handling operations.
Class Register(Handling Text Files) My Mp3 Playlist(Handling Text Files)

London 2012

london-2012

Learning Objectives


In this challenge we are going to investigate methods that can be used to:

  • Read and extract data from a text file,
  • Sort this data in ascending or descending order,
  • Display this sorted data on screen.

Context


We have a text file with the list of the 10 top countries at the London 2012 Olympic Games. (Countries which won the most gold medals). This data is not sorted and is organised as follows:

Name of Country;Number of Gold Medals;Number of Silver Medals;Number of Bronze Medals

You can download this text file:

TextFilecountries.txt

Step by Step


To achieve our goal of reading the text file, sorting its data and displaying it on the screen we will proceed in 5 steps:
5steps

Python Code


Your Challenge


Tweak this code to:

  • Sort this list in ascending order of gold medals
  • Sort this list in alphabetical (ascending) order of name of country
  • Sort this list in descending order of silver medals
  • Sort this list in descending order of bronze medals
  • Sort this list in descending order of total number of medals (Bronze + Silver + Gold medals)

unlock-access

Solution...

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

Batman vs. Python Turtle

For this challenge we are focusing on a set of equations used to draw different sections of the Batman logo:

  • f(x) = 1.5*sqrt((‑abs(abs(x) – 1)) * abs(3 – abs(x))/((abs(x) – 1)*(3 – abs(x)))) * (1+abs(abs(x) – 3)/(abs(x)- 3)) * sqrt(1 – (x/7)^2)+(4.5+0.75 * (abs(x – 0.5)+abs(x+0.5)) – 2.75 * (abs(x-0.75)+abs(x+0.75))) * (1+abs(1 – abs(x))/(1 – abs(x)))
  • g(x) = (‑3)*sqrt(1 -(x/7)^2) * sqrt(abs(abs(x) – 4)/(abs(x)-4))
  • h(x) = abs(x/2) – 0.0913722 * x^2-3+sqrt(1 – (abs(abs(x) – 2) – 1)^2)
  • i(x) = (2.71052+1.5 – 0.5 * abs(x) – 1.35526 * sqrt(4 – (abs(x) – 1)^2)) * sqrt(abs(abs(x) – 1)/(abs(x) – 1))

We will import two Python libraries:

  • math library to use functions such as sqrt() and fabs(),
  • turtle library to draw/plot on the screen using x and y coordinates.

Batman Logo:


Your Challenge


Check the following page for additional maths equations to draw heart shapes. See how you could tweak the code given above to reuse these equations and draw a heart shape on screen.

Tagged with: ,

HTML Code Builder (in Python)

html-tag

Learning Objectives


By completing this challenge you will learn how to use count-controlled loops (for loops). You will include a loop within a loop: This is called nesting.

In this challenge you will also use string concatenation techniques.

Finally you will also learn about the following tags in HTML:

  • <UL>, <LI> tags used to create bullet point lists in HTML,
  • <TABLE>, <TR> and <TD> tags used to create tables in HTML.

Bullet Point Lists in HTML


In HTML you can create bullet point lists to display information on the page as follows:
  • First bullet point,
  • Second bullet point,
  • and so on…

To do so you need to use both a <UL> tag to open and close the list and a <LI> tag for each bullet point within the list.
Here is HTML the code:

<UL>
	<LI>First bullet point,</LI>
	<LI>Second bullet point,</LI>
	<LI>and so on...</LI>
</UL>

Using Python we have written a script that prompts the user to enter the number of bullet points they need. In return the script produces the HTML code for the user to copy and paste to their webpage.

HTML Tables


From time to time, when building a webpage in HTML you need to present your data using a table.

A table (<TABLE>) is made of rows (<TR>). Each row is made of data cells (<TD>).

So for instance a 3×2 table contains 3 rows and each row contains 2 data cells. The HTML code of such a table is as follows:

HTML-Table

This is the full code in HTML:

<TABLE>
	<TR>
		<TD> ... </TD>
		<TD> ... </TD>
	</TR>
	<TR>
		<TD> ... </TD>
		<TD> ... </TD>
	</TR>
	<TR>
		<TD> ... </TD>
		<TD> ... </TD>
	</TR>
</TABLE>

Check this other example of table from w3schools.

Your Challenge


Write a python script (or reuse the script above) to prompt the user to enter the number of rows and the number of columns they need for their table. The program should then generate the HTML code for the required table.

Extension Task:


Check how this online HTML Table Code Generator works.

Update your code to ask for additional settings such as:

  • Table width,
  • Table alignment,
  • Cell padding,
  • Background Colour,
  • Border thickness and colour,
  • etc…

Your program should then generate the HTML code for the table, including the given parameters using HTML or CSS attributes.

unlock-access

Solution...

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

Calculating Pi using a Python script

Did you know?


Pi (π) is one of the most important and fascinating numbers in mathematics. Roughly 3.14, it is a constant that is used to calculate the circumference of a circle from that circle’s radius or diameter. Pi is also an irrational number, which means that it can be calculated to an infinite number of decimal places without ever slipping into a repeating pattern. This makes it difficult, but not impossible, to calculate precisely.

How to calculate Pi?


Method #1


All we need to calculate Pi is a round object such as a golf ball and a tape measurer.
We will need to take two measurements as follows:

  • Diameter,
  • Circumference

Knowing that Circumference = π x Diameter we can calculate π as follows: π = Circumference / Diameter.
pi-calculation-method-1
As you may have noticed, this method does not give you the exact value of Pi. This due to the fact that the measurements of the diameter and of the circumference of an object are never 100% accurate.

Challenge #1


Your challenge consists of writing a Python script that prompts the end-user to enter both the diameter and the circumference of a round object. Your program should return the corresponding estimation of π by using the formula from method #1: π = Circumference / Diameter.

You can try your algorithm with the following measurements:
pi-calculation-method-1-earth

Method #2: Calculating Pi Using an Infinite Series (Gregory-Leibniz series)


Mathematicians have found several different mathematical series that, if carried out infinitely, will accurately calculate Pi to a great number of decimal places. Some of these are so complex they require supercomputers to process them. One of the simplest, however, is the Gregory-Leibniz series. Though not very efficient, it will get closer and closer to Pi with every iteration, accurately producing Pi to five decimal places with 500,000 iterations. Here is the formula to apply:
pi-calculation-method-2

Challenge #2


Write a Python script that will calculate Pi with at least three accurate decimal places using the Gregory-Leibniz series.
Tip: You will need to use a for loop and decide of a number of iteration for your algorithm.

Method #3: Calculating Pi Using an Infinite Series (Nilakantha series)


The Nilakantha series is another infinite series to calculate Pi that is fairly easy to understand. While somewhat more complicated, it converges on Pi much quicker than the Gregory-Leibniz formula. Here is the formula to apply:
pi-calculation-method-3

Challenge #3


Write a Python script that will calculate Pi with at least three accurate decimal places using the Nilakantha series.

Help?


Our flowcharts can help you complete these three challenges.
unlock-access

Solution...

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

Word Score Challenge

word-score

Did you know?


The ASCII code (Pronounced ask-ee) is a code for representing English characters as numbers, with each character assigned a number from 0 to 127. For example, the ASCII code for uppercase M is 77. The extended ASCII contains 256 characters (using numbers from 0 to 255).

To see a list of the most useful ASCII codes you can download our simplified ASCII helpsheet.

Using Python you can easily access ASCII values of a character using the ord() function. For instance ord(“M”) returns 77 and chr(77) returns “M”

Your Challenge

Write a Pyhon script that prompts the end-user to enter a word, e.g. “Hello”
The script should calculate the score of this word using the letter values (A=1, B=2, C=3…)

So if the use inputs the word “Hello” the script should output: 8 + 5 + 12 + 12 + 15 = 52%.

Solution


Hide SolutionView SolutionExtended Solution
This solution uses a for loop to access each letter of the word one letter at a time.
Using the ord() function it returns the ASCII code for the letter.
The ASCII code for A is 65, for B is 66 and so on. So by taking away 64 to the ASCII code we then get A=1, B=2, C=3 etc.

word = input("Type a word").upper()
wordScore=0

for letter in word:
  letterValue=ord(letter) - 64
  wordScore += letterValue
  
print(str(wordScore) + "%")
This solution is exactly the same as the previous one but displays the full formula to calculate the score e.g. “8 + 5 + 12 + 12 + 15 = 52%”. This formula is stored as a string in a variable called addition.

word = input("Type a word").upper()
wordScore=0
addition=""

for letter in word:
  letterValue=ord(letter) - 64
  if (addition==""):
    addition = str(letterValue)
  else:
    addition = addition + " + " + str(letterValue)
  wordScore += letterValue
  
print(addition + " = " + str(wordScore) + "%")
unlock-access

Solution...

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