Docsity

Computational Thinking - Computer Literacy - Lecture Slides, Slides of Computer Science

Partial preview of the text

Download Computational Thinking - Computer Literacy - Lecture Slides and more Slides Computer Science in PDF only on Docsity!

Computational Thinking

Section 7.

Algorithms

An algorithm for solving a problem is:

  • an unambiguous set of instructions
  • that can be executed in a finite amount of time and
  • that, when finished, has solved the problem.

Stepwise Refinement

1. Make the crust.

1. Take 1 1/3 cup flour.

2. Sift the flour

3. Mix the sifted flour with ½ cup butter and ¼ cup water.

4. Roll into two 9-inch pie crusts.

2. Make the cherry filling.

1. Open a 16-ounce can of cherry pie filling and pour into bowl.

2. Add a dash of cinnamon and nutmeg and stir.

3. Pour the filling into the crust.

4. Bake at 350 for 45 minutes.

Stepwise Refinement

1. Make the crust.

1. Take 1 1/3 cup flour.

2. Sift the flour.

  1. Get out the sifter, which is the device shown in page A-9 of your cookbook, and place it directly on top of a 2-quart bowl.
  2. Pour the flour into the top of the sifter and turn the crank in a counterclockwise- direction.
  3. Let all the flour fall through the sifter into the bowl.

An Algorithm in Python

def average(numbers): sum = 0 for num in numbers: sum = sum + num

return(sum//len(numbers))

By the way, does this algorithm handle errors gracefully?

A Better Algorithm in Python

def average(numbers): try: sum = 0 for num in numbers: sum = sum + num

return(sum//len(numbers)) except: print("Only defined for list of numbers") return(0)

Our First Step

def chess(board): while game_on: internal_board = scan(board) move = choose(internal_board) play(move, board)

This is a real Python program. We’ll study its syntax later.

Our First Step

def chess(board): while game_on: internal_board = scan(board) move = choose(internal_board) play(move, board)

Divide-and conquer

Our First Step

def chess(board): while game_on: internal_board = scan(board) move = choose(internal_board) play(move, board)

Is this program robust?

Our First Step

def chess(board): try: while game_on: internal_board = scan(board) move = choose(internal_board) play(move, board) except: print("Must start with a valid board")

How to Choose a Move?

def chess(board): while game_on: internal_board = scan(board) move = choose(internal_board) play(move, board)

Designing an Algorithm

  • What objects can we work with?

Designing an Algorithm

  • What objects can we work with?

Actually, we work with internal representations of

the real world objects.

Designing an Algorithm

  • What objects can we work with?
  • What can we do with them?