SlideShare uma empresa Scribd logo
1 de 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.

Mais conteúdo relacionado

Mais procurados (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
 

Semelhante a pyton Notes9

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)Live Exam Helper
 
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 YASHU40
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumansNarendran R
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning materialArthyR3
 
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_18012013amanabr
 
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_18012013Kurmendra 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.docxabhi353063
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1Syed Farjad Zia Zaidi
 
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.docxmary772
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And AnswersH2Kinfosys
 
Looping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptxLooping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptxadihartanto7
 
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
Notes5hccit
 
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 addisorayan5ywschuit
 

Semelhante a 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
 

Mais 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
 

Último

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Último (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

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.