Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CS100 - PYTHON – EXAM 2 REVIEW -ONLY THE VITAL STUFF- PYTHON STRING METHODS, LOOPS, FILES, AND DICTIONARIES."— Presentation transcript:

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

2 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

3 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

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

5 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!”

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

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

8 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).")

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

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

11 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()

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

13 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'}

14 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']}

15 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'}

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

17 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'.

18 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

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

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

21 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: 7 5 6 6

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

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

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

25 FOR MORE PRACTICE GO TO https://web.njit.edu/~jat37/cs100.html Practice the multiple choice especially, as I have covered the open ended for the most part. ---Excluding turtle.


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

Similar presentations


Ads by Google