SlideShare une entreprise Scribd logo
1  sur  5
Page 1



6.189 Worksheet
Session 9

Administrivia
Name:



Instructions:
1. Err..complete the questions :).
2. No calculators, no laptops, etc.
3. When we ask for output, you DON'T have to write the spaces/newlines in.
   Program Text:

     print “X”,

     print “X”,



   Output:



                                               XX

Problem 1: Common Errors
Each of the following code snippets represents a common error made by an introductory programming

student (I know this because I ripped these errors from an introductory programming website.) What

did they do wrong?

Assume that the following definitions occur before every code snippet.


   Program Text:

     my_string = "This is a sentence."

     my_list = [4,2,6,8]

     user_input = "100"

     my_integer = 27



1. Convert my_string to lowercase

   Program Text:

     my_string.lower()


   Answer:
Page 2




2. Print every element in my_list in reverse order.

   Program Text:

     for i in my_list.reverse():
       print i,

   Answer:




3. Reverse the order of elements in my_list.
   Program Text:

     my_list.reverse


   Answer:




4. user_input contains a string representation of a number entered by the user. Multiply it by 10
and add the resulting value to my_list as a string.
   Program Text:

     bigger_input = user_input + 0
     my_list.append(user_input)

   Answer:




5. Create a backup copy of my_list, then remove the largest element from my_list.
   Program Text:

     new_list = my_list
     my_list.remove(max(my_list))

   Answer:
Page 3


5. This function finds the position of the last instance of an element e in a list. Hints: 1) There are no
syntax errors 2) The function always returns the correct value.
    Program Text:

      def rindex(my_list, e):
        """Finds the position of the last occurrence of e in my_list. If e
      is not in l, returns -1"""
        if e not in my_list:
          return -1
        my_list.reverse()
        for i in range(len(my_list)):
          if my_list[i] == e:
            return len(my_list) - 1 - i

    Answer:




6. Prints all elements of my_list
    Program Text:

      for i in my_ list:
        print i
        i = i + 1

    Answer:




7. Finds the largest element in a list
    Program Text:

      def find_max(list):
        """Finds the largest integer in list. Assumes list contains only
      positive integers"""
        max = 0
        for i in my_list:
          if i > max:

            return i

        return max
Page 4



    Answer:




Problem 2: Meaningful Names!
Disclaimer: This example is a bit exaggerated.

You’ll learn more about programming style in subsequent courses, but one thing we want to imprint in

you now is using meaningful variable names. Every variable is created for a reason – its name should

reflect the values you choose to store in it.


The following code is something an introductory student could have written for a class. Imagine being

the TA trying to find the bug in it.


    Program Text:

      def f3(ll):
        #all stuff in ll between 0 and 1000000
        j = 0
        k = 0
        for i in range(len(ll)):
          if ll[i] > ll[j]:

            j = i

          elif ll[i] < ll[k]:

            k = i

        l = ll[j]

        ll[k] = ll[l]

        ll[j] = ll[k]




Your task is to find the bug in the above code. The function should swap the maximum and minimum
elements in a list.

Well..maybe that’s too mean. Here – I’ll give you some meaningful variable names for the above code.

   �3 � swap_max_min                       � � max_position               � � temp


              �� � list                   � � min_position


    Answer:
Page 5



Problem 3: Test Cases
We’ve written a function that calculates the square root of a number. If given a negative number, our
function returns 0 (if you ever write a square root function, don’t do that :p.) We’re using this function
in a much larger program that controls our 6.01 robot, so its kind of important that the know the
function works correctly.

How can we tell if a function works correctly? Staring at it for 30 minutes is probably not the best
solution..Instead, we’re going to write a couple of test cases to make sure it works.

    Program Text:

      SQ_3 = ... #assume SQRT_3 has been initialized to the square root
                 #of 3 (1.717...)


      test_cases = [_____, _____, _____, _____, _____, _____]

      test_case_answers = [_____, _____, _____, _____, _____, _____]

      def custom_sqrt(num):
        "Returns the square root of num, or 0 if num < 0"
        ... (code snipped)

      for i in range(len(test_cases)):
        if custom_sqrt(test_cases[i]) != test_case_answers[i]:
          print "Test Case #",i,"failed!"

Note: You can use the built-in zip function to make the last three lines prettier ... look it up at some
point.

Fill in the blanks below to complete our testing code. You’ll want to use as many unique cases as
possible – don’t just test 1,2,3,4,5,6. At least one of your test cases should be a negative number, for
example.

We gave you six blanks, but you don’t need to use all of them. You want a wide variety of test cases in
order to catch as many bugs as possible, but you also don’t want to test every random number you can
think of. It’s a delicate balance :) – just do your best.

Contenu connexe

Tendances

Python iteration
Python iterationPython iteration
Python iteration
dietbuddha
 

Tendances (20)

Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
Python iteration
Python iterationPython iteration
Python iteration
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapalooza
 
Python
PythonPython
Python
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 
Python set
Python setPython set
Python set
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Python PCEP Lists Collections of Data
Python PCEP Lists Collections of DataPython PCEP Lists Collections of Data
Python PCEP Lists Collections of Data
 
More About Strings
More About StringsMore About Strings
More About Strings
 
Sorting
SortingSorting
Sorting
 
Tuple.py
Tuple.pyTuple.py
Tuple.py
 
Dervy bis 155 week 2 quiz new
Dervy   bis 155 week 2 quiz newDervy   bis 155 week 2 quiz new
Dervy bis 155 week 2 quiz new
 
Ms excel 2003 intermediate
Ms excel 2003 intermediateMs excel 2003 intermediate
Ms excel 2003 intermediate
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 

Similaire à pyton Notes9

Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docx
abhi353063
 
CMPS 5P Assignment 3 Spring 19Instructions1. The aim o.docx
CMPS 5P Assignment 3 Spring 19Instructions1. The aim o.docxCMPS 5P Assignment 3 Spring 19Instructions1. The aim o.docx
CMPS 5P Assignment 3 Spring 19Instructions1. The aim o.docx
mary772
 
Looping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptxLooping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptx
adihartanto7
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Notes5
Notes5Notes5
Notes5
hccit
 
Hey i have attached the required file for my assignment.and addi
Hey i have attached the required file for my assignment.and addiHey i have attached the required file for my assignment.and addi
Hey i have attached the required file for my assignment.and addi
sorayan5ywschuit
 

Similaire à pyton Notes9 (20)

Python advance
Python advancePython advance
Python advance
 
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumans
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning material
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docx
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
 
CMPS 5P Assignment 3 Spring 19Instructions1. The aim o.docx
CMPS 5P Assignment 3 Spring 19Instructions1. The aim o.docxCMPS 5P Assignment 3 Spring 19Instructions1. The aim o.docx
CMPS 5P Assignment 3 Spring 19Instructions1. The aim o.docx
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
 
Looping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptxLooping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptx
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Notes5
Notes5Notes5
Notes5
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Hey i have attached the required file for my assignment.and addi
Hey i have attached the required file for my assignment.and addiHey i have attached the required file for my assignment.and addi
Hey i have attached the required file for my assignment.and addi
 

Plus 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
 
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
 
Lec4
Lec4Lec4
Lec4
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
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...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

pyton Notes9

  • 1. Page 1 6.189 Worksheet Session 9 Administrivia Name: Instructions: 1. Err..complete the questions :). 2. No calculators, no laptops, etc. 3. When we ask for output, you DON'T have to write the spaces/newlines in. Program Text: print “X”, print “X”, Output: XX Problem 1: Common Errors Each of the following code snippets represents a common error made by an introductory programming student (I know this because I ripped these errors from an introductory programming website.) What did they do wrong? Assume that the following definitions occur before every code snippet. Program Text: my_string = "This is a sentence." my_list = [4,2,6,8] user_input = "100" my_integer = 27 1. Convert my_string to lowercase Program Text: my_string.lower() Answer:
  • 2. Page 2 2. Print every element in my_list in reverse order. Program Text: for i in my_list.reverse(): print i, Answer: 3. Reverse the order of elements in my_list. Program Text: my_list.reverse Answer: 4. user_input contains a string representation of a number entered by the user. Multiply it by 10 and add the resulting value to my_list as a string. Program Text: bigger_input = user_input + 0 my_list.append(user_input) Answer: 5. Create a backup copy of my_list, then remove the largest element from my_list. Program Text: new_list = my_list my_list.remove(max(my_list)) Answer:
  • 3. Page 3 5. This function finds the position of the last instance of an element e in a list. Hints: 1) There are no syntax errors 2) The function always returns the correct value. Program Text: def rindex(my_list, e): """Finds the position of the last occurrence of e in my_list. If e is not in l, returns -1""" if e not in my_list: return -1 my_list.reverse() for i in range(len(my_list)): if my_list[i] == e: return len(my_list) - 1 - i Answer: 6. Prints all elements of my_list Program Text: for i in my_ list: print i i = i + 1 Answer: 7. Finds the largest element in a list Program Text: def find_max(list): """Finds the largest integer in list. Assumes list contains only positive integers""" max = 0 for i in my_list: if i > max: return i return max
  • 4. Page 4 Answer: Problem 2: Meaningful Names! Disclaimer: This example is a bit exaggerated. You’ll learn more about programming style in subsequent courses, but one thing we want to imprint in you now is using meaningful variable names. Every variable is created for a reason – its name should reflect the values you choose to store in it. The following code is something an introductory student could have written for a class. Imagine being the TA trying to find the bug in it. Program Text: def f3(ll): #all stuff in ll between 0 and 1000000 j = 0 k = 0 for i in range(len(ll)): if ll[i] > ll[j]: j = i elif ll[i] < ll[k]: k = i l = ll[j] ll[k] = ll[l] ll[j] = ll[k] Your task is to find the bug in the above code. The function should swap the maximum and minimum elements in a list. Well..maybe that’s too mean. Here – I’ll give you some meaningful variable names for the above code. �3 � swap_max_min � � max_position � � temp �� � list � � min_position Answer:
  • 5. Page 5 Problem 3: Test Cases We’ve written a function that calculates the square root of a number. If given a negative number, our function returns 0 (if you ever write a square root function, don’t do that :p.) We’re using this function in a much larger program that controls our 6.01 robot, so its kind of important that the know the function works correctly. How can we tell if a function works correctly? Staring at it for 30 minutes is probably not the best solution..Instead, we’re going to write a couple of test cases to make sure it works. Program Text: SQ_3 = ... #assume SQRT_3 has been initialized to the square root #of 3 (1.717...) test_cases = [_____, _____, _____, _____, _____, _____] test_case_answers = [_____, _____, _____, _____, _____, _____] def custom_sqrt(num): "Returns the square root of num, or 0 if num < 0" ... (code snipped) for i in range(len(test_cases)): if custom_sqrt(test_cases[i]) != test_case_answers[i]: print "Test Case #",i,"failed!" Note: You can use the built-in zip function to make the last three lines prettier ... look it up at some point. Fill in the blanks below to complete our testing code. You’ll want to use as many unique cases as possible – don’t just test 1,2,3,4,5,6. At least one of your test cases should be a negative number, for example. We gave you six blanks, but you don’t need to use all of them. You want a wide variety of test cases in order to catch as many bugs as possible, but you also don’t want to test every random number you can think of. It’s a delicate balance :) – just do your best.