A function that returns a list of random 3 letter words 2 A function that reads

A function that returns a list of random 3 letter

This preview shows page 9 - 17 out of 32 pages.

1. A function that returns a list of random 3-letter words. 2. A function that reads a text file and returns a list where each item in the list is a line in the file. 3. A script that uses a US Census dataset to examine county population growth rates from 2010 to 2014.
Image of page 9
1. A Function that Returns a List of Strings def ListOfRandomStrings(n,m): """ Returns an alphabetized length-n list of random strings each of which is made up of m lower case letters. The items in the list are distinct. PreC: n and m are positive integers and n<=26**m. """ Let’s implement this: There are 26**m different possible strings . So n cannot be bigger than that.
Image of page 10
ListOfRandomStrings(100,4) afei atou atzo auvf bdus bmut bnhk btqp bztw cabs cdnr chda dayy dhtb dinj drfq ecme eixm ethh evsv frar gfam gssn gtnx gvmp hfhb hlwe ilsr inxs iolb itzv izwd jfmc jtph jzai kefo keiy keyo kfft kwnu kyoi lbgt ldgs ldrc luwn lvtg lynx medj mplc muzs mvov nawk ngvb nkhp nogc npgc ntjk nwbt oefw oepg pddo pewe phpp qapi qhal qmod qryd qwhj rmhk rorl rvhu sauo sebg segl sknu slgk svsf tmry uake vinu vlvx vygo wtoi wxmj xpcn xuni ypta yqxc yqzq ysny ywsd yyut zayj zhym zqdn zsqf zvce zwgj zxog zyyp Sample outcome:
Image of page 11
Helper Function RandString def RandString(m): """ Returns a random length-m string consisting of lower case letters. PreC: m is a positive integer. """ Assume the availability of…
Image of page 12
If we allowed Repeats… def ListOfRandomStrings(n,m): s = [] for k in range(n): w = RandString(m) s.append(t) s.sort() return s Repeat n times: Generate a random string and append
Image of page 13
Check Before Appending… def ListOfRandomStrings(n,m): s = [] k = 0 # k is the length of s. while k<n: w = RandString(m) if w not in s: s.append(w) k+=1 s.sort() return s Repeat: Generate a random string and append IF it is not yet in s Notice how we can use “in” to look for values in a list. And “not in” to confirm the absence of a value in a list
Image of page 14
2. Reading a Text File Into a List of Strings MyFile.txt abcd 123 abc d fdd xyz 3.14159 2.12345 Text files can be visualized like this: This text file has four lines.
Image of page 15
Our Plan MyFile.txt abcd 123 abc d fdd xyz 3.14159 2.12345 We will “read” the file line-by-line and make each line an item in a list of strings. 0 ---> abcd 1 --- > ‘123 abc d fdd 2 --- > ‘xyz’ 3 --- > ‘3.14159 2.12345’ L -->
Image of page 16
Image of page 17

You've reached the end of your free preview.

Want to read all 32 pages?

  • Fall '19
  • Carriage return

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture