Category: Software Design & Devlopment

Higher – SDD – Reading a file into an array

The code below allows us to read a file into an array then process the data. In this case the processing is just to see how many of each of the numbers (1-6) there were in the file.

def getData(array):
    txtFile=open("diceRolls.txt","r")
    for x in range(len(array)):
        array[x]=int(txtFile.readline().strip())
    
    txtFile.close()
    return array

def countOcc(array,target):
    total=0
    for number in array:
        if number==target:
            total=total+1
            
    return total

def main():
    dice=[0 for x in range(1000)]
    dice=getData(dice)
    for x in range(1,7):
        print("Number of",x,"'s=",countOcc(dice,x))
        
main()

The text file is the result of 1000 D6 rolls.
Can you modify the program to work out which number has the largest number of occurrences?

National 5 – SDD Predefined Functions

So today we were looking over predefined function. For the N5 course we have to be aware of RANDOM, ROUND, & LENGTH.

The RANDOM function picks an integer between two values.

import random
number=random.randint(1,20) # random(StartValue,EndValue)
print(number)

The ROUND function rounds a real number (floating point) to a fixed number of decimal points.

a=1.2 # 1
b=2.6 # 3
c=2.5 # 2
d=3.5 # 4
e=3.453444354

print(round(e,2)) # round(valueToRound,NoOfDecimalDigits)

The LENGTH function displays the number of characters in a String or the length of an Array.

name="Stratton was here"
numbers=[1,2,3,4,2,3,4,6,4,3,2,43]
print(len(name))
print(len(numbers))
print(numbers)

for index in range(len(numbers)):
    print(numbers[index])

for index in range(len(name)):
    print(name[index])

 

Logical Operators

AND

Both expressions must be True for the result to be True

Expression 1 Expression 2 Result
False False False
False True False
True False False
True True True

 

OR

Either expression must be True for the result to be True

Expression 1 Expression 2 Result
False False False
False True True
True False True
True True True

 

NOT

The result is the opposite of the Expression

Expression Result
True False
False True

 

 

Problem Solving – Software Development

As you are solving each problem you should be doing the following in your jotter before hitting the computer

Heading – Name of program

Description of problem – pick out the key things the program must do and write it as a paragraph (rewrite the problem in your own words)

  • Analysis
    • Inputs – What the user must enter to the program
    • Processes – What the program does with the inputs to create the outputs
    • Outputs  – What the program display to the user
  • Design (one of the following)
    • Pseudocode – numbered steps that the program follows
    • Structure Diagram
    • Flow Chart

Pseudocode

Pseudocode is a design methodology that uses structured written language to show the design of the program.

Although there are no formal rules for Pseudocode, in Coltness we use the following rules.

  • Instructions should make sense
  • Instructions should use line numbers
  • Instructions can use mathematical symbols
  • Use indentation and white space where required
  • One line of Pseudocode = one line of Python code
  • Try to use only structures that exist in the language the program will be written in.

 

 

S3 – Python Turtle

This weeks task is to solve the maze. You are not allowed to touch the black lines.

You can use any Python Turtle commands you want including

  • goto(x,y)
  • right(deg)
  • left(deg)
  • forward(length)

Save the image as maze.png and use the boilerplate code below in Thonny to start the task.


# Solve the maze
# Mr Stratton
# 7/6/19

from turtle import *
# Help here https://docs.python.org/3/library/turtle.html
setup(1000,600) # set the window size to 480x360 pixels
bgcolor('yellow') # set BG to yellow
bgpic("maze.png") # BG pic only works with PNG and GIF
title("Mr. Stratton's Maze Tutorial") # Title of window
color("red") # Colour line
# shape("arrow") # Shape of the turtle (“arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”)
turtlesize(3) # size of turtle (easier for some kids to see)
pensize(3) # Set the size of the pen

penup()
goto(-420,220)
pendown()
# vvvvvv Enter your code below here vvvvvv

After you have solved the maze answer these questions:

  1. How many programming steps did you take?
  2. Can you reduce the number of steps?

Save a new copy of the program and edit it to make it more efficient (fewer lines). The number of extra lines that my program needed is below.

Read more

Higher – Count Occurrences Standard Algorithm

The count occurrences algorithm is very similar to the linear search v1. However, it includes an incrementing counter keep track of how many items it finds.

def countOcc(target,numbers):
    #Count the number of times target is found in numbers
    count=0
    for number in numbers:
        if number==target:
            count=count+1
    return count

You will notice that I have used a FOR EACH in this example as there is no requirement to track the position of the elements. This algorithm can also be used to count how many numbers are above or below a target value by simply changing the operator in the IF statment.

Higher – Find Maximum and Find Minimum Standard Algorithms

We spent a lot of last week on Standard Algorithms, most of them have the structure of an IF inside a FOR loop. While it is possible to use a FOR EACH loop this would mean that we could not know what the position was of the value we were searching for. In the examples below the returned value (max or min) could be changed to the position to allow this to be used elsewhere in the program.

To find the largest number in an array we would use the “Find Maximum” algorithm

def findMax(numbers):
    # Find biggest number
    max=numbers[0]
    for counter in range(1,len(numbers)):
        if numbers[counter]>max:
            max=numbers[counter]
            #position=counter
    return max

To find the smallest number in an array we would use the “Find Minimum” algorithm

def findMin(numbers):
    #Find smallest number
    min=numbers[0]
    for counter in range(1,len(numbers)):
        if numbers[counter]<min:
            min=numbers[counter]
            #position=counter
    return min

Notice that both of these functions are very similar with only the operator changing. Did you also notice that the for loop starts from index 1? Why do you think this is?

Higher – Linear Search Standard Algorithm

A linear search is used to check if a value is in an array. There are two ways of doing this:-

Check every value in the list, even if you find the value immediatly.

Check until you find the value you are looking for, this is much more effient and can on average half the ammount of time taken for the program to run.

The same algorithms can be used to find a string in an array of strings or a character in a string.

Higher – Random Number Array Function

The class was asked to create a function that generated 100 number dice throws and stored them in an array.

This function is used to create an array of random integers. The size of the array and the magnatude of the values is set when the function is called.


def randomNumbers(size,min,max):
    # creates an array of (size) random numbers between min and max
    import random
    numbers=[]
    for loop in range(size):
        numbers.append(random.randint(min,max))
    return numbers

rndNumbers=randomNumbers(100,1,6)