Arrays and Strings

Size: px
Start display at page:

Download "Arrays and Strings"

Transcription

1 Arrays and Strings

2 Arrays

3 Recall: Fibonacci() and Arrays a Fibonacci(n) a ß array of length n a[1] ß 1 a[2] ß 1 for i ß 3 to n a[i] ß a[i-1] + a[i-2] return a

4 Declaring Arrays var a [10]int var b [100]string var c [20]float64 Declare arrays of the given type and length. array elements:! index of array:!

5 Accessing/Changing Array Elements in Go Array elements can be accessed by putting their index between [ ] following the array name: fmt.println(a[7],a[8]) a[0] = 10 b[30] = hi there i := c[i] = 3.1 c[2*i] = c[i] x[i] can appear on left side of assignment to set a value.

6 Accessing/Changing Array Elements in Go The length of an array can be found with len(x), where x is an array. Array indices start at 0. The first element is x[0]; last element is x[len(x) - 1]. It s an error to try to access elements past the end (or before the beginning) of the array: var d [100]int d[len(d)-1] = 3 d[len(d)] = 3 d[-60] = 7 // OK // ERROR! // ERROR!

7 Command Line Arguments with os.args HW2: enter command line information that is input as parameters into a function directly. Package os provides access to these parameters: go run myprogram.go a 3 77 another param os.args is an array of strings. os.args[1] is a os.args[2] is 3 os.args[3] is 77 os.args[4] is another param os.args[0] is myprogram

8 Exiting a Program with os.exit() if terminating because of an error, use os.exit(1). if terminating normally, use os.exit(0). func RandomWalk(n, s int) { if n <= 0 { fmt.println( n must be positive! ) os.exit(1) } /* Rest of program here */ } Think: How can we make sure that we have the right number of input parameters to a program?

9 Multidimensional Arrays as 2-D Tables var a [7][4]int a[1][2] = 19 y := a[3][0] // gives 0 x := len(a) // gives 7 Think of as an array of length 7, where each element contains an array of length 4 7 rows columns

10 Multidimensional Arrays as 2-D Tables var a [7][4]int a[1][2] = 19 y := a[3][0] // gives 0 x := len(a) // gives 7 Think of as an array of length 7, where each element contains an array of length 4 7 rows columns Think: How can we determine the number of columns?

11 Multidimensional Arrays as 2-D Tables var a [7][4]int a[1][2] = 19 y := a[3][0] // gives 0 x := len(a) // gives 7 Think of as an array of length 7, where each element contains an array of length 4 7 rows columns z := len(a[0]) // gives 4

12 Strings

13 String Conversion Pain Exercise: What should be the value of MJordan? MJordan := string(45)

14 String Conversion Pain Exercise: What should be the value of MJordan? MJordan := string(45) Answer: It seems like it should be 45. But the answer is -.

15 How Strings are Represented Internally Logical interpretation Internal representation H e l l o, W o r l d! Each item in a string is called a character. A character in Go is represented using a byte variable type that is a number.

16 ASCII Chart (You don t need to know these numbers) Binary Dec Glyph ` a b c d e f g h i j k l m n o p q r s t u v w x y z { } ~ Binary Dec Glyph A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ Binary Dec Glyph (space) ! " # $ % & ' ( ) * , / : ; < = > ?

17 Restoring Sanity: strconv Package

18 Restoring Sanity: strconv Package MJordan := strconv.itoa(45) // gives 45 x, err := strconv.atoi( 107") //gives 107 if err!= nil { os.exit(1) } y, err := strconv.parsefloat( 3.1, 64) if err!= nil { os.exit(1) } Check out FormatFloat() for float to string conversion.

19 strings Package Contains many built-in string algorithms. Example: testing whether a string contains another: var a = hi, there var b = the if strings.contains(a, b) { fmt.println( String a contains string b! ) }

20 Recall: String + Operator s1 + s2 concatenate strings s1 and s2! hi + there == hithere what s + up + doc? == what s up doc?

21 Indexing Strings Strings work like arrays in some ways: Strings have fixed length. You can find the length of string s with len(s). You can access elements of string s with s[i]. s := Hi There! fmt.println(s[0]) // prints H fmt.println(s[len(s)-1]) // prints! if s[0] == H // single quotes for single symbols H i T h e r e!

22 Substrings in Go s := Hi There! fmt.println(s[3:5]) // prints Th fmt.println(s[1:]) // prints i There! fmt.println(s[:4]) // prints Hi T var str string = s[3:6] fmt.println(str) fmt.println(str[0]) // prints The // prints T H i T h e r e!

23 Recall: Counting Pattern in Text 1. Start from the first position of Text and check whether Pattern appears in Text starting at its first position. 2. If yes, draw a dot on a piece of paper. 3. Move to the second position of Text and check whether Pattern appears in Text starting at its second position. 4. If yes, draw another dot on the same piece of paper. 5. Continue until you reach the end of Text. 6. Count the number of dots on the piece of paper.

24 Example: Implement PatternCount() Pattern Counting Problem: Count the number of times that a pattern appears in a longer string. Input: Strings Text and Pattern. Output: The number of times that Pattern appears in Text. fmt.println(strings.count( ATATA, ATA )) // prints 1, not 2. Exercise: Write a PatternCount() function handling overlapping instances of Pattern solving this problem.

25 Example: Implement PatternCount() func PatternCount(Pattern, Text string) int { //fill in details here }

26 Example: Reverse Complementing a String Reverse Complement Problem: Input: A DNA string Text. Output: The reverse complement of Text. 5 3 A G T C G C A T A G T T C A G C G T A T C A 3 5 Think: How could we solve this problem top-down?

27 Example: Reverse Complementing a String ReverseComplement() Complement() Reverse()

28 (Unlike Arrays) Strings are Not Editable! func Complement(s string) string { for i:=0; i<len(s); i++ { switch s[i] { case 'A': s[i] = 'T //ERROR! case 'T': s[i] = 'A //ERROR! case 'C': s[i] = 'G //ERROR! case 'G': s[i] = 'C //ERROR! } } return s }

29 Reverse Complementing a String func Complement(s string) string { s2 := "" for i:=0; i<len(s); i++ { switch s[i] { case 'A': s2 += 'T // type! case 'T': s2 += 'A // type! case 'C': s2 += 'G // type! case 'G': s2 += 'C // type! } } return s2 }

30 Reverse Complementing a String func Complement(s string) string { s2 := "" for i:=0; i<len(s); i++ { switch s[i] { case 'A': s2 += T case 'T': s2 += A case 'C': s2 += G case 'G': s2 += C } } return s2 } Exercise: Write a Reverse() function reversing a string.

31 Reverse Complementing a String func Reverse(s string) string { s2 := n := len(s) for i:=0; i<n; i++ { s2 += string(s[n-i-1]) } return s2 }

32 Slices

33 Last Time: Random Walk Input: Integers n and s. Output: Print each step of a random walk with s steps in an n x n chessboard.

34 Self-Avoiding Random Walks Self-avoiding walk: that never visits the same square of the checkerboard twice. Input: Integers n and s. Output: Print each step of a random self-avoiding walk with s steps in an n x n chessboard (start in the middle). Exercise: Write pseudocode for a function that prints a random self-avoiding walk.

35 Pseudocode for Random Self-Avoiding Walk SelfAvoidingRandomWalk(n, s) field ß n x n boolean array holding all false (x, y) ß (n/2, n/2) field[x][y] ß true Print(x, y) for i ß 0 to (steps 1) (xnext, ynext) = (x, y) while field[xnext][ynext] (xnext, ynext) = RandomStep(x, y, 10) (x, y) = (xnext, ynext) field[x][y] = true Print(x,y) Note the code reuse of RandomStep()...

36 Just Two Little Problems 1. Corner case: If the path works itself into a corner with nowhere to go, the algorithm will have an infinite loop! 2. In Go, arrays cannot have length equal to a variable. func SelfAvoidingRandomWalk(n, s int) { var field [n][n]bool //throws error! //... blah }

37 Who First Computed Earth s Circumference?

38 Eratosthenes of Cyrene ( BC) Also: first algorithm for identifying prime numbers

39 Finding Primes Prime Number Problem: Input: An integer n. Output: All integers p < n such that p is prime.

40 Sieve of Eratosthenes

41 Sieve of Eratosthenes Prime Number Problem: Input: An integer n. Output: All integers p < n such that p is prime. Exercise: Write a program in pseudocode that takes n as input and returns an array iscomposite such that: iscomposite[i] = true if i is composite iscomposite[i] = false if i is prime

42 Fill in Details Later PrimeSieve(n) iscomposite ß array of n false boolean values biggestprime ß 2 while biggestprime < n func primesieve(iscomposite []bool) { var biggestprime = 2 for biggestprime < len(iscomposite) { for i := 2*biggestPrime; i < len(iscomposite); i += biggestprime { iscomposite[i] = true } biggestprime++ for biggestprime < len(iscomposite) && iscomposite[biggestprime] { biggestprime++ } } }

43 Strings

44 Need to Implement: Substring() and Count() FrequentWords(Text, k) FrequentPatterns ß an empty list c ß empty array of length Text - k for i ß 0 to Text - k Pattern ß Substring(Text, i, k) c[i] ß Count(Text, Pattern) maxcount ß Max(a) for i ß 0 to Text - k if a[i] = maxcount add Substring(Text, i, k) to FrequentPatterns FrequentPatterns ß RemoveDuplicates(FrequentPatterns) return FrequentPatterns

45 String + Operator s1 + s2 concatenate strings s1 and s2! hi + there == hithere what s + up + doc? == what s up doc?

46 Indexing Strings Strings work like arrays in some ways: Strings have fixed length. You can find the length of string s with len(s). You can access elements of string s with s[i]. You cannot modify a string once it has been created. s := Hi There! fmt.println(s[0]) // prints H fmt.println(s[len(s)-1]) // prints! s[3] = t // ERROR! Can t assign to strings if s[0] == H //note the single quotes for individual symbols.

47 Substrings in Go s := Hi There! fmt.println(s[3:5]) // prints Th fmt.println(s[1:]) // prints i There! fmt.println(s[:4]) // prints Hi T var str string = s[3:6] fmt.println(str) fmt.println(str[0]) // prints The // prints T H i T h e r e!

48 Recall: Counting Pattern in Text 1. Start from the first position of Text and check whether Pattern appears in Text starting at its first position. 2. If yes, draw a dot on a piece of paper. 3. Move to the second position of Text and check whether Pattern appears in Text starting at its second position. 4. If yes, draw another dot on the same piece of paper. 5. Continue until you reach the end of Text. 6. Count the number of dots on the piece of paper.

49 Example: Implement Count() Pattern Counting Problem: Count the number of times that a pattern appears in a longer string. Input: Strings Text and Pattern. Output: The number of times that Pattern appears in Text. Note: our Count() function should handle overlaps (unlike strings.count()). Think: do you see why strings is before Count()? Exercise: Write a Count() function in Go solving this problem.

50 Example: Reverse Complementing a String Reverse Complement Problem: Input: A DNA string Text. Output: The reverse complement of Text. 5 3 A G T C G C A T A G T T C A G C G T A T C A 3 5 Exercise: How could we solve this? What are the barriers?

51 Strings are Not Editable! func Complement(s string) string { for i:=0; i<len(s); i++ { switch s[i] { case 'A': s[i] = 'T //ERROR! case 'T': s[i] = 'A //ERROR! case 'C': s[i] = 'G //ERROR! case 'G': s[i] = 'C //ERROR! } } return s }

52 Self-Avoiding Random Walks Self-avoiding walk: a walk that never visits the same square of the checkerboard twice. Input: Integers n and s. Output: Print each step of a random self-avoiding walk with s steps in an n x n chessboard (start in the middle).

53 Pseudocode for Random Self-Avoiding Walk SelfAvoidingRandomWalk(n, s) field ß n x n boolean array holding all false (x, y) ß (n/2, n/2) field[x][y] ß true Print(x,y) for i ß 0 to (steps 1) (xnext, ynext) = (x, y) while field[xnext][ynext] (xnext, ynext) = RandomStep(x, y, 10) (x, y) = (xnext, ynext) field[x][y] = true Print(x,y) Note the code reuse of RandomStep()...

54 Just Two Little Problems 1. Corner case: If the path works itself into a corner with nowhere to go, the algorithm will have an infinite loop! 2. In Go, arrays cannot have length equal to a variable. func SelfAvoidingRandomWalk(n, s int) { var field [n][n]bool //throws error! //... blah }

55 Let s Next Look at Max() FrequentWords(Text, k) FrequentPatterns ß an empty list c ß empty array of length Text - k for i ß 0 to Text - k Pattern ß Substring(Text, i, k) c[i] ß Count(Text, Pattern) maxcount ß Max(a) for i ß 0 to Text - k if a[i] = maxcount add Substring(Text, i, k) to FrequentPatterns FrequentPatterns ß RemoveDuplicates(FrequentPatterns) return FrequentPatterns

56 Issue #2: Arrays Copied in Function Calls func Max(A [ ]int) int { m := 0 for i := range A { if A[i] > m { m = A[i] } } return m } func main() { var numbers [ ]int } // fill numbers with random integers for i := range numbers { numbers[i] = rand.int() } fmt.println(max(numbers)) A new array A is created and the contents from numbers is copied over (wasteful of memory).

57 (See Burrows-Wheeler Transform Slides)

58 Slices

59 Slices: Everything Arrays in Go Should Be A slice variable is declared by not specifying a size in [] var a []int // at this point a has the special value nil // and can t be used as an array a = make([]int, 10, 20) Creates an array of size 20 with a slice of size 10 inside it. 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10! 11! 12! 13! 14! 15! 16! 17! 18! 19! Length of this slice is 10! Underlying array has size 20!

60 Omitting the Third Parameter var a []int a = make([]int, 10) // this is the same as make([]int, 10, 10)

61 We Can Still Change Items var a []int a = make([]int, 10) a[3] = -18

62 Passing a Variable as Slice Length var n int = 5050 var a []string a = make([]string, n) // this is OK!

63 Defining a Slice in One Line var n int = 100 b := make([]string, n) // this is OK!

64 Recall: Literals... The Other Side of = Integer literals: a sequence of digits String literals: a sequence of characters between Hi there! 1+ = Unicode strings are supported. bool (Boolean) literals: either true or false true false

65 Array and Slice Literals Can also write slice literals (useful if you have a short list of data that may change):! var a = []float64{3.2, -30, 84, 62} var prime = []int{2,3,5,7,11}

66 Array and Slice Literals Can also write slice literals (useful if you have a short list of data that may change):! var a = []float64{3.2, -30, 84, 62} var prime = []int{2,3,5,7,11} We can also use array literals (useful for a short list of data that is fixed):! var a = [3]float64{3.2, -30.0, } var prime = [5]int{2,3,5,7,11}

67 The append() Operation If we want to make a slice bigger by adding something to the end of it... s := make([]int, 10) 0! 0! 0! 0! 0 0! 0! 0! 0 0! 0! 1! 2! 3! 4! 5! 6! 7! 8! 9!

68 The append() Operation If we want to make a slice bigger by adding something to the end of it... s := make([]int, 10) s = append(s, 5) 0! 0! 0! 0! 0 0! 0! 0! 0 0! 5 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10

More on Strings & Arrays

More on Strings & Arrays More on Strings & Arrays 02-201 Indexing Strings Strings work like arrays in some ways: Strings have fixed length. You can find the length of string s with len(s). You can access elements of string s with

More information

Issue with Implementing PrimeSieve() in Go

Issue with Implementing PrimeSieve() in Go Slices 02-201 Issue with Implementing PrimeSieve() in Go func PrimeSieve(n int) [n+1]bool { var iscomposite [n+1]bool //ERROR! biggestprime := 2 for biggestprime < n for i:=2; i

More information

Lecture 9: Lists. Lists store lists of variables. Declaring variables that hold lists. Carl Kingsford, , Fall 2015

Lecture 9: Lists. Lists store lists of variables. Declaring variables that hold lists. Carl Kingsford, , Fall 2015 Carl Kingsford, 0-0, Fall 0 Lecture : Lists Terminology: Go uses a non-standard term slice to refer to what we are calling lists. Others use the term array for the same concept. Unfortunately, Go uses

More information

Arrays/Slices Store Lists of Variables

Arrays/Slices Store Lists of Variables Maps 02-201 Arrays/Slices Store Lists of Variables H i T h e r e! 0 1 2 3 4 5 6 7 8 1 1 2 3 5 8 13 21 34 55 89 0 1 2 3 4 5 6 7 8 9 10 ACG TTA GAG CCT TAA GGG CAT 0 1 2 3 4 5 6 What if Indices Aren t Integers?

More information

From Last Time... Given a bacterial genome (~3 Mbp), where is ori?

From Last Time... Given a bacterial genome (~3 Mbp), where is ori? From Last Time... Given a bacterial genome (~3 Mbp), where is ori? Given ori (~500 bp), what is the hidden message saying that replication should start here? From Last Time... Frequent Words Problem. Find

More information

Functions & Variables !

Functions & Variables ! Functions & Variables 02-201! What Is Programming? Programming is clearly, correctly telling a computer what to do. Programming Executable Program Algorithm: (English) instructions to the computer Programming

More information

A Slice of Life

A Slice of Life A Slice of Life 02-201 More on Slices Last Time: append() and copy() Operations s := make([]int, 10)! s = append(s, 5)! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 5! 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10! s! c := make([]int,

More information

Last Time: Rolling a Weighted Die

Last Time: Rolling a Weighted Die Last Time: Rolling a Weighted Die import math/rand func DieRoll() int { return rand.intn(6) + 1 Multiple Rolls When we run this program 100 times, we get the same outcome! func main() int { fmt.println(dieroll())

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

More Examples /

More Examples / More Examples 02-201 / 02-601 Debugging How to Debug Debugging is solving a murder mystery: you see the evidence of some failure & you try to figure out what part of the code caused it. It s based on backward

More information

Homework 6: Spatial Games Due: 11:59pm on Friday, October 30

Homework 6: Spatial Games Due: 11:59pm on Friday, October 30 02-201 Homework 6: Spatial Games Due: 11:59pm on Friday, October 30 1. Set up The set up is the basically the same as for homework 4. 1. Create a directory called go someplace (different than where you

More information

Conditionals !

Conditionals ! Conditionals 02-201! Computing GCD GCD Problem: Compute the greatest common divisor of two integers. Input: Two integers a and b. Output: The greatest common divisor of a and b. Exercise: Design an algorithm

More information

// initialize array to true. for (i = 0; i < s; i++) f[i] = true; // get rid of known non-primes f[0] = f[1] = false;

// initialize array to true. for (i = 0; i < s; i++) f[i] = true; // get rid of known non-primes f[0] = f[1] = false; Listing 1: GeneratePrimes.java This class Generates prime numbers up to a user specified maximum. The algorithm used is the Sieve of Eratosthenes. Eratosthenes of Cyrene, b. c. 276 BC, Cyrene, Libya

More information

Summary of Go Syntax /

Summary of Go Syntax / Summary of Go Syntax 02-201 / 02-601 Can declare 1 or more variables in same var statement Variables Can optionally provide initial values for all the variables (if omitted, each variable defaults to the

More information

Conditionals & Loops /

Conditionals & Loops / Conditionals & Loops 02-201 / 02-601 Conditionals If Statement if statements let you execute statements conditionally. true "then" part condition a > b false "else" part func max(a int, b int) int { var

More information

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Strings and Escape Characters Primitive Data Types Variables, Initialization, and Assignment Constants Reading for this lecture: Dawson, Chapter 2 http://introcs.cs.princeton.edu/python/12types

More information

Review 4. Lists and Sequences

Review 4. Lists and Sequences Review 4 Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 x[k] = 2 * x[0] x[k 2] = 6 Create list of length 4 with all zeroes Append 2 to end of list

More information

The type of all data used in a C (or C++) program must be specified

The type of all data used in a C (or C++) program must be specified The type of all data used in a C (or C++) program must be specified A data type is a description of the data being represented That is, a set of possible values and a set of operations on those values

More information

Lecture 10: Lindenmayer Systems

Lecture 10: Lindenmayer Systems Carl Kingsford, 0-01, Fall 015 Lecture 10: Lindenmayer Systems (Stacks, Queues, append, and list literals) Lindenmayer systems or L-systems are a way to model complex shape contruction simply. They are

More information

Homework 5: Spatial Games : Programming for Scientists Due: Thursday, March 3, 2016 at 11:59 PM

Homework 5: Spatial Games : Programming for Scientists Due: Thursday, March 3, 2016 at 11:59 PM Homework 5: Spatial Games 02-201: Programming for Scientists Due: Thursday, March 3, 2016 at 11:59 PM 1. Reading Read Ch. 8 and Ch. 9 of An Introduction to Programming in Go (on pointers and structs).

More information

Introduction to Programming, Aug-Dec 2006

Introduction to Programming, Aug-Dec 2006 Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components

More information

Exercise: Using Numbers

Exercise: Using Numbers Exercise: Using Numbers Problem: You are a spy going into an evil party to find the super-secret code phrase (made up of letters and spaces), which you will immediately send via text message to your team

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016 CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016 In this course you will start by building a compiler for a language called Xi. This is an imperative,

More information

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Basic Operations jgrasp debugger Writing Programs & Checkstyle Basic Operations jgrasp debugger Writing Programs & Checkstyle Suppose you wanted to write a computer game to play "Rock, Paper, Scissors". How many combinations are there? Is there a tricky way to represent

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

Introduction to Python and Programming. 1. Python is Like a Calculator. You Type Expressions. Python Computes Their Values /2 2**3 3*4+5*6

Introduction to Python and Programming. 1. Python is Like a Calculator. You Type Expressions. Python Computes Their Values /2 2**3 3*4+5*6 1. Python is a calculator. A variable is a container Introduction to Python and Programming BBM 101 - Introduction to Programming I Hacettepe University Fall 016 Fuat Akal, Aykut Erdem, Erkut Erdem 3.

More information

Basics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011

Basics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011 Basics of Java: Expressions & Statements Nathaniel Osgood CMPT 858 February 15, 2011 Java as a Formal Language Java supports many constructs that serve different functions Class & Interface declarations

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections C++ Programming Chapter 6 Arrays and Vectors Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

The type of all data used in a C++ program must be specified

The type of all data used in a C++ program must be specified The type of all data used in a C++ program must be specified A data type is a description of the data being represented That is, a set of possible values and a set of operations on those values There are

More information

CS 61A Discussion 8: Scheme. March 23, 2017

CS 61A Discussion 8: Scheme. March 23, 2017 CS 61A Discussion 8: Scheme March 23, 2017 Announcements Ants is due today. Finish it! Also turn it in! HW 6 is due tomorrow. Finish it! Also turn it in! HW party today from 6:30-8:30p in 247 Cory. Midterm

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

Problem Solving for Intro to Computer Science

Problem Solving for Intro to Computer Science Problem Solving for Intro to Computer Science The purpose of this document is to review some principles for problem solving that are relevant to Intro to Computer Science course. Introduction: A Sample

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

CS 115 Lecture 4. More Python; testing software. Neil Moore

CS 115 Lecture 4. More Python; testing software. Neil Moore CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement

More information

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp. Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also

More information

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

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

CIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL

CIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL CIS 194: Homework 3 Due Wednesday, February 11, 2015 Interpreters An interpreter is a program that takes another program as an input and evaluates it. Many modern languages such as Java 1, Javascript,

More information

Values and Variables 1 / 30

Values and Variables 1 / 30 Values and Variables 1 / 30 Values 2 / 30 Computing Computing is any purposeful activity that marries the representation of some dynamic domain with the representation of some dynamic machine that provides

More information

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

Lecture 22 Go http://xkcd.com/979/ Go developed ~2007 at Google by Robert Griesemer, Rob Pike, Ken Thompson open sourced in 2009 compiled, statically typed very fast compilation C-like syntax garbage collection

More information

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans Computer Science 121 Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans 3.1 The Organization of Computer Memory Computers store information as bits : sequences of zeros and

More information

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

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Java basics: Compilation vs Interpretation Program structure Statements Values Variables Types Operators and Expressions

More information

Bits. Binary Digits. 0 or 1

Bits. Binary Digits. 0 or 1 Data Representation Bits Binary Digits 0 or 1 Everything stored in a computer is stored as bits. Bits can mean different things depending on how the software or hardware interpret the bits Bits are usually

More information

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017 8. The C++ language, 1 Programming and Algorithms II Degree in Bioinformatics Fall 2017 Hello world #include using namespace std; int main() { } cout

More information

Lecture 2: Variables & Assignments

Lecture 2: Variables & Assignments http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 2: Variables & Assignments (Sections 2.1-2.3,2.5) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner,

More information

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 4, April 22) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 Passing Arguments By Value and By Reference So far, we have been passing in

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

Review of Important Topics in CS1600. Functions Arrays C-strings

Review of Important Topics in CS1600. Functions Arrays C-strings Review of Important Topics in CS1600 Functions Arrays C-strings Array Basics Arrays An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why

More information

Variables and Data Representation

Variables and Data Representation You will recall that a computer program is a set of instructions that tell a computer how to transform a given set of input into a specific output. Any program, procedural, event driven or object oriented

More information

Math 15 - Spring Homework 5.2 Solutions

Math 15 - Spring Homework 5.2 Solutions Math 15 - Spring 2017 - Homework 5.2 Solutions 1. (5.2 # 14 (not assigned)) Use Prim s algorithm to construct a minimal spanning tree for the following network. Draw the minimal tree and compute its total

More information

(Refer Slide Time: 00:23)

(Refer Slide Time: 00:23) In this session, we will learn about one more fundamental data type in C. So, far we have seen ints and floats. Ints are supposed to represent integers and floats are supposed to represent real numbers.

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0)) SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

More information

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR REVISION 1 HAWTHORNE-PRESS.COM Go Idiomatic Conventions Explained in Color Published by Hawthorne-Press.com 916 Adele Street Houston, Texas 77009, USA 2013-2018

More information

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) Introduction This semester, through a project split into 3 phases, we are going

More information

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017 Introduction to Python and programming Ruth Anderson UW CSE 160 Winter 2017 1 1. Python is a calculator 2. A variable is a container 3. Different types cannot be compared 4. A program is a recipe 2 0.

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #29 Arrays in C (Refer Slide Time: 00:08) This session will learn about arrays in C. Now, what is the word array

More information

Perl for Biologists. Session 2 March 19, Constants, variables and functions. Jaroslaw Pillardy

Perl for Biologists. Session 2 March 19, Constants, variables and functions. Jaroslaw Pillardy Perl for Biologists Session 2 March 19, 2014 Constants, variables and functions Jaroslaw Pillardy Session 2: Constants, variables and functions Perl for Biologists 1.1 1 "shebang" notation path to the

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Week 03: Data Types and Console Input / Output Introduction to Types As we have already seen, 1 computers store numbers in a binary sequence of bits. The organization

More information

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) THE INTEGER DATA TYPES STORAGE OF INTEGER TYPES IN MEMORY All data types are stored in binary in memory. The type that you give a value indicates to the machine what encoding to use to store the data in

More information

Lab 10: OCaml sequences, comparators, stable sorting 12:00 PM, Nov 12, 2017

Lab 10: OCaml sequences, comparators, stable sorting 12:00 PM, Nov 12, 2017 Integrated Introduction to Computer Science Hughes Lab 10: OCaml sequences, comparators, stable sorting 12:00 PM, Nov 12, 2017 Contents 1 A last OCaml type, and its utility 1 1.1 Sequences in OCaml....................................

More information

Lecture 16: Object-oriented Programming

Lecture 16: Object-oriented Programming Carl Kingsford, 0-0, Fall 05 Lecture 6: Object-oriented Programming Programming languages provide many ways to help you organize your code. Functions are the most important and we've seen a lot of examples

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Student Number: Comments are not required except where indicated, although they may help us mark your answers. CSC 108H5 F 2018 Midterm Test Duration 90 minutes Aids allowed: none Student Number: utorid: Last Name: First Name: Do not turn this page until you have received the signal to start. (Please fill out the

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore CS 115 Data Types and Arithmetic; Testing Taken from notes by Dr. Neil Moore Statements A statement is the smallest unit of code that can be executed on its own. So far we ve seen simple statements: Assignment:

More information

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1 2.1 Indefinite Loops The final kind of control flow is Python s indefinite loop, the while loop. It functions much like the for loop in that it repeatedly executes some body of statements. The difference

More information

GO SHORT INTERVIEW QUESTIONS EXPLAINED IN COLOR

GO SHORT INTERVIEW QUESTIONS EXPLAINED IN COLOR GO SHORT INTERVIEW QUESTIONS EXPLAINED IN COLOR REVISION 1 HAWTHORNE-PRESS.COM Go Short Interview Questions Explained in Color Published by Hawthorne-Press.com 916 Adele Street Houston, Texas 77009, USA

More information

Go Tutorial. To do. A brief, gentle intro to Go. Next Networking. q Today

Go Tutorial. To do. A brief, gentle intro to Go. Next Networking. q Today Go Tutorial To do q Today A brief, gentle intro to Go q Next Networking About Go Developed by Google Webpage: https://golang.org/ Concurrency was a priority in the language design A bit of a mix between

More information

Python Class-Lesson1 Instructor: Yao

Python Class-Lesson1 Instructor: Yao Python Class-Lesson1 Instructor: Yao What is Python? Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

Programming Languages 3. Definition and Proof by Induction

Programming Languages 3. Definition and Proof by Induction Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.

More information

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

Go Cheat Sheet. Operators. Go in a Nutshell. Declarations. Basic Syntax. Hello World. Functions. Comparison. Arithmetic. Credits

Go Cheat Sheet. Operators. Go in a Nutshell. Declarations. Basic Syntax. Hello World. Functions. Comparison. Arithmetic. Credits Credits Go Cheat Sheet Most example code taken from A Tour of Go, which is an excellent introduction to Go. If you're new to Go, do that tour. Seriously. Original HTML Cheat Sheet by Ariel Mashraki (a8m):

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Python Working with files. May 4, 2017

Python Working with files. May 4, 2017 Python Working with files May 4, 2017 So far, everything we have done in Python was using in-memory operations. After closing the Python interpreter or after the script was done, all our input and output

More information

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Algorithmic Thinking: Computing with Lists

Algorithmic Thinking: Computing with Lists Algorithmic Thinking: Computing with Lists So Far in Python Data types: int, float, Boolean, string Assignments, function definitions Control structures: For loops, while loops, conditionals Last Lecture

More information

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015 Carl Kingsford, 0-0, Fall 0 Lecture : Java Overall Structure Classes & Objects Every function in Java must be inside a class, which are similar to Go's struct s. For example: 8 9 0 8 9 class MyProgram

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Slicing. Open pizza_slicer.py

Slicing. Open pizza_slicer.py Slicing and Tuples Slicing Open pizza_slicer.py Indexing a string is a great way of getting to a single value in a string However, what if you want to use a section of a string Like the middle name of

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

1 Dynamic Programming

1 Dynamic Programming Recitation 13 Dynamic Programming Parallel and Sequential Data Structures and Algorithms, 15-210 (Spring 2013) April 17, 2013 1 Dynamic Programming Dynamic programming is a technique to avoid needless

More information

Teaching London Computing

Teaching London Computing Teaching London Computing A Level Computer Science Topic 3: Advanced Programming in Python William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims Further

More information

Basic data types. Building blocks of computation

Basic data types. Building blocks of computation Basic data types Building blocks of computation Goals By the end of this lesson you will be able to: Understand the commonly used basic data types of C++ including Characters Integers Floating-point values

More information

Language Reference Manual

Language Reference Manual ALACS Language Reference Manual Manager: Gabriel Lopez (gal2129) Language Guru: Gabriel Kramer-Garcia (glk2110) System Architect: Candace Johnson (crj2121) Tester: Terence Jacobs (tj2316) Table of Contents

More information