[Courses] [python] Lesson 5: Infinite loops, modulo, and random numbers
Kay Nettle
pkn at cs.utexas.edu
Fri Jul 22 02:17:55 UTC 2011
>
>1. Suppose you have a list of colors, like
> colors = [ "red", "orange", "yellow", "green", "blue" ]
> and you have a bunch of things (say, 20 of them) that you
> need to color without repeating. How would you use the modulo
> operator, %, to step through the colors in order, printing out one
> after another and going back to red after blue?
colors = [ "red", "orange", "yellow", "green", "blue" ]
lenght=len(colors)
for i in range(20):
print colors[i % lenght]
>2. How would you write a program to choose a random file from a
> directory full of files? Assume the directory is in some fixed place,
> like "/usr/share/backgrounds" or "/home/yourname/Backgrounds".
> Hint: os.listdir(dirname) will give you a list of all the files in
> a directory. Of course you have to import os first.
import os, random
dir="/usr/share/backgrounds"
if os.path.isdir(dir):
print random.choice(os.listdir(dir))
>3. Make a list of nouns and a list of verbs. Then write a program that
> makes a random sentence by choosing a random noun and a random verb.
>
> You may notice that my verbs are intransitive -- they can be used on
> their own. So you can say "the cat waited", whereas a noun-verb sentence
> wouldn't work if you used a transitive verb like "the cat fixed".
I don't have the grammer gene, so I stopped reading the instructions. I
wrote something that did have some nouns and verbs, but I read from a
file or files...sorry (and I played with argparse).
#!/usr/bin/python
import argparse, random, os, string
nouns=[]
verbs=[]
nouns_default=['the cat', 'the dog', 'the dog who eats pillows', 'the man', 'the girl']
verbs_default=['ate a pillow', 'ran', 'barked']
def read_file(file_name, word_list):
if not os.path.isfile(file_name):
print "%s is not a filename" % (file_name)
sys.exti(1)
else:
file = open(file_name, "r")
for line in file:
line=line.lstrip()
line=line.rstrip(' ' '\n')
if not line:
continue
word_list.append(line)
file.close()
return word_list
parser = argparse.ArgumentParser(description='Print sentences with \
random verbs and nouns (will use built in list if no files are given)')
parser.add_argument('-n','--nouns', dest='noun_file', action='store', \
type=str, default="", help='file with nouns on on a line')
parser.add_argument('-v','--verb', dest='verb_file', action='store', \
type=str, default="", help='file with verbs with verbs one on a line')
parser.add_argument('-t','--times', dest='count', action='store', type=int, \
default=1, help='number of sentences you want generated')
args = parser.parse_args()
if args.noun_file:
read_file(args.noun_file,nouns)
else:
nouns=nouns_default
if args.verb_file:
read_file(args.verb_file,verbs)
else:
verbs=verbs_default
for i in range(args.count):
print random.choice(nouns), random.choice(verbs)
More information about the Courses
mailing list