450 likes | 807 Views
Programming for Linguists. An Introduction to Python 6 /12/2012. Overview. Exercises Fruitful vs. Void Functions Return Statement Recursion Lists While Statement Introduction to Regular Expressions. Exercises.
E N D
Programming for Linguists An Introduction to Python6/12/2012
Overview • Exercises • Fruitful vs. Void Functions • Return Statement • Recursion • Lists • While Statement • Introduction to Regular Expressions
Exercises Oef. 1defprintSentence(sentence): print sentence.upper( ) print sentence.lower( ) print sentence.title( )printSentence(“hallo iedereen”)
Oef 2.defcheckIndex(sent, let):highestI = sent.rfind(let)lowestI= sent.find(let) print ‘higest index’, highestI print ‘lowest index’, lowestI for s in sent: if sent.index(s) > 3 and s == let: sent = sent[:3] + sent[3:].replace(s, ‘3’) print sentcheckIndex(“Hello iedereen”, “e”)
Oef 3.deftkofschip(verb): ifverb.endswith ("t") or verb.endswith("k") or verb.endswith ("f") or verb.endswith("s") or verb.endswith("c") or verb.endswith("h") or verb.endswith("p"): print verb+"te" else: print verb+"de" tkofschip(“lach”)
Oef 4.def change( ): name = raw_input(“What's your name? ”) name = name.lower( ) name = name.replace(‘a’, ‘4’)name = name.replace(‘e’, ‘3’) name = name.replace(‘i’, ‘1’)name = name.replace(‘o’, ‘0’) print namechange( )
Fruitful vs. Void Functions defwordLength(word): print len(word) word1 = wordLength(“hallo”)print word1type(word1) def wordLength2(word):returnlen(word) word2 = wordLength2(“hallo”)print word2type(word2)
Fruitful functions: • return a value • result = int, str, float, function,… • you can work with this value in the rest of your script • often contain the return-statement • Void functions: • do not return a value • result = NoneType • all operations in the function are lost
Return statement • Translation: “return immediately from the function and use the following expression as a return value” defwl(word): return len(word) print len(word) wl(“kast”) def wl2(word): print len(word) return len(word) wl2(“kast”)
You can use multiple return statements defabsoluteValue(x): if x >= 0: return x else: return –x absoluteValue(–1)
You can return a value, a variable, a function, a boolean expression • As soon as a return statement executes, the function terminates • Code that appears after a return statement = dead code
Ask the user to enter his/her age. Write a functionthat takes the result as an argumentand returns Trueif the user is over 18 andFalseif the user is under 18. Thenwriteanif-statementthat prints “Pass” when the result of the function is True and “Stop” if the result is False.
>>>input = raw_input(“Welcome. How old are you? ”) >>>defageCheck(user_age):user_age = int(user_age) if user_age >= 18: return True else: return False >>> if ageCheck(input) == True: print “Pass” else: print “Stop”
Recursion • As we saw: one function can call another • A function can also call itself • A function that calls itself = recursive • The process = recursion
Try this:def countdown(nr): ifnr<=0: print ‘Happy Newyear!’ else: print nrnr = nr - 1 countdown(nr)countdown(10)
Infinite Recursion • If a recursion never reaches a base case, it goes on making recursive calls forever the program never terminates • Generally not a good idea • Python reports an error message when the maximum recursion depth is reached
Lists • A list is a sequence of values • The valuescanbe of any type • The values = elements/items • A list is always in between[ ] • To create a new list:l1 = [10, “cheese”, 5.6, “this is a sentence”]
A list can contain another list (nested list):l2 = [‘hello’, 15, [‘my name is’, ‘X’]] • A list also has an indexprint l2[0]print l2[– 1]print l2[1:]print l2.index(15) • you can change existing lists>>>l2[2] = 10>>>print l2[‘hello’, 15, 10]
A list index works the sameway as a string index: • any integer expressioncanbeused as an index • ifyoutry to readorwritean element that does notexist, yougetanIndexError • ifan index has a negativevalue, itcountsbackwardfrom the end of the list • the in operator alsoworksonlists
Working with Lists • Creating an empty list empty_list = [ ] • Traversing a list: words = [‘work’, ‘run’, ‘play’, ‘jump’]forwinwords: print w Thefor loop traverses the list andperformsan action on eachelement
List Operations • The + operator concatenateslists • the * operator repeats a list a givennumber of times • The slice operator [n:m] givesyou a slice of the list
Example list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list3 = list1 + list2 print list3 print list1*2 print list1[1:3]
Addingelementstolists • one elementlist1 = [‘a’, ‘b’, ‘c’]list1 + ‘d’list1 += ‘d’print list1list1 = list1 + [‘e’]print list1list1.append(‘f’)print list1list1.extend(‘g’)print list1
more thanone elementlist1 = [‘a’, ‘b’, ‘c’]list1 +=[‘d’, ‘e’, ‘f’]print list1list1.append([‘g’, ‘h’, ‘i’])print list1list1.extend([‘j’, ‘k’, ‘l’])print list1 • But list1.append(‘g’, ‘h’, ‘i’)list1.extend(‘g’, ‘h’, ‘i’)
Pay attention! • Whenyouonlyaddone element +=item ,.append(item), .extend(item)and+[item] return the sameresult • Whenyouadda list .append(list)returns a nested list!
Deleting elements from a listlist1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] • using the index in the list list1.pop(1) print list1del list1[0] print list1 • using the elements in the list list1.remove(‘d’) print list1
popmethod modifies the list and returns the removed element • delmethod modifies the list without returning the removedelement • removemethod ifyou do notknow the index of the element
Pay attention!words = [‘ha’,‘funny’, ‘ha’, ‘ha’]words.remove(‘ha’)print words • .remove( ) only deletes the first occurrence of the item in the list • again details: pay attention to where your list variable should comelist.pop(index) del list[index]list.remove(item)
Some other methods • list.count( ) counts the number of items • list.sort( )sorts the list bynumber/alphabetically • list.insert(index, item) places the item at the given index in the list • list.reverse( ) reverses the list
From String to List • From a word to a list of letters: list( ) functions = “spam”print list(s)[‘s’, ‘p’, ‘a’, ‘m’] • From a sentence to a list of words: .split( )functions = “This is a sentence”print s.split( )[‘This’, ‘is’, ‘a’, ‘sentence’]
The split( ) function splits on white spaces, but can also be used to split a string on other characters s = “spam;spam;spam”print s.split(“;”)[‘spam’, ‘spam’, ‘spam’] • “;” is called the delimiterin this case
From List to String • Join( ) is the inverse of split( )l = [‘this’, ‘is’, ‘a’, ‘sentence’]delimiter = “ ”delimiter.join(l)“this is a sentence”
Rewriteyourtkofschipfunctionusing a list and return statements.
deftkofschip(verb): letters = [‘t’, ‘k’, ‘f’, ‘s’, ‘c’, ‘h’, ‘p’]ifverb[-1] in letters: return verb + ‘te’else: return verb + ‘de’tkofschip(‘speel’)tkofschip(‘schop’)
The While Statement • used to perform identical or similar tasks def countdown(nr):whilenr > 0: print nrnr = nr – 1 print “Happy Newyear!”countdown(10)
Mind the difference in indentation between the statements inside and outside the while statement ! • The statements inside the body should change the value of one or more variables so that the condition becomes False at a certain point • If a loop goes on forever = infinite loop • You can use the break statement to jump out of the loop
This program will echo the keyboard input until the user types “done” while True: line = raw_input (“> ”)if line == “done”: break print line
Regular Expressions • Touseregularexpressions in Python we need to import the re library(at the beginning of the script)import re
Some Basic Regular Expression Meta-characters • . Wildcard, matches anycharacter • ^abc Matches somepattern abc at the start of a string • abc$ Matches somepattern abc at the end of a string • [abc] Matches one of a set of characters • [A-Z0-9] Matches one of a range ofcharacters
a|b|c Matches one of the specifiedstrings (disjunction) • * Zero or more of the previous item(s) • + One or more of the previous item(s) • ? Zero orone of the previous item(s) (i.e.optional) • {n} Exactlynrepeatswheren is anon-negative integer • {n,} At leastnrepeats
{,n} No more thannrepeats • {m,n} At leastmand no morethannrepeats • a(b|c)+ Parentheses thatindicate the scope of the operatorse.g.w(i|e|ai|oo)t matches wit, wet, waitand woot • <.*> Matches anytoken • In general, whenusingregularexpressionsit is best to user'...' before the regularexpressions
Counting all vowels in a given word:word='supercalifragilisticexpialidocious' vowels = re.findall(r'[aeiou]', word)nr_vowels = len(vowels) • The re.findall( ) functionfinds all (non-overlapping) matches of the givenregularexpression
You can find a list of all regular expressions operations in Python on: http://docs.python.org/library/re.html • Exercises for next week on Blackboard