Programming in Python

Size: px
Start display at page:

Download "Programming in Python"

Transcription

1 Programming in Python Michael Schroeder Sebas0an Salen0n Lecture 2: Sequences Slides derived from Ian Holmes, Department of Sta0s0cs, University of Oxford 1 Updates by Andreas Henschel

2 Summary: Scalars and Loops Assignment operator Arithme0c opera0ons String opera0ons Condi0onal tests Logical operators Loops Reading a file x = 5 y = x * 3 s = "Concatenating " + "strings" if y > 10: print s if y > 10 and not s == "": print s for x in range(10): print x for line in open("sequence.txt"): print line 2

3 How to sum up all the numbers in [3,7,10,4,-1,0]? print all word in [ Oranges, Bananas, Cucumbers, Apples ] star0ng with an O or A? check which element of [1,5,-1,8,7] are also inside [8,7,10,5,0,0]? check if the ra0o of two integers a and b is larger than 0.5? check for all tuples in [(3,2),(10,5),(1,-1)] if the square of the first number can be divided by the second without rest? 3

4 Overview Types of sequences and their proper0es Lists, Tuples, Strings, Iterators Building, accessing and modifying sequences List comprehensions Lambda func0ons File opera0ons 4

5 Types and Proper0es of Sequences 5

6 Lists vs tuples Both are sequences Lists should be used for storing equal elements Tuples should be used for storing different elements Lists are larger than tuples (i.e. consume more memory) mylist = [1,2,3,4] mylist2 = [ Apple, Banana, Orange ] Construc<on (Syntax) mytuple = ( sebastian, m, 28) mytuple2 = ( motif, ATTCG, E44 ) mylist[0] 1 Accessing Elements sebastian mytuple[0] Modiying Elements mylist[1] = 5 mytuple[1] = 5 immutable! mylist += [3,2] Adding Elements mytuple += ( phd, biotec ) 6

7 Iterators Iterators work (almost) like lists Save 0me and memory with larger data Can only be used once (!) range(1000) xrange(1000) Completely constructed at the beginning Everything loaded into memory Available aber looping Elements served when needed Not filling the memory Not available aber looping 07_iterators 7

8 Working with Sequences 8

9 Lists A list is a list of variables nucleotides = ['a', 'c', 'g', 't'] print "Nucleotides: ", nucleotides Nucleotides: ['a', 'c', 'g', 't'] We can think of this as a list with 4 entries element 0 a c g t the list is the set of all four elements element 1 element 2 element 3 Note that the element indices start at zero. 9

10 List literals There are several, equally valid ways to assign an en0re array at once. This is the most common: a commaseparated list, delimited by squared brackets a = [1,2,3,4,5] print "a = ",a b = ['a','c','g','t'] print "b = ",b c = range(1,6) print "c = ",c d = "a c g t".split() print "d = ", d a = [1,2,3,4,5] b = ['a','c','g','t'] c = [1,2,3,4,5] d = ['a','c','g','t'] 10

11 Accessing lists To access list elements, use square brackets e.g. x[0] means "element zero of list x" x = ['a', 'c', 'g', 't'] i=2 print x[0], x[i], x[-1] a g t Remember, element indices start at zero! Nega0ve indices refer to elements coun0ng from the end e.g. x[-1] means "last element of list x" 11

12 List opera0ons You can sort and reverse lists... x = ['a', 't', 'g', 'c'] print "x =",x x.sort() print "x =",x x.reverse() print "x =",x You can add, delete and count elements x = ['a', 't', 'g', 'c'] x = ['a', 'c', 'g', 't'] x = ['t', 'g', 'c', 'a'] nums = [2,2,5,2,6] nums.append(8) print nums print nums.count(2) nums.remove(5) print nums [2,2,5,2,6,8] 3 [2,2,2,6,8] 12

13 More list opera0ons Mul0plying lists with * pop removes the last element of a list append adds an element to the end of a list concatena0ng lists with + or += Removing the first occurrence of an element Posi0on of an element >>> x=[1,0]*5 >>> x [1, 0, 1, 0, 1, 0, 1, 0, 1, 0] >>> while 0 in x: print x.pop(), >>> x [1] >>> x.append(2) >>> x [1, 2] >>> x+=x >>> x [1, 2, 1, 2] >>> x.remove(2) >>> x [1, 1, 2] >>> x.index(2) 2 13

14 Example: Reverse complemen0ng DNA A common opera0on due to double-helix symmetry of DNA Start by making string lower case again. This is generally good prac0ce Replace 'a' with 't', 'c' with 'g', 'g' with 'c' and 't' with 'a' Reverse the list def revcomp(dna): replaced=list(dna.lower(). replace("a","x").replace("t","a"). replace("x", "t").replace("g","x"). replace("c","g").replace("x", "c")) replaced.reverse() return "".join(replaced) print revcomp("accacgttaggtct ") agacctaacgtggt 14

15 for loop revisited Finding the total of a list of numbers: for statement loops through each entry in a list val = [4, 19, 1, 100, 125, 10] total = 0 for x in val: total += x print total 259 val = [4, 19, 1, 100, 125, 10] total = 0 for i in range(len(val)): total += val[i] print total 259 val = [4, 19, 1, 100, 125, 10] Print sum(val)

16 Taking a slice of a list The syntax x[i:j] returns a list containing elements i,i+1,,j-1 of list x nucleotides = ['a', g, 'c', 't'] purines = nucleotides[0:2] # nucleotides[:2] also works pyrimidines = nucleotides[2:4]# nucleotides[2:] also works # Another way: nucleotides[-2:], i.e. last two elements print "Nucleotides:", nucleotides print "Purines:", purines print "Pyrimidines:", pyrimidines Nucleotides: ['a', 'g', 'c', 't'] Purines: ['a', 'g'] Pyrimidines: ['c', 't'] 16

17 Lists and Strings A string can be converted into a list of strings and Using the split method: string.split(separator) A list of strings can be converted into one string Using the join method: separator.join(list) sentence = This is a complete sentence. print sentence.split() [ This, is, a, complete, sentence ] datarow = Apples,Bananas,Oranges Print datarow.split(, ) [ Apples, Bananas, Oranges ] cities = [ Dresden, Munich, Hamburg, Cologne ] print -->.join(cities) Dresden --> Munich --> Hamburg --> Cologne 17

18 List Comprehensions 18

19 What are list comprehensions? Easy way to construct sequences, especially lists Oben replaces a for loop and an if-construc0on Is used very oben in Python Syntax: [expr(var) for var in sequence if condi<on] Squares of all odd numbers between 1 and 10 [1,9,25,49,81] newlist = [] for x in range(1,11): if x % 2: newlist.append(x**2) Naïve construc<on of list newlist = [x**2 for x in range(1,11) if x % 2] Construc<on with list comprehension 19

20 Examples: List comprehensions sentence = I like MySQL but not Python print [(w.lower(), len(w)) for w in sentence.split()] [(i, 1), (like, 4), (mysql, 5), (but, 3), (not, 3), (python, 6)] generator = ((x-2)*3 for x in range(10)) Constructs a generator (iterator) with the sequence of numbers my_numbers = (1,0,-1,6,3,-2,3,4) my_sum = sum([x for x in my_numbers if x >0]) print my_sum Add up all posi<ve integers in my tuple 17 20

21 Lambda Func0ons 21

22 Lambda Func0ons Kind of anonymous func0ons Equivalent to normal func0ons Not bound to a name Different syntax def f(x): return (x-3)**2 f(5) f = lambda x: (x-3)**2 f(5) Normal func<on defini<on Lambda func<on

23 Map, filter, and reduce Lambda func0ons can be used anywhere where a func0on is expected Powerful in combina0on with map, filter, and reduce map filter reduce (lambda_function, sequence) Func0on applied to each element...of the given sequence Decides what to to with the result: map -> apply to each element, return modified list filter -> return list with element tested True reduce -> returns one element resulting from computation 23

24 Examples map(lambda x: x*3, [1,2,3]) [3,6,9] filter(lambda x: x>=1.0, [1.2,0.5,0.7,1.3]) [1.2,1.3] filter(lambda x: x!=0, map(lambda x: x-2, [4,2,5])) [2,3] reduce(lambda x,y: x+y if x<=2 else x*y, (1,2,3)) x y 1, 2 3 x y 3,

25 File IO 25

26 Opening, reading and wri0ng a file Returns file handler f = open( myfile.txt, r ) for line in f: if not line.startswith( # ): print line f.close() Loop variable File mode (r, w, a,...) Linewise itera<on over file! with open( myfile.txt, r ) as f: for line in f: if not line.startswith( # ): print line File is closed aber block! Shorter and bener form #Old number 1234 # New number 5555 # Test

27 Example: FASTA format A format for storing mul0ple named sequences This file contains 3' UTRs for Drosophila genes CG11604 CG11455 CG11488 Name of sequence is preceded by > symbol NB sequences can span mul0ple lines >CG11604 TAGTTATAGCGTGAGTTAGT TGTAAAGGAACGTGAAAGAT AAATACATTTTCAATACC >CG11455 TAGACGGAGACCCGTTTTTC TTGGTTAGTTTCACATTGTA AAACTGCAAATTGTGTAAAA ATAAAATGAGAAACAATTCT GGT >CG11488 TAGAAGTCAAAAAAGTCAAG TTTGTTATATAACAAGAAAT CAAAAATTATATAATTGTTT TTCACTCT fly3utr.txt 27

28 Example: FASTA format with open( fly3utr.txt, r ) as f: for line in f: if line.startswith( > ): print line What if we want to show the length of sequence for each record? >CG11604 >CG11455 >CG11488 >CG11604 TAGTTATAGCGTGAGTTAGT TGTAAAGGAACGTGAAAGAT AAATACATTTTCAATACC >CG11455 TAGACGGAGACCCGTTTTTC TTGGTTAGTTTCACATTGTA AAACTGCAAATTGTGTAAAA ATAAAATGAGAAACAATTCT GGT >CG11488 TAGAAGTCAAAAAAGTCAAG TTTGTTATATAACAAGAAAT CAAAAATTATATAATTGTTT TTCACTCT 28

29 Example: FASTA format >CG11604 TAGTTATAGCGTGAGTTAGT TGTAAAGGAACGTGAAAGAT AAATACATTTTCAATACC >CG11455 TAGACGGAGACCCGTTTTTC TTGGTTAGTTTCACATTGTA AAACTGCAAATTGTGTAAAA ATAAAATGAGAAACAATTCT GGT >CG11488 TAGAAGTCAAAAAAGTCAAG TTTGTTATATAACAAGAAAT CAAAAATTATATAATTGTTT TTCACTCT name = '' with open('fly3utr.txt', 'r') as f: for line in f: line = line.rstrip() if line.startswith('>'): if name: # Empty str is False print name, length name = line[1:] length = 0 else: length += len(line) print name, length CG CG CG _fasta 29

30 Summary Strings, lists, iterators, and tuples are all sequences Lists for storage of element of equal elements More flexible, more memory consump0on Tuples for storage of different elements Immutable, less memory consump0on Iterators for fast itera0on Least memory consump0on, can be only used once! Oben, a list comprehension can replace a for loop with an if-construc0on Convert strings into lists and vice versa with join and split Lambda func<on with map, filter, and reduce for efficient list processing File object provides line-wise itera0on 30

University of Texas at Arlington, TX, USA

University of Texas at Arlington, TX, USA Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,

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

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

University of Texas at Arlington, TX, USA

University of Texas at Arlington, TX, USA Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA The set of program statements over which a variable exists (i.e. can be referred to) It is about understanding, for any

More information

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want

More information

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

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

Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork Lecture 18: Lists II CS1068+ Introductory Programming in Python Dr Kieran T. Herley 2018/19 Department of Computer Science University College Cork Summary More on Python s lists. Sorting and reversing.

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

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

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

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Administrative Homework #5 is due today Homework #6 is out and DUE on MONDAY (3/5)

More information

LECTURE 3 Python Basics Part 2

LECTURE 3 Python Basics Part 2 LECTURE 3 Python Basics Part 2 FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for the use of a special kind of function, a lambda function.

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

Local defini1ons. Func1on mul1ples- of

Local defini1ons. Func1on mul1ples- of Local defini1ons The func1ons and special forms we ve seen so far can be arbitrarily nested except define and check- expect. So far, defini.ons have to be made at the top level, outside any expression.

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

(Func&onal (Programming (in (Scheme)))) Jianguo Lu

(Func&onal (Programming (in (Scheme)))) Jianguo Lu (Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you

More information

A tuple can be created as a comma-separated list of values:

A tuple can be created as a comma-separated list of values: Tuples A tuple is a sequence of values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable, and hence

More information

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH Introduction to Python Ph.D. Scien5fic Compu5ng Consultant PACE GATECH Things Covered What is Python? How to access Python environment? Fundamental elements in Python Variables (assignment, comparison,

More information

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions Outline 1 Guessing Secrets functions returning functions oracles and trapdoor functions 2 anonymous functions lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

More information

UNIT 4B Itera,on: Sor,ng. Sor,ng

UNIT 4B Itera,on: Sor,ng. Sor,ng UNIT 4B Itera,on: Sor,ng 1 Sor,ng 2 1 Inser,on Sort Outline def isort(datalist): result = [] for value in datalist: # insert value in its # proper place in result return result"! 3 insert func,on datalist.insert(position,

More information

Writing a Fraction Class

Writing a Fraction Class Writing a Fraction Class So far we have worked with floa0ng-point numbers but computers store binary values, so not all real numbers can be represented precisely In applica0ons where the precision of real

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

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

61A LECTURE 8 SEQUENCES, ITERABLES

61A LECTURE 8 SEQUENCES, ITERABLES 61A LECTURE 8 SEQUENCES, ITERABLES Steven Tang and Eric Tzeng July 8, 013 Announcements Homework 4 due tonight Homework 5 is out, due Friday Midterm is Thursday, 7pm Thanks for coming to the potluck! What

More information

61A LECTURE 8 SEQUENCES, ITERABLES. Steven Tang and Eric Tzeng July 8, 2013

61A LECTURE 8 SEQUENCES, ITERABLES. Steven Tang and Eric Tzeng July 8, 2013 61A LECTURE 8 SEQUENCES, ITERABLES Steven Tang and Eric Tzeng July 8, 2013 Announcements Homework 4 due tonight Homework 5 is out, due Friday Midterm is Thursday, 7pm Thanks for coming to the potluck!

More information

Python Programming: Lecture 2 Data Types

Python Programming: Lecture 2 Data Types Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)

More information

15110 Principles of Compu5ng, Carnegie Mellon University - CORTINA. Finding the maximum. Required: a non-empty list of integers.

15110 Principles of Compu5ng, Carnegie Mellon University - CORTINA. Finding the maximum. Required: a non-empty list of integers. UNIT 3C Using Loops and Condi5onals 1 Finding the maximum Required: a non-empty list of integers. 1. Set max equal to the first number in the list. 2. For each number n in the list: a. If n is greater

More information

OOP and Scripting in Python Advanced Features

OOP and Scripting in Python Advanced Features OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh

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

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 60 20 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E I SEMESTER GE85- Problem Solving and Python Programming Regulation 207 Academic

More information

Wrap up indefinite loops Text processing, manipula7on. Broader Issue: Self-driving cars. How do write indefinite loops in Python?

Wrap up indefinite loops Text processing, manipula7on. Broader Issue: Self-driving cars. How do write indefinite loops in Python? Objec7ves Wrap up indefinite loops Text processing, manipula7on Ø String opera7ons, processing, methods Broader Issue: Self-driving cars Feb 16, 2018 Sprenkle - CSCI111 1 Review How do write indefinite

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

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Numbers, lists and tuples. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Numbers, lists and tuples. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas Numbers, lists and tuples Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas Numbers Python defines various types of numbers: Integer (1234) Floating point number

More information

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt. Lecture 4 while and for loops if else test Tuples Functions Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.edu Launching Python > python Quick Reminder: while Loop Example >>>

More information

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ] Python Lists Chapter 8 Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution.0 License. http://creativecommons.org/licenses/by/.0/. Copyright 2010,

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 09 For Loops All materials copyright UMBC unless otherwise noted Last Class We Covered Lists and what they are used for Operations a list can perform Including

More information

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments Chapter 6: List What we will learn: List definition Syntax for creating lists Selecting elements of a list Selecting subsequence of a list What you need to know before: Data types Assignments List Sub-list

More information

DM502 Programming A. Peter Schneider-Kamp.

DM502 Programming A. Peter Schneider-Kamp. DM502 Programming A Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm502/! PROJECT PART 1 2 Organizational Details 2 possible projects, each consisting of 2 parts for 1 st part,

More information

Thinking Induc,vely. COS 326 David Walker Princeton University

Thinking Induc,vely. COS 326 David Walker Princeton University Thinking Induc,vely COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa,onal purposes Administra,on 2 Assignment

More information

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017 Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Spring 2017 Outline Functions State Functions as building blocks Higher order functions Map Reduce

More information

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1 Turn In Homework 2 Homework

More information

Spring INF Principles of Programming for Informatics. Manipulating Lists

Spring INF Principles of Programming for Informatics. Manipulating Lists Manipulating Lists Copyright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in the INF 510 class at the University of Southern California (USC) have explicit permission to make copies of

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

Common Loop Algorithms 9/21/16 42

Common Loop Algorithms 9/21/16 42 Common Loop Algorithms 9/21/16 42 Common Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match Is Found 4. Maximum and Minimum 5. Comparing Adjacent Values 9/21/16 43 Sum

More information

Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

More information

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala Functions, Scope & Arguments HORT 59000 Lecture 12 Instructor: Kranthi Varala Functions Functions are logical groupings of statements to achieve a task. For example, a function to calculate the average

More information

MEIN 50010: Python Data Structures

MEIN 50010: Python Data Structures : Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing

More information

Use JSL to Scrape Data from the Web and Predict Football Wins! William Baum Graduate Sta/s/cs Student University of New Hampshire

Use JSL to Scrape Data from the Web and Predict Football Wins! William Baum Graduate Sta/s/cs Student University of New Hampshire Use JSL to Scrape Data from the Web and Predict Football Wins! William Baum Graduate Sta/s/cs Student University of New Hampshire Just for Fun! I m an avid American football fan Sports sta/s/cs are easily

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

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

F21SC Industrial Programming: Functional Programming in Python

F21SC Industrial Programming: Functional Programming in Python F21SC Industrial Programming: Functional Programming in Python Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary software

More information

Chapter 2: Lists, Arrays and Dictionaries

Chapter 2: Lists, Arrays and Dictionaries Chapter 2: Lists, Arrays and Dictionaries 1. Higher order organization of data In the previous chapter, we have seen the concept of scalar variables that define memory space in which we store a scalar,

More information

Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

More information

CS1 Lecture 11 Feb. 9, 2018

CS1 Lecture 11 Feb. 9, 2018 CS1 Lecture 11 Feb. 9, 2018 HW3 due Monday morning, 9:00am for #1 I don t care if you use 1, 2, or 3 loops. Most important is clear correct code for #3, make sure all legal situations are handled. Think

More information

Program Verification (Rosen, Sections 5.5)

Program Verification (Rosen, Sections 5.5) Program Verification (Rosen, Sections 5.5) TOPICS Program Correctness Preconditions & Postconditions Program Verification Assignments Composition Conditionals Loops Proofs about Programs Why study logic?

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016 Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada Under Supervision of: Dr. Richard Kelley Chief Engineer, NAASIC March 6th, 2016 Science Technology Engineering

More information

Python Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다. PythonBasics

Python Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다.   PythonBasics Python Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다. http://ai.berkeley.edu/tutorial.html# PythonBasics Operators >>> 1 + 1 2 >>> 2 * 3 6 Boolean operators >>> 1==0 False >>> not (1==0) True >>> (2==2) and (2==3)

More information

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011 Python Lists Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 5, 2011 Stéphane Vialette (LIGM UPEMLV) Python Lists October 5, 2011 1 / 31 Outline 1 Introduction 2 Methods 3 Lists as

More information

Introduction to Functional Programming (Python) John R. Woodward

Introduction to Functional Programming (Python) John R. Woodward Introduction to Functional Programming (Python) John R. Woodward Functional Programming 1. Programming paradigm? Object oriented, imperative 2. Immutable state (referential transparency) 3. Higher order

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

CSc 120. Introduc/on to Computer Programing II. 01- b: Python review. Adapted from slides by Dr. Saumya Debray

CSc 120. Introduc/on to Computer Programing II. 01- b: Python review. Adapted from slides by Dr. Saumya Debray CSc 120 Introduc/on to Computer Programing II Adapted from slides by Dr. Saumya Debray 01- b: Python review Lists of Lists x = [ [1,2,3], [4], [5, 6]] x [[1, 2, 3], [4], [5, 6]] y = [ ['aa', 'bb', 'cc'],

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

Comp Exam 1 Overview.

Comp Exam 1 Overview. Comp 170-400 Exam 1 Overview. Resources During the Exam The exam will be closed book, no calculators or computers, except as a word processor. In particular no Python interpreter running in a browser or

More information

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc. CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

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

Document Databases: MongoDB

Document Databases: MongoDB NDBI040: Big Data Management and NoSQL Databases hp://www.ksi.mff.cuni.cz/~svoboda/courses/171-ndbi040/ Lecture 9 Document Databases: MongoDB Marn Svoboda svoboda@ksi.mff.cuni.cz 28. 11. 2017 Charles University

More information

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value. Data Structures Lists - stores a series of ordered mutable items Tuples - stores a series of ordered immutable items [not commonly used] Sets - stores a series of mutable or immutable(frozen) unsorted

More information

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013 CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

Array Basics: Outline

Array Basics: Outline Array Basics: Outline More Arrays (Savitch, Chapter 7) TOPICS Array Basics Arrays in Classes and Methods Programming with Arrays Searching and Sorting Arrays Multi-Dimensional Arrays Static Variables and

More information

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1 Lecture #12: Immutable and Mutable Data Last modified: Mon Feb 22 16:33:22 2016 CS61A: Lecture #12 1 Listing Leaves def leaf_labels(tree): """A list of the labels of all leaves in TREE.""" Last modified:

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

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

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G. Haskell: Lists CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

More information

MITOCW watch?v=rvrkt-jxvko

MITOCW watch?v=rvrkt-jxvko MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

Unit 14. Passing Arrays & C++ Strings

Unit 14. Passing Arrays & C++ Strings 1 Unit 14 Passing Arrays & C++ Strings PASSING ARRAYS 2 3 Passing Arrays As Arguments Can we pass an array to another function? YES!! Syntax: Step 1: In the prototype/signature: Put empty square brackets

More information

CS251 Programming Languages Spring 2016, Lyn Turbak Department of Computer Science Wellesley College

CS251 Programming Languages Spring 2016, Lyn Turbak Department of Computer Science Wellesley College Functions in Racket CS251 Programming Languages Spring 2016, Lyn Turbak Department of Computer Science Wellesley College Racket Func+ons Functions: most important building block in Racket (and 251) Functions/procedures/methods/subroutines

More information

List comprehensions (and other shortcuts) UW CSE 160 Spring 2015

List comprehensions (and other shortcuts) UW CSE 160 Spring 2015 List comprehensions (and other shortcuts) UW CSE 160 Spring 2015 Three Ways to Define a List Explicitly write out the whole thing: squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Write a loop to create

More information

MACRO NOTES DOCUMENTATION

MACRO NOTES DOCUMENTATION MACRO NOTES DOCUMENTATION 1 The NIH Image manual, appendix A provides a descrip;on of the macro language and menu by menu explana;on of the commands 2 Reference card - this comes as a macro/text file with

More information

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013 CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

Artificial Intelligence Lecture 1

Artificial Intelligence Lecture 1 Artificial Intelligence Lecture 1 istrative Matters Webpage: www.aass.oru.se/~mbl/ai Examiner: Mathias Broxvall Assistant: Lia Susana d.c. Silva Lopez Schedule 20 hours/week on this course. 4 hours lectures,

More information

Python Lists and for Loops. Learning Outcomes. What s a List 9/19/2012

Python Lists and for Loops. Learning Outcomes. What s a List 9/19/2012 Python Lists and for Loops CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Learning Outcomes Be aware that multiple items can be stored in a list. Become

More information

Python Programming Exercises 3

Python Programming Exercises 3 Python Programming Exercises 3 Notes: These exercises assume that you are comfortable with the contents of the two previous sets of exercises including variables, types, arithmetic expressions, logical

More information

Array Basics: Outline

Array Basics: Outline Array Basics: Outline More Arrays (Savitch, Chapter 7) TOPICS Array Basics Arrays in Classes and Methods Programming with Arrays Searching and Sorting Arrays Multi-Dimensional Arrays Static Variables and

More information

Proofs about Programs

Proofs about Programs Proofs about Programs Program Verification (Rosen, Sections 5.5) TOPICS Program Correctness Preconditions & Postconditions Program Verification Assignment Statements Conditional Statements Loops Composition

More information

15110 Principles of Computing, Carnegie Mellon University - CORTINA. Binary Search. Required: List L of n unique elements.

15110 Principles of Computing, Carnegie Mellon University - CORTINA. Binary Search. Required: List L of n unique elements. UNIT 5B Binary Search 1 Binary Search Required: List L of n unique elements. The elements must be sorted in increasing order. Result: The index of a specific element (called the key) or None if the key

More information

CS1 Lecture 12 Feb. 11, 2019

CS1 Lecture 12 Feb. 11, 2019 CS1 Lecture 12 Feb. 11, 2019 HW4 available tomorrow, due next Wed. Discussion sections this week will be closely tied to one of the homework problems. Exam 1, Thursday evening, 2/21, 6:30-8:00pm HW2 scores

More information

List Processing Patterns and List Comprehension

List Processing Patterns and List Comprehension List Processing Patterns and List Comprehension Review: Lists Summary of what we know about lists. A list is a sequence type (like strings and tuples), but that differently from them is mutable (it can

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

An Introduction to Python

An Introduction to Python An Introduction to Python Day 3 Renaud Dessalles dessalles@ucla.edu Writing Modules Combining what we ve learnt Yesterday we learnt a lot of different bits of Python. Let s summarize that knowledge by

More information

Table of Contents. Preface... xxi

Table of Contents. Preface... xxi Table of Contents Preface... xxi Chapter 1: Introduction to Python... 1 Python... 2 Features of Python... 3 Execution of a Python Program... 7 Viewing the Byte Code... 9 Flavors of Python... 10 Python

More information

Python Lists, Tuples, Dictionaries, and Loops

Python Lists, Tuples, Dictionaries, and Loops Python Lists, Tuples, Dictionaries, and Loops What you need to Know For this lecture you need to know: 1. How to write and run basic python programs 2. How to create and assign data to variables 3. How

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