ecs10-11-14 - Announcements ECS 10 11/14 MIDTERM MIDTERM...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 11/14/2008 Announcements ECS 10 11/14 MIDTERM MIDTERM Mon Nov 17 Open Open book, open notes. Bring sample programs from class, your programs, etc. Bring Bring a Scantron 2000 On myUCDavis: On myUCDavis: solutions to Prog 4, programming problem on sample midterm. Topics Topics Lists, Lists, indexing, concatenation of lists range range and len functions for for loops on lists and strings Files Files String String methods (split, replace, strip) Dictionaries Dictionaries Exceptions Exceptions Formatting Formatting floating point output Midterm 1 Topics choosing = True while choosing: a = raw_input(‘Enter h or t: ’ ) choosing = not (a == ‘h’ or a == ‘t’) print ‘You chose’,a choosing choosing is a Boolean variable. while loop while loop runs so long as choosing is True choosing is Gets Gets set to False if a==‘h’ or a==‘t’ False if List Indexing import random suits = ['Hearts', 'Clubs', 'Spades', 'Diamonds'] faces = ['J', 'Q', 'K'] i = random.randrange(4) num = random.randrange(13) if num < 10: print 'My card is the',num+1,'of',suits[i] else: print 'My card is the',faces[num-11],'of',suits[i] Example Question The program: dogList = [‘Collie’, ‘Beagle’, ‘Dachshund’] print dogList[3] dogList[3] will print… a) ‘Collie’ b) ‘Beagle’ c) ‘Dachshund’ d) crashes 1 11/14/2008 Concatenating Lists digits = [ ] for i in range(10): digits = digits + [str(i)] print digits digits begins as the empty list Function range(10) has the value [0,1,2,…8,9] (it produces a list!). Function str(i) converts integer i to a string We have to concatenate two lists, so [str(i)] Example Question This program has a missing line. dogList = [‘Collie’] ______________ for i in range(len(dogList)): print dogList[i] dogList[ The program prints: a) dogList = dogList+’Beagle’ Collie b) dogList[1] = ‘Beagle’ Beagle c) dogList[2] = ‘Beagle’ The missing line should be: d) dogList=dogList+[Beagle] e) dogList=dogList+[‘Beagle’] For Loop on a String line = '+11(0)456-897-4565' digits = ['0','1','2','3','4','5','6','7','8','9'] numStr = '' for char in line: li if char in digits: numStr = numStr+char num = int(numStr) print num For Loops for char in line: Since line is a string, the variable char will be each character in the string in turn. for word in wordList: dL If wordList is a list of strings, the variable word will be each string in the list in turn. for i in range(len(a)): Whether a is a list or a string, i will be the integers from 0 through len(a)-1, in turn. String String Methods string string.strip() string = string.strip() Removes Removes leading and trailing whitespace String Processing string = ‘ Nov 12\tNASDAQ\t 2634.93\t+0.63%\n’ string = string.strip() words = string.split(‘\t’) change = words[ len(words) – 1 ] if change[0] == ‘+’: direction = ‘up’ change = change.replace(‘+’, ‘’) else: direction = ‘down’ change = change.replace(‘-’, ‘’) print ‘NASDAQ’, direction, ‘by’, change words string.split(‘\ words = string.split(‘\t’) Returns list of substrings change change.replace(‘%’, change = change.replace(‘%’, ‘’) Replaces Replaces all copies of one substring with another 2 11/14/2008 Files inFile = open(‘myFile.txt’, ‘r’) giftStr = inFile.readline() while giftStr != ‘’: print ‘Read line: ’, giftStr giftStr = inFile.readline() inFIle.close() Files are read from beginning to end; no going backwards! readline() method returns next line. readline() returns empty string at end of file. Alternative File Loop inFile = open(‘myFile.txt’, ‘r’) giftStr = None while giftStr != ‘’: giftStr = inFile.readline() print ‘Read line: ’, giftStr inFIle.close() The value None lets you define the variable giftStr without putting anything into it. Keeps Boolean in while from crashing first time through. Writing Files myFile = open('toExcel.tsv', 'w') for i in range(10): floatNum = float(i) myFile.write('item'+str(i)+'\t%.2f\n'%floatNum) myFile.close() Open file to write with ‘w’ write() method has one string argument. Formatting Formatting Strings '\t%.2f\n'%floatNum % operator has string on the left, number on operator the right. h Formatting Formatting string on the left contains special formatting sequences that get replaced by the number. ‘%.2f’ ‘%.2f’ writes the number with two decimal places. Dictionaries giftDict = {} giftDict['Lion'] = 'Courage' giftDict['Tin Man'] = 'a Heart' giftDict['Scarecrow'] = 'Brains' character = raw_input('Character name: ') if character in giftDict: gift = giftDict[character] print 'The gift of the',character,'is',gift+'.' Key – Value Pairs {'Lion': 'Courage', 'Scarecrow': 'Brains', 'Tin Man': 'a Heart'} Keys Keys on left of colon, values on right. Keys are like indices, values are the data stored stored by indices. 3 11/14/2008 Dictionary Access Putting Putting a pair into the dictionary: giftDict[‘Lion’] = ‘Courage’ Dictionary Dictionary location on the left is like a variable; it is a `labeled box’ we put data into. bl `l Data Data value on the right can be anything. Getting Getting data out of the dictionary: gift = giftDict[character] Data Data from dictionary goes into the variable on the left. Checking Checking for a Key if character in giftDict: If If you try to access a key that is not in the dictionary, the program crashes! If If there is any doubt that your key will be there, check first. Use Use the in operator. Produces a Boolean, True if key on left is in dictionary on right. Example Example This program is missing a Boolean exprssion. I exprssion. should be… D = {'A':1, 'B':2, 'C':3} code = raw_input('Enter the code: ') raw if _______________: print D[code] a) helper.isInt(code) helper.isInt(code) b) int(code) int(code) c) ‘:’ in code d) code in D Exceptions def isFloat(s): try: float(s) # Try to do the conversion except: return False # Conversion failed! else: return True # Conversion succeeded 4 ...
View Full Document

This note was uploaded on 03/23/2011 for the course ECS 10 taught by Professor Amenta during the Winter '07 term at UC Davis.

Ask a homework question - tutors are online