Pseudocode. 1 Guidelines for writing pseudocode. CS 231 Naomi Nishimura

Similar documents
Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122

Guidelines for Writing Mathematical Proofs

Style and Submission Guide

The second statement selects character number 1 from and assigns it to.

Lecture Notes for Chapter 2: Getting Started

An Introduction to Python (TEJ3M & TEJ4M)

The Big Python Guide

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

printf( Please enter another number: ); scanf( %d, &num2);

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

G Programming Languages - Fall 2012

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

C++ Style Guide. 1.0 General. 2.0 Visual Layout. 3.0 Indentation and Whitespace

SOFTWARE ENGINEERING DESIGN I

Chapter 8 Algorithms 1

Intro to Algorithms. Professor Kevin Gold

EE 382 Style Guide. March 2, 2018

SML Style Guide. Last Revised: 31st August 2011

Java Style Guide. 1.0 General. 2.0 Visual Layout. Dr Caffeine

1 Dynamic Memory continued: Memory Leaks

Chapter 9: Dealing with Errors

Java Bytecode (binary file)

CS1 Lecture 22 Mar. 6, 2019

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

Program Planning, Data Comparisons, Strings

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

Intro to semantics; Small-step semantics Lecture 1 Tuesday, January 29, 2013

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

CS112 Lecture: Making Choices

CSE 373 Spring 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

CPS122 Lecture: From Python to Java

EDITING & PROOFREADING CHECKLIST

Data Structures and Algorithms CSE 465

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion

Intro. Scheme Basics. scm> 5 5. scm>

A A B U n i v e r s i t y

Introduction to Parsing. Lecture 8

Context-free Grammars

Use of scanf. scanf("%d", &number);

Algorithms and Data Structures

CSE 230 Computer Science II (Data Structure) Introduction

L A TEX Primer. Randall R. Holmes. August 17, 2018

CS 151. Recursion (Review!) Wednesday, September 19, 12

5 The Control Structure Diagram (CSD)

Introduction to Algorithms 6.046J/18.401J

CSC236 Week 5. Larry Zhang

Propositional Logic. Part I

Theory and Algorithms Introduction: insertion sort, merge sort

5. Control Statements

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Chapter 6 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

Organisation. Assessment

Lecture 2: Getting Started

Interdisciplinary Journal of Best Practices in Global Development Final Manuscript Preparation Guidelines

19. Bulleted and Numbered Lists

Introduction to Programming, Aug-Dec 2006

Teacher Activity: page 1/9 Mathematical Expressions in Microsoft Word

Today s Outline. CSE 326: Data Structures Asymptotic Analysis. Analyzing Algorithms. Analyzing Algorithms: Why Bother? Hannah Takes a Break

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

CITS3001. Algorithms, Agents and Artificial Intelligence. Semester 2, 2016

CS 142 Style Guide Grading and Details

Fun facts about recursion

11 Coding Standards CERTIFICATION OBJECTIVES. Use Sun Java Coding Standards

CMSC 201 Spring 2019 Lab 06 Lists

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Mergesort again. 1. Split the list into two equal parts

Introduction to L A TEX for MCS-236

2 Sets. 2.1 Notation. last edited January 26, 2016

Proofwriting Checklist

CHAPTER 10 GRAPHS AND TREES. Alessandro Artale UniBZ - artale/

Introduction to Asymptotic Running Time Analysis CMPSC 122

Slicing. Open pizza_slicer.py

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators)

CS 132 Exam #1 - Study Suggestions

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Lecture 2: Variables & Assignments

Racket Style Guide Fall 2017

A very long title with deep neural networks variants applied on five databases and solving many problems occuring there.

Introduction to Algorithms 6.046J/18.401J/SMA5503

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

CS302 Topic: Algorithm Analysis. Thursday, Sept. 22, 2005

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Recursively Enumerable Languages, Turing Machines, and Decidability

Data Structures. Lists, Tuples, Sets, Dictionaries

Z Notation. June 21, 2018

Programming Style Guide v1.1

CSI33 Data Structures

(Refer Slide Time: 01.26)

Algorithms - Ch2 Sorting

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Digital Signage Content Creation Guidelines

Creating Universally Designed Word 2013 Documents - Quick Start Guide

If Statements, For Loops, Functions

<Project Name> Use Case Specification: <Use-Case Name> Version <1.0>

MergeSort, Recurrences, Asymptotic Analysis Scribe: Michael P. Kim Date: April 1, 2015

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Transcription:

Pseudocode CS 231 Naomi Nishimura In lectures, algorithms will often be expressed in pseudocode, a mixture of code and English. While understanding pseudocode is usually not difficult, writing it can be a challenge. One example of pseudocode, used in this course, is presented in Section 2. Section 3 contains examples of pseudocode found in various textbooks. 1 Guidelines for writing pseudocode Why use pseudocode at all? Pseudocode strikes a sometimes precarious balance between the understandability and informality of English and the precision of code. If we write an algorithm in English, the description may be at so high a level that it is difficult to analyze the algorithm and to transform it into code. If instead we write the algorithm in code, we have invested a lot of time in determining the details of an algorithm we may not choose to implement (as we typically wish to analyze algorithms before deciding which one to implement). The goal in writing pseudocode, then, is to provide a high-level description of an algorithm which facilitates analysis and eventual coding (should it be deemed to be a good algorithm) but at the same time suppresses many of the details that vanish with asymptotic notation. Finding the right level in the tradeoff between readability and precision can be tricky. If you have questions about the pseudocode you are writing on an assignment, please ask one of the course personnel to look it over and give you feedback (preferably before you hand it in so you can change it if necessary). Just as a proof is written with a type of reader in mind (hence proofs in undergraduate textbooks tend to have more details than those in journal papers), algorithms written for different audiences may be written at different levels of detail. In assignments and exams for the course, you need to demonstrate your knowledge without obscuring the big picture with unneeded detail. Here are a few general guidelines for checking your pseudocode: 1. Mimic good code and good English. Using aspects of both systems means adhering to the style rules of both to some degree. It is still important that variable names be mnemonic, comments be included where useful, and English phrases be comprehensible (full sentences are usually not necessary). 2. Ignore unnecessary details. If you are worrying about the placement of colons, you are using too much detail. It is a good idea to use some convention to group statements (begin/end, brackets, or whatever is clear), but you shouldn t obsess about syntax. 3. Don t belabour the obvious. In many cases, the type of a variable is clear from context; unless it is critical that it is specified to be an integer, for example, it is often unnecessary to make it explicit. 4. Take advantage of programming shorthands. Using branching or looping structures is more concise than writing out the equivalent in English; general constructs that are not

CS 231: Pseudocode 2 peculiar to a small number of languages are good candidates for use in pseudocode. Using parameters when defining functions is concise, clear, and accurate, and hence should not be omitted from pseudocode. 5. Consider the context. If you are writing an algorithm for mergesort, the statement Use mergesort to sort the values is hiding too much detail; if we have already studied mergesort in class and later use it as a subroutine in another algorithm, the statement would be appropriate to use. 6. Don t lose sight of the underlying model. It should be possible to see through your pseudocode to the model below; if not (that is, you are not able to analyze the algorithm easily), it is written at too high a level. 7. Check for balance. If the pseudocode is hard for a person to read or difficult to translate into working code (or worse yet, both!), then something is wrong with the level of detail you have chosen to use. 2 Pseudocode used in the course The pseudocode used in the course will adhere to the following conventions: To make it distinguishable from code, which is presented in typewriter font, pseudocode is presented using italics. Variable names are capitalized, and function names are written in all capital letters. Simple Python list operations, such as [] for an empty list or accessing an item in a position, will be included, but no powerful operations, such as sorted and reverse. The Python method len will be written as Length for consistency with other names. Function definitions are presented with a three-line preamble consisting of the name of the function and parameters, the input, and the output. Function applications are given as the name of the function with all parameters appearing afterwards in parentheses, separated by commas. For consistency, instead of using dot notation for methods, the object appears as one of the inputs. For example, a method that counts the number of times an item x appears a list L might be written as Count(L, x). Reserved words (such as for and if ) are shown in boldface. Assignment statements are shown using, like in Example 3. Other common conventions are the use of = (Example 4) and := (Example 2). Types of variables are not listed explicitly, unlike in Examples 2 (which uses integer) and 4 (which uses int). Ideally, the code will be written in such a way that the type is clear from context, or from the listing of inputs and outputs.

CS 231: Pseudocode 3 Indentation is used to group statements, like in Python. The word return is used to indicate that a value is returned. Branching mimics Python; thus, if and are used, but unlike in Examples 1 3, not then. In for loops, a loop that goes from the value Start to the value Finish will be written for Count from Start to Finish, where Count can be replaced by a variable of another name. The comparable Python code would be for count in range(start, finish+1). For a for loop over a list or other collection, for each is used. For the ease of analysis, almost always a line will contain a finite number of simple tasks (cost Θ(1)) or a function application. As you can see from the example of binary search below, the pseudocode is quite close to Python. Binsearch(L, Item) INPUT: A list L OUTPUT: True or False depending on whether Item is in L if Length(L) 1 if Length(L) == 1 and L[0] == Item return True return False Mid = Floor( Length(L) / 2) if L[Mid] == Item return True if L[Mid] > Item return Binsearch(L[:Mid], Item) return Binsearch(L[Mid+1:], Item) 3 Pseudocode style examples Various styles of pseudocodes can be observed in these examples of the binary search algorithm. Not all of these examples are worth emulating, as some are too detailed and some are hard to understand. Example 1 The Design and Analysis of Computer Algorithms, Aho, Hopcroft, and Ullman, 1974, page 114.

CS 231: Pseudocode 4 procedure SEARCH(a, f, l): if f > l then return "no" if a = A[ (f+l)/2 ] then return "yes" if a < A[ (f+l)/2 ] then return SEARCH(a, f, (f+l)/2-1) return SEARCH(a, (f+l)/2 + 1, l) Example 2 Algorithms, Robert Sedgewick, 1988, p. 198. function binarysearch(v:integer):integer; var x, l, r:integer; begin l:=1; r:=n; repeat x:=(l+r)div 2; if v<a[x].key then r:=x-1 l:=x+1 until (v=a[x].key) or (l >r); if v=a[x].key then binarysearch:=x binarysearch:=n + 1 end; Example 3 Data Structures and Their Algorithms, Lewis and Denenberg, 1991, p. 182. function BinarySearchLoopUp(key K, table T[0..n-1]): info {Return information stored with key K in T, or Λ if K is not T} Left 0 Right n-1 repeat forever if Right < Left then return Λ Middle (Left + Right)/2 if K = Key(T[Middle]) then return info(t[middle]) if K < Key(T[Middle]) then Right Middle - 1 Left Middle + 1 Example 4 Computer Algorithms: Introduction to Design and Analysis, Baase and Van Gelder, 2000, p. 129

CS 231: Pseudocode 5 int binarysearch(int[], E, int first, int last, int K) if (last < first) index = -1; int mid - (first + last)/2; if (K == E[mid]) index = mid; if (K < E[mid]) index = binarysearch(e, first, mid-1, K); index = binarysearch(e, mid+1, last, K); return index;