CS100 - PYTHON – EXAM 2 REVIEW -ONLY THE VITAL STUFF- PYTHON STRING METHODS, LOOPS, FILES, AND DICTIONARIES.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Container Types in Python
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Python Dictionary.
Lists Introduction to Computing Science and Programming I.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Guide to Programming with Python
Group practice in problem design and problem solving
Python Control of Flow.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
 1 String and Data Processing. Sequential Processing Processing each element in a sequence for e in [1,2,3,4]: print e for c in “hello”: print c for.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists and More About Strings CS303E: Elements of Computers and Programming.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Data Collections: Dictionaries CSC 161: The Art of Programming Prof. Henry Kautz 11/4/2009.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 8: Fun with strings.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
More Strings CS303E: Elements of Computers and Programming.
Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
14. DICTIONARIES AND SETS Rocky K. C. Chang 17 November 2014 (Based on from Charles Dierbach, Introduction to Computer Science Using Python and Punch and.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
CMSC201 Computer Science I for Majors Lecture 08 – Lists
String and Lists Dr. José M. Reyes Álamo.
Intro to CS Nov 21, 2016.
Tuples and Lists.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
CSc 120 Introduction to Computer Programing II
CSC 108H: Introduction to Computer Programming
Week 5: Dictionaries and tuples
Strings Part 1 Taken from notes by Dr. Neil Moore
Winter 2018 CISC101 11/16/2018 CISC101 Reminders
Bryan Burlingame Halloween 2018
CEV208 Computer Programming
String and Lists Dr. José M. Reyes Álamo.
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
(more) Python.
15-110: Principles of Computing
Topics Introduction to File Input and Output
Topics Basic String Operations String Slicing
Introduction to Computer Science
Python Review
Python Strings.
Topics Basic String Operations String Slicing
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Topics Basic String Operations String Slicing
Introduction to Computer Science
Presentation transcript:

CS100 - PYTHON – EXAM 2 REVIEW -ONLY THE VITAL STUFF- PYTHON STRING METHODS, LOOPS, FILES, AND DICTIONARIES

REVIEW: WHAT IS A STRING? A string is an immutable list of characters. This differs from a list of characters because a list is mutable. String functions operate on s, and return a new string without affecting the original one. EX. S = “Hello, world” L = S.lower() print(S) print(L) >>>Hello, world >>>hello, world

LIST OF NOTABLE STRING METHODS s.lower() --- Returns a lowercase representation of s. s.upper() --- Returns an uppercase representation of s. s.split(x) --- Returns a list of strings from the original string, that were separated by x. If no x is given it defaults to white space. s.index(x) --- Returns the index of the first occurrence of x in s. s.count(x) --- Returns the number of occurrences of x in s. s.strip(x) --- Returns a new string with the leading and trailing x’s removed

DON’T FORGET INDEXING V SLICING s=“Hello, world.” print(s[0]) print(s[0:1]) print(s[-1:]) print(s[-1]) >>>H >>>[‘H’] >>>[‘.’] >>>.

WHILE LOOPS While loops will loop over a block of code, as long as a specified condition evaluates to true. while( True ): print(“Lots of hellos!”) This loop, will loop FOREVER, and will continually print out “Lots of hellos!”

SOLVING 2^X = Y WITH A WHILE LOOP This is known as a logarithm, and the simplest way to understand this problem is, how many times must you multiply 2 by itself in order to reach Y Alternatively, how many times can you halve Y? EX. Y = 5, Halved once(without the decimal portion) Y=2, Halved twice Y = 1. 1 can not be halved in a meaningful way so Y can be halved twice.

BREAKING AND CONTINUING The keyword break leaves a loop entirely. The keyword continue goes to the next iteration of the loop instantly. ---That’s about all there is to it.

HOW MANY TIMES CAN WE HALVE SOMETHING We can halve a number as long as it is not 1. We should then loop, as long as the number we are working with, is not 1. orig = x = int(input("Enter a number to be halved: ")) c = 0 while (x != 1): x = x//2 c += 1 print(int(orig)," can be halved ", int(c), "time(s).")

WHILE LOOPS --- THE NATIVE FOR LOOP CLASSIC FOR LOOP for x in range(10): print(x) THE SAME AS A WHILE LOOP x = 0 while(x < 10): print(x)

WHEN TO WHILE, WHEN TO FOR? FOR LOOP When you are given a list or sequence to work with and look at elements individually WHILE LOOP When you are not given a list or sequence. When you don’t know when to stop looping.

FILES --- JUST REMEMBER TO CLOSE THEM! INPUT FILES fileObj = open(filename, 'r') fileObj.readlines() fileObj.read() fileObj.close() OUTPUT FILES fileObj = open(filename, 'w') fileObj.write('info to be written') fileObj.close()

RECALL Variables must be initialized before use. Lists must be initialized before appending. x = y + 1 NAME ERROR: y is not defined. x.append(“Hello”) NAME ERROR: x is not defined.

DICTIONARIES Dictionaries are a data structure used to associate keys and values. For example in a English to Spanish dictionary there may be an entry : Two : Dos. Two is the key, and Dos is the value. Below is a python representation. d = {'two':'dos'}

DICTIONARIES d = {} #empty dictionary englishToSpanish = {'cat':'gato', 'blue':'azul'} usernamePassword = {'user1':'pass1', 'user2':'pass2', 'user3':'pass3'} letterCount = {'a':2, 'b':3, 'c':1} familyDict = {'Simpson':['Homer', 'Marge', 'Lisa', 'Bart', 'Maggie'], 'Belcher':['Bob', 'Linda', 'Tina', 'Louise', 'Gene']}

DICTIONARIES --- KEYS DON’T HAVE TO BE STRINGS Keys can assume any value as long as the type is immutable. Numbers, Strings, Booleans, and Tuples are the immutable types we’ve encountered Lists, Dictionaries, Files, and Turtles are the mutable types we’ve encountered boolCount = {True:10, False:3} numberWord = {1:'one', 2:'two', 3:'three'}

DICTIONARY PROBLEMS Keeping Count – Keeping track of counts that are sorted by something like line number, character, evenness? Tracking Lists – How many words begin with a letter? How many words are of a specific length?

PLURAL COUNT Write a function named pluralCount() that takes two string parameters. The first parameter is the name of an input file that exists before pluralCount() is called. The second parameter is the name of an output file that pluralCount() creates and writes to. You may assume that the input file is in the current working directory and you should write the output file to that directory as well. For each line in the input file, the function pluralCount() should write to the output file the number of words in the line that end in the letter 's'.

For example, if the following is the content of the file foxInSocks.txt: Look, sir. Look, sir. Mr. Knox, sir. Let's do tricks with bricks and blocks, sir. Let's do tricks with chicks and clocks, sir. The following function call: inF = 'foxInSocks.txt' outF = 'foxRepLines.txt' pluralCount(inF, outF) should create the file ‘foxRepLines.txt’ with the content: 0 4

VOWEL COUNT The letters a, e, i, o and u are the only vowels. Write a function named vowelUseDict() takes a string t as a parameter and computes and returns a dictionary with the number of words in t containing each vowel. Assume that the given text contains only lower case letters and white space. Input: t, a string consisting of lower case letters and white space Return: a dictionary in which each vowel is a key and its value is the number of words containing that vowel For example, the following would be correct output. text = 'like a vision she dances across the porch as the radio plays' print(vowelUseDict(text)) {'e': 5, 'u': 0, 'o': 4, 'a': 6, 'i': 3}

LONGEST WORD IN LINE Write a function named longestWord() that find the length of the longest word in each line in a file and writes that length to a new file. The function longestWord() takes two string parameters. The first parameter is the name of an input file that exists before longestWord() is called. The second parameter is the name of an output file that longestWord() creates and writes to. Assume that the input file contains only letters and white space. Assume that the input file is in the current working directory and write the output file to that directory. The function longestWord() should write a line to the output file only if the line in the input file is not empty, that is, it contains at least one word.

For example, if the following is the content of the file trouble.txt: We surely got trouble Right here in River City Gotta figger out a way To keep the young ones moral after school The following function call: inF = 'trouble.txt‘ outF = 'troubleLongest.txt‘ longestWord(inF, outF) should create the file longestWord.txt with the content:

WORD LENGTH COUNT Write a function named wordLengths() that counts the frequency with which words of different lengths occur in an input file and then returns a dictionary that contains this information. The function wordLengths() takes one parameter: a string that is the name of an input file that exists before wordLengths() is called. You may assume that the input file is in the current working directory. Assume that the input file contains only lower case letters and endlines (no capital letters or punctuation). Each occurrence of a word in the input file should be counted. Duplicate words should be counted twice, triplicates three times, and so on.

For example, suppose this is the content of the file santa.txt: merry christmas to all and to all a good night Then the function call wordLengths('santa.txt') should return a dictionary with these key/value pairs {1: 1, 2: 2, 3: 3, 4: 1, 5: 2, 9: 1} Hint: note that in the returned dictionary, word lengths are keys and the count of words of that length is the corresponding value.

PHONE BOOK FILTER Inputs: A dictionary of names as keys and phone numbers as values. A string to use as a filter. Outputs: A dictionary of names as keys and phone numbers as values, the keys and values come from the input dictionary, and are only in the output if the name contains the filter value.

FOR MORE PRACTICE GO TO Practice the multiple choice especially, as I have covered the open ended for the most part. ---Excluding turtle.