ENGR 102 Engineering Lab I - Computation

Size: px
Start display at page:

Download "ENGR 102 Engineering Lab I - Computation"

Transcription

1 ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation x = [x 0, x 1, x 2,..., x n ], (1) 1 These notes are based closely on a PowerPoint presentation prepared by Dr. John Keyser for the Pilot Course version of ENGR 102. and we saw that many operations we may want to perform on an array involve iteration, such as for the mean x = 1 n n x i. (2) i=0 We also learned that we could store this type of data in a built-in Python data type called a list. Lists are key element of the for loop iteration structure, 2 and we can create lists using a command such as 2 More generally, for loops operate on any iterable object. In this lecture, we will learn more about how lists work, and we will introduce three other ways to store array-type data in Python. These are the data types of tuples, dictionaries, and a special type of list we will import from the numpy package, called arrays. Tuples are like lists, but their values cannot be changed once you create them. Dictionaries are like lists and tuples, except that you get to name the index to the list that index is a keyword; hence, the term dictionary. Numpy arrays are special lists that can be used in mathematical operations. Together, these Python data types give us a lot of flexibility to store arrays of data and manipulate them to extract meaningful, quantitative metrics that describe them. Data storage in list, tuple, dict, and array Each of the array-type data types in Python are similar in that they can store multiple values in a variable of a single name. We create these different data types using different syntax, and each data type behaves in a slightly different way. It is the differences among these data types that help us to decide the best data type to use to store a given dataset.

2 2 engr Basic behavior of the list data type Lists are actually much more flexible than the single example above that stores exam grades. Lists can contain non-numeric values and can contain lists of lists, as in 3 names = [ John, Kathy, Elsa, David, [47, 36, 27, 19], [True, False, False, True]] This list has six elements, four are strings and two are additional lists; the nested lists contain a list of integers and a list of Booleans. On the other hand, because lists can contain just about anything, they do not operate in mathematical statements like arrays or vectors. If you try to add two lists, they concatenate like strings: 4 grades = grades + [87., 54.] print(grades) [98.0, 87.0, 97.0, 89.0, 92.0, 87.0, 54.0] 3 It would be a good idea to type all of the example code from this lecture into an interactive Python window to see what happens. 4 Notice that we have to add two lists; you cannot add a number to a list as in grades = grades + 87.; to do that we have to put the value in a list like [87.], or we can use the list method append, as in grades.append(87.). Another important attribute of lists is that you can change their values after you create them. As an example: grades[2] = 97. Remember from last week, we access individual elements of a list using an index counter that starts counting from zero. Thus, the above statement changes the 92.5 in the third element 5 to be Element number 2 when counting 0, 1, 2. Basic behavior of the tuple data type There is a similar kind of list, called a tuple, that does not allow you to change its values after you create it. You create tuples the same way you create lists, but using () instead of [], as in: grades = (98., 87., 92.5, 89., 92.) Tuples are accessed identically to lists, but are unchangeable. 6 In this way, grades[2] 6 The word we use for unchangeable in object-oriented programming is immutable. We say in Python that tuple objects are immutable. now returns the value 92.5, but grades[2] = 97. throws an error. We can also change lists into tuples and tuples into lists: exams = tuple(grades) scores = list(exams) # This is a list # This is a tuple # This is a list

3 engr 102 engineering lab i - computation 3 Basic behavior of the dict data type The last way we can store data using built-in data types is in dictionaries. Lists and tuples are both indexed by a counter that starts at zero, as in grades[2] In a dictionary, we get to choose what to call the index. We create dictionaries using {}. So, if we want our index to be a person s name and the data stored in the dictionary to be their age, we could write: ages = { John : 47, Kathy : 36, Elsa : 27, David : 19} Then, to find out Kathy s age, we could write ages[ Kathy ] and the value 36 is returned. We call the indexes to the dictionary a key, and if you try to use a key that does not yet exist, you get an error: ages[ Bill ] KeyError: Bill An alternative way to create a dictionary is to index a new key name and use the assignment operator. Hence, 7 ages[ Bill ] = 29. is a valid way to add the data for Bill to the variable ages. Basic behavior of the array data type in numpy The data types we have seen so far have parallels in lower-level programming languages, like C and Fortran. To do mathematics with them, we generally have to do everything by hand. 8 A common example is in converting sensor data to meaningful measurements. Temperature sensors are generally linear over a certain range, where the temperature can be computed from 7 Notice that even though we use [] on the right-hand-side of an assignment statement to create lists, () to create tuples, and {} to create dictionaries, we always use [] on the left-hand-side of an assignment to surround the index or key name. 8 In other words, we write operations that will be done on each element of the array, and we embed these operations in an iteration structure, such as a for loop. T = av + b (3) where a and b are calibration constants and V is the voltage read by the sensor. If you have an array of voltage data, you need to compute T i = a V i + b (4) for each element i to find all the temperatures. You cannot multiple a list by a constant to compute an equation with that list; instead, like strings, multiplication for lists is defined only for integers and results in multiple lists.

4 4 engr You can solve the above problem with lists using a for loop 1 # Let V contain the voltage measured by an analog temperature probe 2 V = [3.57, 3.46, 3.67, 3.44, 3.55] 3 T = [] # Initialize empty list to hold computed temperatures 4 5 # Compute the temperature in deg F from the calibration curve given by 6 # T = * V , where V is the voltage reading of the sensor 7 a = b = for i in range(len(v)): 10 T.append(a * V[i] + b) # Return the results 13 print('the measured temperatures in deg F are:') 14 print(t) This works fine, 9 but it takes a lot of lines of code, and it is normally not as fast to execute iterations of a for loop in Python as it would be in C or Fortan. Instead, it would be nice to replace the for loop with the single command 9 When we run this code, the output is: The measured temperatures in deg F are: [ , , , , ] T = a * V + b and have that create a new array T that contains the desired result. We can do this with numpy arrays. As the name implies, the numpy package provides numerical data types to Python. The most basic numpy data type is an array. By convention, we import the numpy package using the following command: import numpy as np This allows us to use functions in numpy through operation in the format np.<fun>(). The simplest way to create a numpy array is to send a list as the input to the np.array() function: V = np.array([3.57, 3.46, 3.67, 3.44, 3.55]) print(v) [ ] This looks like a regular list, but we notice when we print the array, the commas are missing, and importantly, we can use it to do math without a for loop. Our program from above using numpy now becomes: 1 import numpy as np 2 3 # Let V contain the voltage measured by an analog temperature probe 4 V = np.array([3.57, 3.46, 3.67, 3.44, 3.55]) 5 6 # Compute the temperature in deg F from the calibration curve given by

5 engr 102 engineering lab i - computation 5 7 # T = * V , where V is the voltage reading of the sensor 8 a = b = T = a * V + b # Return the results 13 print('the measured temperatures in deg F are:') 14 print(t) This program has the identical output as before, but without the commas when displaying the printed T data. Numpy arrays also have built-in methods to compute statistics. Hence, we could continue our code above to print out the mean and variance of the temperature as Try it in Python. print( The mean temperature is + str(t.mean()) + (deg F) ) print( and the temperature variance is + str(t.var()) + (deg F)^2 ) Clearly, the numerical power of numpy to operate on our data is great, and we will want to take advantage of numpy to manipulate numerical data as much as possible. A Closer Look at the list data type The previous section introduced four different ways to store arraytype data 11 In this section, we will look at the list data type more carefully. Many of the operations we describe below can be applied to tuples and numpy arrays, except that tuples cannot be changed. 12 We can always find the length of a list using the built-in function len() as in print(len(grades)) 5 11 These are using lists, tuples, dictionaries, and numpy arrays. 12 We cannot change a tuple value in an assignment state, nor can we append anything to a tuple. Once a tuple is created, it is unchangeable, or immutable. When we create a list, Python allocates a block of memory on our computer, just as for any other variable. Because we may store a lot of data in a list, Python does something we have not yet seenif we create a list from an existing list. Consider these lines of code: my_grades = grades my_grades[2] = 0. print(grades[2]) What do you think the print function should print? We expect it to print 92.5 since that value is stored in the third element of grades (i.e., index number two). Instead, the outcome is: 0.0 What happend?! The line my_grades = grades does not create a new block of memory to store a new dataset. Instead, it creates a second

6 6 engr variable name, in this case my_grades that points at the same block of memory as the variable name grades. So, when we change a value using the variable name my_grades, it actually changes the value for both grades and my_grades since they both point at the same physical block of bytes in the computer s memory. Hence, we must be very careful when we use variable names that contain lists on the right-hand-side of the assignment operator! Last week, we also saw that a for loop will access each element of a list one-at-a-time. What do you think this code will do: for grade in grades: grade = 0. print(grades) After the previous example, you may be tempted to think that grades now contains a list of five zeros. Instead, the print statement returns [98.0, 87.0, 92.5, 89.0, 92.0] What happend here?! The for loop creates a copy of each element of the list grades one-at-a-time in a new memory location in order to be sure you don t accidentally change values in grades inside the loop. If you wanted to change all the grades to zero, you would have to write for i in range(len(grades)): grades[i] = 0. print(grades) Here, grades[i] is an index to the real memory location of the ith element of grades, and the print statement does return [0.0, 0.0, 0.0, 0.0, 0.0] Adding data to a list As we saw above in the basic introduction to lists, we can add elements to a list using the.append() list method or by concatenation using +. If we just want to add one element to a list, you add it as a list: grades = [] grades = grades + [98.] grades.append(87.) print(grades) [98.0, 87.0] # create an empty list Indexing and slicing lists We can index arrays in more flexible ways than just with an integer value of the element number. For all of the following examples, assume we have created the list

7 engr 102 engineering lab i - computation 7 If we want the last element, we can use -1 to get it print(grades[-1]) 92.0 We can also extract slices, or spans, of the list using the colon operator. The colon operator works as in: start : stop : step where start is the element number of the first element to include in the slice, stop is the element number of the first element not to include in the slice, and step is the step size of the slice counter. Hence, we can have print(grades[1:3]) [87.0, 92.5] print(grades[0:4]) [98.0, 87.0, 92.5, 89.0] print(grades[:4]) [98.0, 87.0, 92.5, 89.0] print(grades[:-4:-1]) [92.0, 89.0, 92.5] print(grades[3:]) [89.0, 92.0] There are lots of ways to use slices! If we do not specify a step, we get the default step size, which is one. If we omit start, Python starts at zero; if we omit stop, Python sets stop to include the last data point. If we use negative values, Python just counts backward the -2 element of grades is 89. We can slice numpy arrays in much the same way, and the slice operation will return a numpy array. When you have a list inside a list, you can use successive [][] indices to drill down into a list. Consider points = [[2, 4], [3, 5], [6, 4]] To return the 6 in the third list above, we could use points[2][0] Numpy also supports multidimensional arrays, and their indexing is the same. Try np.array(points) and see how you can slice it. Are strings lists? If you worked some of the challenge problems in the Lab assignments, you may have seen that we can get one character of a string using the indexing notation, for example name = Scott A. Socolofsky print(name[6]) A

8 8 engr Strings act like lists, but they are their own data type. They can only store characters. Hence, this command gives an error name = name + [7] since 7 is an integer and only a string can be concatenated to a string. Also unlike lists, strings are said to be immutable. As a result, this command also gives an error name[6] = a Hence, in this regard, one might think of strings as special kinds of tuples. Conclusions The fastest way to understand array-type data is to start programming with it and we will do that this week in the Lab assignments. We will start by primarily using the list data type, which will require you to iterate through the dataset by hand to make calculations. In this way, you will gain understanding of what is happening to your data element-by-element. Soon, we will avoid writing a lot of loops to do dataset mathematics whenever we can replace the operation by a numpy array operation these will always be faster since they are coded in C and compiled to create the numpy package. We conclude with a very loose rule-of-thumb for when to use what data type: Use a list for non-numeric datasets and for datasets that may be formatted and sorted but that will not be operated on using math formulas. Use a tuple like a list, but select a tuple when you want to ensure that the data values in the dataset cannot be changed. Use a dict when the keyword that is associated with each datapoint is something other than simply an integer subscript. For instance, when you want to associate a data value with a keyword name as in a database. Use a numpy array whenever you have numerical data on which you want to make numerical calculations or for which you want to compute statistics. This will be the most common Python arraylike data type used in engineering.

ENGR (Socolofsky) Week 07 Python scripts

ENGR (Socolofsky) Week 07 Python scripts ENGR 102-213 (Socolofsky) Week 07 Python scripts A couple programming examples for this week are embedded in the lecture notes for Week 7. We repeat these here as brief examples of typical array-like operations

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

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

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

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

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

\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

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

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

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

ENGR (Socolofsky) Week 02 Python scripts

ENGR (Socolofsky) Week 02 Python scripts ENGR 102-213 (Socolofsky) Week 02 Python scripts Listing for script.py 1 # data_types.py 2 # 3 # Lecture examples of using various Python data types and string formatting 4 # 5 # ENGR 102-213 6 # Scott

More information

TUPLES AND RECURSIVE LISTS 5

TUPLES AND RECURSIVE LISTS 5 TUPLES AND RECURSIVE LISTS 5 COMPUTER SCIENCE 61A July 3, 2012 1 Sequences From the Pig project, we discovered the utility of having structures that contain multiple values. Today, we are going to cover

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

Decisions, Decisions. Testing, testing C H A P T E R 7

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

Lecture 3. Input, Output and Data Types

Lecture 3. Input, Output and Data Types Lecture 3 Input, Output and Data Types Goals for today Variable Types Integers, Floating-Point, Strings, Booleans Conversion between types Operations on types Input/Output Some ways of getting input, and

More information

Notebook. March 30, 2019

Notebook. March 30, 2019 Notebook March 30, 2019 1 Complex Data Types Some kinds of data can store other kinds of data. 1.1 Lists We ve actually seen the most common complex data type a few times before, I just haven t pointed

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

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

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

More information

Introduction to Problem Solving and Programming in Python.

Introduction to Problem Solving and Programming in Python. Introduction to Problem Solving and Programming in Python http://cis-linux1.temple.edu/~tuf80213/courses/temple/cis1051/ Overview Python sequences Lists, Tuples, and Ranges Built-in operations Slicing

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

: Intro Programming for Scientists and Engineers Final Exam

: Intro Programming for Scientists and Engineers Final Exam Final Exam Page 1 of 6 600.112: Intro Programming for Scientists and Engineers Final Exam Peter H. Fröhlich phf@cs.jhu.edu December 20, 2012 Time: 40 Minutes Start here: Please fill in the following important

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

Week Two. Arrays, packages, and writing programs

Week Two. Arrays, packages, and writing programs Week Two Arrays, packages, and writing programs Review UNIX is the OS/environment in which we work We store files in directories, and we can use commands in the terminal to navigate around, make and delete

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

Week - 03 Lecture - 18 Recursion. For the last lecture of this week, we will look at recursive functions. (Refer Slide Time: 00:05)

Week - 03 Lecture - 18 Recursion. For the last lecture of this week, we will look at recursive functions. (Refer Slide Time: 00:05) Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 03 Lecture - 18 Recursion For 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

Introduction to Python: Data types. HORT Lecture 8 Instructor: Kranthi Varala

Introduction to Python: Data types. HORT Lecture 8 Instructor: Kranthi Varala Introduction to Python: Data types HORT 59000 Lecture 8 Instructor: Kranthi Varala Why Python? Readability and ease-of-maintenance Python focuses on well-structured easy to read code Easier to understand

More information

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries Assignment: Lab 12 Tuples and Dictionaries Due Date: During discussion, November 30 th through December 3 rd Value: 1% of final grade Part 1: Data Types

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

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

Handling arrays in Python (numpy)

Handling arrays in Python (numpy) Handling arrays in Python (numpy) Thanks to all contributors: Alison Pamment, Sam Pepler, Ag Stephens, Stephen Pascoe, Anabelle Guillory, Graham Parton, Esther Conway, Wendy Garland, Alan Iwi and Matt

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02) Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 04 Lecture - 01 Merge Sort (Refer

More information

Programming in C++ PART 2

Programming in C++ PART 2 Lecture 07-2 Programming in C++ PART 2 By Assistant Professor Dr. Ali Kattan 1 The while Loop and do..while loop In the previous lecture we studied the for Loop in C++. In this lecture we will cover iteration

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for

More information

Advanced Algorithms and Computational Models (module A)

Advanced Algorithms and Computational Models (module A) Advanced Algorithms and Computational Models (module A) Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 34 Python's built-in classes A class is immutable if each object of that class has a xed value

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

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

The second statement selects character number 1 from and assigns it to. Chapter 8 Strings 8.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: The second statement selects character number 1

More information

Consolidation and Review

Consolidation and Review Consolidation and Review Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction to Computer Science, 2 nd edition,

More information

Selection Statement ( if )

Selection Statement ( if ) Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 4 Selection Statement ( if ) Eng. Ibraheem Lubbad October 10, 2016 In this lab we will constructs program that allow

More information

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

For strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table.

For strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table. Page 1 6.189 Notes Session 8 Day 6: Immutable Objects Earlier, we made a big deal about the fact that lists are mutable. The reason this is important is because certain objects are immutable once created,

More information

Introduction to Python

Introduction to Python Introduction to Python EECS 4415 Big Data Systems Tilemachos Pechlivanoglou tipech@eecs.yorku.ca 2 Background Why Python? "Scripting language" Very easy to learn Interactive front-end for C/C++ code Object-oriented

More information

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi Python Tutorial CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi 1 Python2 vs Python3 Python syntax Data structures Functions Debugging Classes The NumPy Library Outline 2 Many examples adapted from

More information

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

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

Fundamentals of Python: First Programs. Chapter 4: Strings (Indexing, Slicing, and Methods)

Fundamentals of Python: First Programs. Chapter 4: Strings (Indexing, Slicing, and Methods) Fundamentals of Python: First Programs Chapter 4: Strings (Indexing, Slicing, and Methods) Objectives After completing this lesson, you will be able to: 1) Know the definition of a string and that strings

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

The Practice of Computing Using PYTHON

The Practice of Computing Using PYTHON The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures

More information

Lists CS 1111 Introduction to Programming Fall 2018

Lists CS 1111 Introduction to Programming Fall 2018 Lists CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 12] 1 Overview: Lists List = ordered sequence of values Mutable data type Because of the ordering, an element in a list can

More information

Unit E Step-by-Step: Programming with Python

Unit E Step-by-Step: Programming with Python Unit E Step-by-Step: Programming with Python Computer Concepts 2016 ENHANCED EDITION 1 Unit Contents Section A: Hello World! Python Style Section B: The Wacky Word Game Section C: Build Your Own Calculator

More information

DSC 201: Data Analysis & Visualization

DSC 201: Data Analysis & Visualization DSC 201: Data Analysis & Visualization Arrays Dr. David Koop Class Example class Rectangle: def init (self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h def set_corner(self, x, y): self.x =

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

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

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

ECS15, Lecture 13. Midterm solutions posted. Topic 4: Programming in Python, cont. Staying up to speed with Python RESOURCES. More Python Resources

ECS15, Lecture 13. Midterm solutions posted. Topic 4: Programming in Python, cont. Staying up to speed with Python RESOURCES. More Python Resources Midterm solutions posted ECS15, Lecture 13 Topic 4: Programming in Python, cont. Don t forget, you have one week since the material returned to request a re-grade for whatever reason. We will re-evaluate

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

NumPy quick reference

NumPy quick reference John W. Shipman 2016-05-30 12:28 Abstract A guide to the more common functions of NumPy, a numerical computation module for the Python programming language. This publication is available in Web form1 and

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

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

CS 2316 Individual Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 18th, before 11:55 PM Out of 100 points

CS 2316 Individual Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 18th, before 11:55 PM Out of 100 points CS 2316 Individual Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 18th, before 11:55 PM Out of 100 points Files to submit: 1. HW4.py This is an INDIVIDUAL assignment! Collaboration at a

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

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

COMP1730/COMP6730 Programming for Scientists. Sequence types, part 2

COMP1730/COMP6730 Programming for Scientists. Sequence types, part 2 COMP1730/COMP6730 Programming for Scientists Sequence types, part 2 Lecture outline * Lists * Mutable objects & references Sequence data types (recap) * A sequence contains n 0 values (its length), each

More information

CS 1803 Pair Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 29th, before 6 PM Out of 100 points

CS 1803 Pair Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 29th, before 6 PM Out of 100 points CS 1803 Pair Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 29th, before 6 PM Out of 100 points Files to submit: 1. HW4.py This is a PAIR PROGRAMMING Assignment: Work with your partner!

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Module 02 Lecture - 45 Memoization Let us continue our discussion of inductive definitions. (Refer Slide Time: 00:05)

More information

All programs can be represented in terms of sequence, selection and iteration.

All programs can be represented in terms of sequence, selection and iteration. Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational

More information

CMSC 201 Computer Science I for Majors

CMSC 201 Computer Science I for Majors CMSC 201 Computer Science I for Majors Lecture 02 Intro to Python Syllabus Last Class We Covered Grading scheme Academic Integrity Policy (Collaboration Policy) Getting Help Office hours Programming Mindset

More information

APPM 2460 Matlab Basics

APPM 2460 Matlab Basics APPM 2460 Matlab Basics 1 Introduction In this lab we ll get acquainted with the basics of Matlab. This will be review if you ve done any sort of programming before; the goal here is to get everyone on

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015 Numerical Methods Claus Führer Alexandros Sopasakis Centre for Mathematical Sciences Lund University Spring 2015 Preface These notes serve as a skeleton for the course. They document together with the

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

Lab 7 1 Due Thu., 6 Apr. 2017

Lab 7 1 Due Thu., 6 Apr. 2017 Lab 7 1 Due Thu., 6 Apr. 2017 CMPSC 112 Introduction to Computer Science II (Spring 2017) Prof. John Wenskovitch http://cs.allegheny.edu/~jwenskovitch/teaching/cmpsc112 Lab 7 - Using Stacks to Create a

More information

CPS122 Lecture: From Python to Java

CPS122 Lecture: From Python to Java Objectives: CPS122 Lecture: From Python to Java last revised January 7, 2013 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

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

CSCA20 Worksheet Strings

CSCA20 Worksheet Strings 1 Introduction to strings CSCA20 Worksheet Strings A string is just a sequence of characters. Why do you think it is called string? List some real life applications that use strings: 2 Basics We define

More information

Molecular Statistics Exercise 1. As was shown to you this morning, the interactive python shell can add, subtract, multiply and divide numbers.

Molecular Statistics Exercise 1. As was shown to you this morning, the interactive python shell can add, subtract, multiply and divide numbers. Molecular Statistics Exercise 1 Introduction This is the first exercise in the course Molecular Statistics. The exercises in this course are split in two parts. The first part of each exercise is a general

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

Python Review IPRE

Python Review IPRE Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information

Physics 514 Basic Python Intro

Physics 514 Basic Python Intro Physics 514 Basic Python Intro Emanuel Gull September 8, 2014 1 Python Introduction Download and install python. On Linux this will be done with apt-get, evince, portage, yast, or any other package manager.

More information

Topic 7: Lists, Dictionaries and Strings

Topic 7: Lists, Dictionaries and Strings Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:

More information

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python ENGG1811 UNSW, CRICOS Provider No: 00098G W4 Computers have changed engineering http://www.noendexport.com/en/contents/48/410.html

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

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

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries Chapter 1 Data types In this chapter you will: learn about data types learn about tuples, lists and dictionaries make a magic card trick app. Data types In Python Basics you were introduced to strings

More information

Python Review IPRE

Python Review IPRE Python Review Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information

CS 301: Recursion. The Art of Self Reference. Tyler Caraza-Harter

CS 301: Recursion. The Art of Self Reference. Tyler Caraza-Harter CS 301: Recursion The Art of Self Reference Tyler Caraza-Harter Goal: use self-reference is a meaningful way Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's

More information

PHY224 Practical Physics I Python Review Lecture 1 Sept , 2013

PHY224 Practical Physics I Python Review Lecture 1 Sept , 2013 PHY224 Practical Physics I Python Review Lecture 1 Sept. 16-17, 2013 Summary Python objects Lists and arrays Input (raw_input) and output Control Structures: iterations References M H. Goldwasser, D. Letscher:

More information

a b c d a b c d e 5 e 7

a b c d a b c d e 5 e 7 COMPSCI 230 Homework 9 Due on April 5, 2016 Work on this assignment either alone or in pairs. You may work with different partners on different assignments, but you can only have up to one partner for

More information

JME Language Reference Manual

JME Language Reference Manual JME Language Reference Manual 1 Introduction JME (pronounced jay+me) is a lightweight language that allows programmers to easily perform statistic computations on tabular data as part of data analysis.

More information

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files Fundamentals of Python: First Programs Chapter 4: Strings and Text Files Objectives After completing this chapter, you will be able to Access individual characters in a string Retrieve a substring from

More information

8. Control statements

8. Control statements 8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon

More information