SlideShare una empresa de 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.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (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
 

Similar a pyton Notes9

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
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And AnswersH2Kinfosys
 
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
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
 
Exam 1 Review CS 1803
Exam 1 Review CS 1803Exam 1 Review CS 1803
Exam 1 Review CS 1803Will Barr
 
Problem solving using computers - Chapter 1
Problem solving using computers - Chapter 1 Problem solving using computers - Chapter 1
Problem solving using computers - Chapter 1 To Sum It Up
 

Similar a pyton Notes9 (20)

Python advance
Python advancePython advance
Python advance
 
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
 
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
 
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
 
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
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
Exam 1 Review CS 1803
Exam 1 Review CS 1803Exam 1 Review CS 1803
Exam 1 Review CS 1803
 
ex 2.pdf
ex 2.pdfex 2.pdf
ex 2.pdf
 
Problem solving using computers - Chapter 1
Problem solving using computers - Chapter 1 Problem solving using computers - Chapter 1
Problem solving using computers - Chapter 1
 

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

Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 

Último (20)

Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 

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.