SlideShare una empresa de Scribd logo
1 de 14
Page 1


6.189 – Notes/Homework
Session 6

Administrivia
Name:



Instructions:
1. Err..complete the questions :). Putting a serious effort into this homework is mandatory for receiving
a passing grade in this course (note the word effort – getting them all wrong is ok, but skipping this
homework is not.)
2. These notes (and homework problems) are a continuation of the notes from Exam 1.
3. Some problems may be marked {alone} (it’ll be in red and braces.) Work on those problems alone!
4. When we ask for output, you DON'T have to write the spaces/newlines in.
    Program Text:

      print “X”,
      print “X”,


    Output:



                                                   XX
Day 4: List Basics
Notes:
This section covers the basics of lists. We'll cover them in more detail after we cover objects and
references.

We've used variables to store basic information such as numbers, strings, and boolean values. We can
also store more complex information. A list stores a sequence of elements [x1,x2,x3,...]. Note that
order matters: [x1,x2] != [x2,x1]

You can store different types of variables in the same list: [1,3,"test",True]. You can even store
lists in lists! (Note: For now, don't store lists in lists! You'll understand why when we talk about objects
and mutability.)

Chapters 9.1-9.3 cover basic syntax on using lists. Here’s a quick review:

  - You can create a list using square brackets [1,2,5,1,3,"test"].
  - To read an element from list some_list, use some_list[index]. The index of an element is just
    its position, but note that the first element is considered to have a position of 0!
Page 2


  - The built-in function len(x) will find the length of any list passed in as a parameter. This works
    more generally with any complex data structure (like dictionaries, which we'll cover later) as well as
    strings.

We'll also be using the following syntax for adding something to the end of a list.

    Program Text:

      some_list = [1,2,3,4]
      some_list.append(5)
      print some_list

    Output:

      [1,2,3,4,5]


For now, just memorize the syntax -- you'll understand what's going on in a later section.

Problem 12 {alone}:
What is the output of the following code. The output of each program has at most two semi-colons.

    Program Text:

      some_list = [3,6,2,5]
      i = 1
      while i < 3:
        print some_list[i], ";"
        i = i + 1
      print some_list[3]

    Output:




    Program Text:

      list1 = [2,5,6,3,7,8,12]
      list2 = [1,2,6,5,7,3,12]
      i = 0
      while i < 6:
        if list1[i] == list2[i]:
          print list1[i], ";",
        i = i + 1
      print len(list1)

    Output:
Page 3


Day 6: Objects and References
Notes:
Lists are fundamentally different than everything we've seen to date. They are the first example we've
seen of an object.

You've learned that we can use variables to store information in a table. This works for simple things like
numbers, but not for complex information like a list. Instead, Python stores this information in an area
of memory called the heap.

Understanding what the heap is isn't important. What is important to know, however, is that instead of
storing objects in the variable table, Python stores a pointer or reference to the object.

A reference is like an arrow. The easiest way to explain this is with an example:

    Program Text:

      example_list = []

      def append_one(my_list):
        "This is a function that adds something to the end of a list"
        #Point 2
        my_list.append(1)
        #Point 3

      #Point 1
      append_one(example_list)
      print example_list
      #Point 4

    Output:

      [1]


At point 1, the variable table looks something like the following.




After this, we pass the location of the list (which is the value stored in the variable) to the function. Thus,
at point 2 both variables point to the same thing.
Page 4




We change the list afterwards, and the table looks like the following at point 3.




The local variable disappears when the function ends, and at point 4 the variable table looks like the
following.




Hence the output of the code is [1]! This differs from problem 10 – since these variables are storing
arrows, any changes we make within the function are reflected outside of it too.

This arrow is literally stored as an integer in the table – think of it as a locker number. We can find out
the value of this number using the id(x) function.
Page 5


    Program Text:

      def small_function(my_list):
        print "in function:"
        print id(my_list)
        my_list.append(1)

      example_list = []
      example2_list = [3,6]
      print id(example_list)
      print id(example2_list)

      small_function(example_list)

    Output:

      18162752
      12860152
      in function:
      18162752


Note: Your numbers may differ from mine. The first and last numbers will still be the same, though.

You probably won't need to use the id function ever. Its really useful for figuring out whether two
variables are pointing to the same list or not, though.

Problem 13:
What is the output of the following code. Use single digits for the output of id(x).

    Program Text:

      some_list = [1,3,2]

      def f1(my_list):
        new_list = [2]
        print id(my_list), "; ",
        print id(new_list), ";",

      print id(some_list), "; ",
      f1(some_list)

    Output:
Page 6


    Program Text:

      some_list = [1,3,2]

      def f1(my_list)
        my_list.append(7)
        print id(my_list), “;”,
        return [1,4,5]

      print id(some_list), “;”,
      some_list.append(5)
      print id(some_list), “;”,
      some_list = [4,3,7]
      print id(some_list), “;”,
      some_list = f1(some_list)
      print id(some_list)

    Output:




Day 6: Mutability
Notes:
Now that you understand the true nature of a list, we can talk about the concept of mutability. Lists are
an example of a mutable object. Mutability is a synonym for changable – in essence, we're saying that
you can change a list. Be careful -- while this sounds very simple, it can get quite tricky.

For the next problem, the references example will help a lot. Remember that statements like list1 =
[1,2,5] change the reference (what the arrow is pointing to) and statements like list1.append(5)
change the list itself.

Problem 14:
What is the output of the following code.

    Program Text:

      list1 = [1,2,4]
      list2 = list1
      list2.append(3)
      print list1

    Output:
Page 7


Program Text:

  list1 = [1,2,4]
  list2 = [1,2,4]
  list2.append(3)
  print list1

Output:




Program Text:

  example_list = [1,2,4]

  def f1(my_list):
    my_list.append(3)

  f1(example_list)
  print example_list

Output:




Program Text:

  example_list = [1,2,4]

  def f1(my_list):
    my_list = [1,2,4,3]

  f1(example_list)
  print example_list

Output:
Page 8


    Program Text:

      list1 = [1,2,4]
      list2 = [1,2,4]
      list3 = list2
      list2.append(3)
      list2 = list1
      list2.append(3)
      list1.append(3)
      list1 = list3
      print list1, ";",
      print list3

    Output:




We’ll talk about immutable objects later when we cover tuples and revisit strings.

Day 6: Member functions
Notes:
We saw at the append function earlier – this function had some unusual syntax. Objects have something
called member functions. append is a member function of a list.

In essence, member functions are basically shorthand. Python could easily have made a general
append(some_list, element) function that appends the value of element to the list some_list.
Instead, we use the member function of some_list: we write some_list.append(element) to
append an element to some_list.

In general, member functions have the syntax object_name.function(parameters) – the function
affects or applies to the object object_name.

Day 4: Lists Redux
Notes:
Now let's go over lists for real. Remember what you've just learned about them.

  - Lists are mutable objects. When you change a list somewhere, every other reference will still point
    to the now changed list.
  - Lists have member functions. For lists, these functions tend to change the list itself.

Basics: You already know how to create a list and read its members. You can also use the
example_list[i] syntax to change values, e.g. example_list[1] = 5. Finally, you can write del
example_list[i] to delete the element at position i.

Length: As mentioned earlier, you can use the built-in function len(x) to find the length of a list.
Page 9


Membership: The in operator can be used to determine whether an element is a member of a list or
not. 3 in [3,5,7] evaluates to True, while 6 in [3,4,1] evaluates to false.

Analogous to !=, you can use not in to check if an element is NOT a member of a list. 12 not in
[3,5,7] returns True.

Warning: Never use booleans for this operator unless the list consists ONLY of booleans. Recall that the
== operator can compare different types; Python considers 0 == False and any other number equal to
True. Hence, True in [0,3,5] evaluates to True because 3 == True is considered True by Python.

Member functions: All of the following functions change the list they're called from. They have NO
return values.

  -   append(element). Appends element to the end of the list.
  -   insert(index, element). Inserts element before the list element at index.
  -   reverse(). Reverses the order of elements in the list.
  -   remove(element). Removes the first instance of element from the list.

The following function(s) don’t change the list. They return information about the list instead.

  - index(element). Returns the position of the first instance of element in the list.
  - count(element). Returns the number of times element appears in the list.

Don’t worry too much about memorizing all these functions. Just keep in mind that they exist.

Concatenation: You can combine two lists into a new list with the concatenation operator +.

Problem 15:
Write a definition for the following shift functions. shift takes a list and moves the first element to the
very end. reverse_shift does the opposite – it moves the last element to the beginning of the list.
Neither function should return anything!

      Program Text:

        def shift(my_list):
           "Shifts the list [x1,x2,...,xn] to [x2,x3,...,xn,x1]."
Page 10



    Program Text:

      def reverse_shift(my_list):
         "Shifts the list [x1,x2,...,xn] to [xn,x1,x2,...,x(n-1)]."




Problem 16:
Write a definition for the function last_index. last_index takes a list and an element and returns
the position of the last instance of element in list, e.g. last_index([3,4,3,7,9],3) returns 2. Be
sure that list is in its original form when your function completes! (either create your own copy of the
list or reverse any changes you make.)

    Program Text:

      def last_index(my_list, element):
         "Returns the position of the last instance of element in my_list"




Day 4: Advanced Positioning and Slicing
Notes:
You've already learned about the notation for selecting an element some_list[i] by using its
position. You can also use negative numbers to select an element – the last element is considered to
have position -1.
Page 11


You can do even slicker things. some_list[start:end] creates a list slice – it returns a new list with
all the elements between start and end – 1 from the original list. If you omit either start or end,
it’ll select all elements from the beginning / up until the end, e.g. some_list[1:] creates a slice
including all but the first element.

You can change the values of slices the same way you change individual values, e.g. some_list[3:5]
= [1,5,4,4,7]. Note that the new assignment doesn’t have to be the same length as the list slice you
cut out.

Note, however, that if you assign the slice to a variable, that variable points to a new list.

    Program Text:

      list1 = [1,3,5,7]
      list1[1:3] = [2,4,6]
      print list1
      list2 = list1[1:] #list2 points to a new list
      list2.append(55)
      print list1
      print len(list1)
      list1[3:5] = [8,8,8,8]
      print list1

    Output:

      [1, 2, 4, 6, 7]
      [1, 2, 4, 6, 7]
      5
      [1, 2, 4, 8, 8, 8, 8]


some_list[:] creates a duplicate of the list. This is very useful – since most of our list techniques
destructively change the list, many times, it may be a good idea to create a duplicate of the list and mess
around with that instead.

Problem 17:
What is the output of the following code.

    Program Text:

      list1 = [4,6,12]
      list2 = list1[:]
      list1.append(4)
      print list2

    Output:
Page 12


   Program Text:

     list1 = [2,5,6,3]
     i = 1
     while i < len(list1):
       print list1[-i], ";",
       i = i + 1
     print list1[-len(list1)]

   Output:




   Program Text:

     list1 = [1,2,3]
     i = 1
     while i < len(list1):
       print list1[:i], ";",
       i = i + 1
     print list1

   Output:




Day 4: Range function
Notes:
range(x) is a built-in function that returns a list [0,1,...,x-1], e.g. range(3) returns [0,1,2].
You can also do range(start, finish), which creates the list [start, start+1, ...,
finish-1]. Its a very useful function.

Day 4: For loop
Notes:
Like the while loop, the for loop is another control flow command – a way of executing a sequence of
statements multiple times. A for loop executes a sequence of statements once for each element in a
list.

   Program Text:

     for i in [1,2,4,6]:
       print i, ";",
     print 8

   Output:

     1;2;4;6;8
Page 13


The for loop is incredibly useful. For example, you can combine the for loop and range(x) function
to execute a statement a fixed number of times.

Problem 18:
Write a definition for a function that takes a list and returns the sum of all elements in that list.

    Program Text:

      def sum_elements(my_list):
         "Returns the sum of all elements in my_list"




Day 4: Basic Advanced Loops
Notes:
This title is not a contradiction :p. For loops can be incredibly difficult to use correctly. This section will
give you a bunch of problems to give you practice in solving problems with for loops.

Problem 19:
Each of the following function definitions takes a list as a parameter and solves a specific problem.
Correctly fill the blanks in the following code to solve the problems.

There is a way to solve each problem by only filling in the blanks. Don’t just add extra lines to force a
solution. Also, there may even be more elegant solutions that don’t use all the blanks – feel free to use
those too.

    Program Text:

      def all_under_6(my_list):
        """Returns True if ALL members in my_list are under 6 (False
      otherwise). my_list must be list of integers."""
         under_6 = ___________
         for i in my_list:
             if __________________:
                _________________________________________________________
         return under_6
Page 14


Program Text:

  def no_vowels(my_list):
    """Returns True if my_list contains only consonants (no vowels).
  Assume that my_list only contains lowercase letters."""
     vowels = ['a','e','i','o','u']
     contains_vowels = _________
     for i in __________________:
         if ______________________:
            ____________________________________________________________
     return not contains_vowels

Program Text:

  def find_max_element(my_list):
    """Finds and returns the maximum value contained in my_list.
  Assume my_list contains positive values only."""
     max_value = -1
     for i in __________________:
         if ______________________:
            ____________________________________________________________
     return max_value

Más contenido relacionado

La actualidad más candente (19)

Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python list
Python listPython list
Python list
 
Lists
ListsLists
Lists
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
List in Python
List in PythonList in Python
List in Python
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python data type
Python data typePython data type
Python data type
 
1. python
1. python1. python
1. python
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 

Destacado (7)

Does Your Festival or Event MakeCcent$
Does Your Festival or Event MakeCcent$Does Your Festival or Event MakeCcent$
Does Your Festival or Event MakeCcent$
 
Everywhere Ergonomics
Everywhere ErgonomicsEverywhere Ergonomics
Everywhere Ergonomics
 
Text book
Text bookText book
Text book
 
Talon Financial
Talon FinancialTalon Financial
Talon Financial
 
finalproject
finalprojectfinalproject
finalproject
 
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
 
Student kap hiv aids
Student kap hiv aidsStudent kap hiv aids
Student kap hiv aids
 

Similar a pyton Notes6

The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189Mahmoud Samir Fayed
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4Syed Farjad Zia Zaidi
 
Although people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxAlthough people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxmilissaccm
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181Mahmoud Samir Fayed
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data CollectionJoseTanJr
 
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docxAssg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docxfestockton
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And AnswersH2Kinfosys
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxCatherineVania1
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 
The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88Mahmoud Samir Fayed
 

Similar a pyton Notes6 (20)

The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4
 
Although people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxAlthough people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docx
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data Collection
 
Python Objects
Python ObjectsPython Objects
Python Objects
 
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docxAssg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 
pyton Notes9
pyton Notes9pyton Notes9
pyton Notes9
 
Python lists
Python listsPython lists
Python lists
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Python advance
Python advancePython advance
Python advance
 
Data structure
 Data structure Data structure
Data structure
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Lecture 09.pptx
Lecture 09.pptxLecture 09.pptx
Lecture 09.pptx
 
The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88
 

Más de Amba Research

Más de Amba Research (20)

Case Econ08 Ppt 16
Case Econ08 Ppt 16Case Econ08 Ppt 16
Case Econ08 Ppt 16
 
Case Econ08 Ppt 08
Case Econ08 Ppt 08Case Econ08 Ppt 08
Case Econ08 Ppt 08
 
Case Econ08 Ppt 11
Case Econ08 Ppt 11Case Econ08 Ppt 11
Case Econ08 Ppt 11
 
Case Econ08 Ppt 14
Case Econ08 Ppt 14Case Econ08 Ppt 14
Case Econ08 Ppt 14
 
Case Econ08 Ppt 12
Case Econ08 Ppt 12Case Econ08 Ppt 12
Case Econ08 Ppt 12
 
Case Econ08 Ppt 10
Case Econ08 Ppt 10Case Econ08 Ppt 10
Case Econ08 Ppt 10
 
Case Econ08 Ppt 15
Case Econ08 Ppt 15Case Econ08 Ppt 15
Case Econ08 Ppt 15
 
Case Econ08 Ppt 13
Case Econ08 Ppt 13Case Econ08 Ppt 13
Case Econ08 Ppt 13
 
Case Econ08 Ppt 07
Case Econ08 Ppt 07Case Econ08 Ppt 07
Case Econ08 Ppt 07
 
Case Econ08 Ppt 06
Case Econ08 Ppt 06Case Econ08 Ppt 06
Case Econ08 Ppt 06
 
Case Econ08 Ppt 05
Case Econ08 Ppt 05Case Econ08 Ppt 05
Case Econ08 Ppt 05
 
Case Econ08 Ppt 04
Case Econ08 Ppt 04Case Econ08 Ppt 04
Case Econ08 Ppt 04
 
Case Econ08 Ppt 03
Case Econ08 Ppt 03Case Econ08 Ppt 03
Case Econ08 Ppt 03
 
Case Econ08 Ppt 02
Case Econ08 Ppt 02Case Econ08 Ppt 02
Case Econ08 Ppt 02
 
Case Econ08 Ppt 01
Case Econ08 Ppt 01Case Econ08 Ppt 01
Case Econ08 Ppt 01
 
Notes8
Notes8Notes8
Notes8
 
Notes7
Notes7Notes7
Notes7
 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 
pyton Exam1 soln
 pyton Exam1 soln pyton Exam1 soln
pyton Exam1 soln
 
learn matlab for ease Lec5
learn matlab for ease Lec5learn matlab for ease Lec5
learn matlab for ease Lec5
 

Último

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 

pyton Notes6

  • 1. Page 1 6.189 – Notes/Homework Session 6 Administrivia Name: Instructions: 1. Err..complete the questions :). Putting a serious effort into this homework is mandatory for receiving a passing grade in this course (note the word effort – getting them all wrong is ok, but skipping this homework is not.) 2. These notes (and homework problems) are a continuation of the notes from Exam 1. 3. Some problems may be marked {alone} (it’ll be in red and braces.) Work on those problems alone! 4. When we ask for output, you DON'T have to write the spaces/newlines in. Program Text: print “X”, print “X”, Output: XX Day 4: List Basics Notes: This section covers the basics of lists. We'll cover them in more detail after we cover objects and references. We've used variables to store basic information such as numbers, strings, and boolean values. We can also store more complex information. A list stores a sequence of elements [x1,x2,x3,...]. Note that order matters: [x1,x2] != [x2,x1] You can store different types of variables in the same list: [1,3,"test",True]. You can even store lists in lists! (Note: For now, don't store lists in lists! You'll understand why when we talk about objects and mutability.) Chapters 9.1-9.3 cover basic syntax on using lists. Here’s a quick review: - You can create a list using square brackets [1,2,5,1,3,"test"]. - To read an element from list some_list, use some_list[index]. The index of an element is just its position, but note that the first element is considered to have a position of 0!
  • 2. Page 2 - The built-in function len(x) will find the length of any list passed in as a parameter. This works more generally with any complex data structure (like dictionaries, which we'll cover later) as well as strings. We'll also be using the following syntax for adding something to the end of a list. Program Text: some_list = [1,2,3,4] some_list.append(5) print some_list Output: [1,2,3,4,5] For now, just memorize the syntax -- you'll understand what's going on in a later section. Problem 12 {alone}: What is the output of the following code. The output of each program has at most two semi-colons. Program Text: some_list = [3,6,2,5] i = 1 while i < 3: print some_list[i], ";" i = i + 1 print some_list[3] Output: Program Text: list1 = [2,5,6,3,7,8,12] list2 = [1,2,6,5,7,3,12] i = 0 while i < 6: if list1[i] == list2[i]: print list1[i], ";", i = i + 1 print len(list1) Output:
  • 3. Page 3 Day 6: Objects and References Notes: Lists are fundamentally different than everything we've seen to date. They are the first example we've seen of an object. You've learned that we can use variables to store information in a table. This works for simple things like numbers, but not for complex information like a list. Instead, Python stores this information in an area of memory called the heap. Understanding what the heap is isn't important. What is important to know, however, is that instead of storing objects in the variable table, Python stores a pointer or reference to the object. A reference is like an arrow. The easiest way to explain this is with an example: Program Text: example_list = [] def append_one(my_list): "This is a function that adds something to the end of a list" #Point 2 my_list.append(1) #Point 3 #Point 1 append_one(example_list) print example_list #Point 4 Output: [1] At point 1, the variable table looks something like the following. After this, we pass the location of the list (which is the value stored in the variable) to the function. Thus, at point 2 both variables point to the same thing.
  • 4. Page 4 We change the list afterwards, and the table looks like the following at point 3. The local variable disappears when the function ends, and at point 4 the variable table looks like the following. Hence the output of the code is [1]! This differs from problem 10 – since these variables are storing arrows, any changes we make within the function are reflected outside of it too. This arrow is literally stored as an integer in the table – think of it as a locker number. We can find out the value of this number using the id(x) function.
  • 5. Page 5 Program Text: def small_function(my_list): print "in function:" print id(my_list) my_list.append(1) example_list = [] example2_list = [3,6] print id(example_list) print id(example2_list) small_function(example_list) Output: 18162752 12860152 in function: 18162752 Note: Your numbers may differ from mine. The first and last numbers will still be the same, though. You probably won't need to use the id function ever. Its really useful for figuring out whether two variables are pointing to the same list or not, though. Problem 13: What is the output of the following code. Use single digits for the output of id(x). Program Text: some_list = [1,3,2] def f1(my_list): new_list = [2] print id(my_list), "; ", print id(new_list), ";", print id(some_list), "; ", f1(some_list) Output:
  • 6. Page 6 Program Text: some_list = [1,3,2] def f1(my_list) my_list.append(7) print id(my_list), “;”, return [1,4,5] print id(some_list), “;”, some_list.append(5) print id(some_list), “;”, some_list = [4,3,7] print id(some_list), “;”, some_list = f1(some_list) print id(some_list) Output: Day 6: Mutability Notes: Now that you understand the true nature of a list, we can talk about the concept of mutability. Lists are an example of a mutable object. Mutability is a synonym for changable – in essence, we're saying that you can change a list. Be careful -- while this sounds very simple, it can get quite tricky. For the next problem, the references example will help a lot. Remember that statements like list1 = [1,2,5] change the reference (what the arrow is pointing to) and statements like list1.append(5) change the list itself. Problem 14: What is the output of the following code. Program Text: list1 = [1,2,4] list2 = list1 list2.append(3) print list1 Output:
  • 7. Page 7 Program Text: list1 = [1,2,4] list2 = [1,2,4] list2.append(3) print list1 Output: Program Text: example_list = [1,2,4] def f1(my_list): my_list.append(3) f1(example_list) print example_list Output: Program Text: example_list = [1,2,4] def f1(my_list): my_list = [1,2,4,3] f1(example_list) print example_list Output:
  • 8. Page 8 Program Text: list1 = [1,2,4] list2 = [1,2,4] list3 = list2 list2.append(3) list2 = list1 list2.append(3) list1.append(3) list1 = list3 print list1, ";", print list3 Output: We’ll talk about immutable objects later when we cover tuples and revisit strings. Day 6: Member functions Notes: We saw at the append function earlier – this function had some unusual syntax. Objects have something called member functions. append is a member function of a list. In essence, member functions are basically shorthand. Python could easily have made a general append(some_list, element) function that appends the value of element to the list some_list. Instead, we use the member function of some_list: we write some_list.append(element) to append an element to some_list. In general, member functions have the syntax object_name.function(parameters) – the function affects or applies to the object object_name. Day 4: Lists Redux Notes: Now let's go over lists for real. Remember what you've just learned about them. - Lists are mutable objects. When you change a list somewhere, every other reference will still point to the now changed list. - Lists have member functions. For lists, these functions tend to change the list itself. Basics: You already know how to create a list and read its members. You can also use the example_list[i] syntax to change values, e.g. example_list[1] = 5. Finally, you can write del example_list[i] to delete the element at position i. Length: As mentioned earlier, you can use the built-in function len(x) to find the length of a list.
  • 9. Page 9 Membership: The in operator can be used to determine whether an element is a member of a list or not. 3 in [3,5,7] evaluates to True, while 6 in [3,4,1] evaluates to false. Analogous to !=, you can use not in to check if an element is NOT a member of a list. 12 not in [3,5,7] returns True. Warning: Never use booleans for this operator unless the list consists ONLY of booleans. Recall that the == operator can compare different types; Python considers 0 == False and any other number equal to True. Hence, True in [0,3,5] evaluates to True because 3 == True is considered True by Python. Member functions: All of the following functions change the list they're called from. They have NO return values. - append(element). Appends element to the end of the list. - insert(index, element). Inserts element before the list element at index. - reverse(). Reverses the order of elements in the list. - remove(element). Removes the first instance of element from the list. The following function(s) don’t change the list. They return information about the list instead. - index(element). Returns the position of the first instance of element in the list. - count(element). Returns the number of times element appears in the list. Don’t worry too much about memorizing all these functions. Just keep in mind that they exist. Concatenation: You can combine two lists into a new list with the concatenation operator +. Problem 15: Write a definition for the following shift functions. shift takes a list and moves the first element to the very end. reverse_shift does the opposite – it moves the last element to the beginning of the list. Neither function should return anything! Program Text: def shift(my_list): "Shifts the list [x1,x2,...,xn] to [x2,x3,...,xn,x1]."
  • 10. Page 10 Program Text: def reverse_shift(my_list): "Shifts the list [x1,x2,...,xn] to [xn,x1,x2,...,x(n-1)]." Problem 16: Write a definition for the function last_index. last_index takes a list and an element and returns the position of the last instance of element in list, e.g. last_index([3,4,3,7,9],3) returns 2. Be sure that list is in its original form when your function completes! (either create your own copy of the list or reverse any changes you make.) Program Text: def last_index(my_list, element): "Returns the position of the last instance of element in my_list" Day 4: Advanced Positioning and Slicing Notes: You've already learned about the notation for selecting an element some_list[i] by using its position. You can also use negative numbers to select an element – the last element is considered to have position -1.
  • 11. Page 11 You can do even slicker things. some_list[start:end] creates a list slice – it returns a new list with all the elements between start and end – 1 from the original list. If you omit either start or end, it’ll select all elements from the beginning / up until the end, e.g. some_list[1:] creates a slice including all but the first element. You can change the values of slices the same way you change individual values, e.g. some_list[3:5] = [1,5,4,4,7]. Note that the new assignment doesn’t have to be the same length as the list slice you cut out. Note, however, that if you assign the slice to a variable, that variable points to a new list. Program Text: list1 = [1,3,5,7] list1[1:3] = [2,4,6] print list1 list2 = list1[1:] #list2 points to a new list list2.append(55) print list1 print len(list1) list1[3:5] = [8,8,8,8] print list1 Output: [1, 2, 4, 6, 7] [1, 2, 4, 6, 7] 5 [1, 2, 4, 8, 8, 8, 8] some_list[:] creates a duplicate of the list. This is very useful – since most of our list techniques destructively change the list, many times, it may be a good idea to create a duplicate of the list and mess around with that instead. Problem 17: What is the output of the following code. Program Text: list1 = [4,6,12] list2 = list1[:] list1.append(4) print list2 Output:
  • 12. Page 12 Program Text: list1 = [2,5,6,3] i = 1 while i < len(list1): print list1[-i], ";", i = i + 1 print list1[-len(list1)] Output: Program Text: list1 = [1,2,3] i = 1 while i < len(list1): print list1[:i], ";", i = i + 1 print list1 Output: Day 4: Range function Notes: range(x) is a built-in function that returns a list [0,1,...,x-1], e.g. range(3) returns [0,1,2]. You can also do range(start, finish), which creates the list [start, start+1, ..., finish-1]. Its a very useful function. Day 4: For loop Notes: Like the while loop, the for loop is another control flow command – a way of executing a sequence of statements multiple times. A for loop executes a sequence of statements once for each element in a list. Program Text: for i in [1,2,4,6]: print i, ";", print 8 Output: 1;2;4;6;8
  • 13. Page 13 The for loop is incredibly useful. For example, you can combine the for loop and range(x) function to execute a statement a fixed number of times. Problem 18: Write a definition for a function that takes a list and returns the sum of all elements in that list. Program Text: def sum_elements(my_list): "Returns the sum of all elements in my_list" Day 4: Basic Advanced Loops Notes: This title is not a contradiction :p. For loops can be incredibly difficult to use correctly. This section will give you a bunch of problems to give you practice in solving problems with for loops. Problem 19: Each of the following function definitions takes a list as a parameter and solves a specific problem. Correctly fill the blanks in the following code to solve the problems. There is a way to solve each problem by only filling in the blanks. Don’t just add extra lines to force a solution. Also, there may even be more elegant solutions that don’t use all the blanks – feel free to use those too. Program Text: def all_under_6(my_list): """Returns True if ALL members in my_list are under 6 (False otherwise). my_list must be list of integers.""" under_6 = ___________ for i in my_list: if __________________: _________________________________________________________ return under_6
  • 14. Page 14 Program Text: def no_vowels(my_list): """Returns True if my_list contains only consonants (no vowels). Assume that my_list only contains lowercase letters.""" vowels = ['a','e','i','o','u'] contains_vowels = _________ for i in __________________: if ______________________: ____________________________________________________________ return not contains_vowels Program Text: def find_max_element(my_list): """Finds and returns the maximum value contained in my_list. Assume my_list contains positive values only.""" max_value = -1 for i in __________________: if ______________________: ____________________________________________________________ return max_value