Sunday, August 26, 2012

Exercises 14-21: Files and subroutines

ex14.py:
1:    
2:  from sys import argv  
3:    
4:  script, uname, pword = argv  
5:  prompt = "My answer is "  
6:    
7:  if pword == "password":  
8:    print "%s@%s" % (uname, script)  
9:    print "Do you like me %s?" % uname  
10:    likes = raw_input(prompt)  
11:    
12:    print "Where you live %s?" % uname  
13:    lives = raw_input(prompt)  
14:    
15:    # copy-pasting the above down here, I left uname in -  
16:    # caused a runtime error - python ran until the statement itself, it  
17:    # didn't do any pre-checking  
18:    print "What kinda comp you got?" #% uname  
19:    comp = raw_input(prompt)  
20:    
21:    print """  
22:    Alright, so you said %r about liking me.  
23:    You live in %r. Not sure where that is.  
24:    And you have a %r computer. Nice.  
25:    """ % (likes, lives, comp)  
26:    
27:  else:  
28:    print "Incorrect password!"  
29:    
ex15.py:
1:    
2:    
3:  from sys import argv  
4:    
5:  #script, filename = argv  
6:    
7:  # opens a file and stores it as a file object  
8:  #txt = open(filename)  
9:    
10:  # read is a method of the file object which returns a string containg the file  
11:  #print "H %r:" % filename  
12:  #print txt.read()  
13:    
14:  # collecting input and making a new file object called txt2  
15:  fn2 = raw_input("Next filename: ")  
16:  txt2 = open(fn2)  
17:    
18:  # read is performed on the file object again  
19:  print "T %r:" % fn2  
20:  #print txt2.readlines()  
21:  for line in txt2:  
22:    print line  
23:  txt2.close()  
24:    
25:  # It is better to do raw_input because it can collect spaces (while spaces in  
26:  # in the argument vector simply increase its length.  
27:  # On the other hand, argument input supports globbing natively.  
28:    
ex16.py:
1:    
2:    
3:  from sys import argv  
4:    
5:  script, filename = argv  
6:    
7:  print "We're going to erase %r." % filename  
8:  print "If you don't want that, hit CTRL-C (^C)."  
9:  print "If you do want that, hit RETURN."  
10:    
11:  raw_input("?")  
12:  t = open(filename, 'w')  
13:  #t.truncate()  # seems unnecessaryu for this stricpt  
14:    
15:  l1 = raw_input("1:")  
16:  l2 = raw_input("2:")  
17:  l3 = raw_input("3:")  
18:    
19:  t.write("%s\n%s\n%s\n" % (l1,l2,l3))  
20:    
21:  t.close()  
22:    
23:  # check conbtents  
24:  t = open(filename)  
25:  print t.read()  
26:  t.close()  
27:    
28:  print "something"  
29:    
ex17.py:
1:    
2:    
3:  from sys import argv  
4:  from os.path import exists  
5:    
6:  script, ffile, tfile = argv  
7:    
8:    
9:  ifile = open(ffile)  
10:  indata = ifile.read()  
11:  print "Preparing to copy %d bytes from %s to %s" % (len(indata),ffile,tfile)  
12:    
13:  if not exists(tfile):  
14:    ofile = open(tfile,'w')  
15:    ofile.write(indata)  
16:    print "DONE!"  
17:    ofile.close() # its possible without this line that the new file would not  
18:           # be written to disk.  
19:  ifile.close()  
20:  print "something"  
21:    
22:    
23:  # options regarding importing modules:  
24:  ##> import X - creates a ref in current namespace... X.method() works  
25:  ##  X = __import__('x') - imports module defined by string to programmer  
26:  ##          defined variable X in cur namespace  
27:  ##  from X import * - creates refs for all public objects  
28:  ##  from X import Y, Z - creates refs for listed objects  
29:  # the first one is generally ideal.  
30:  # avoid circular imports - two files which import each other  
31:    
32:    
33:  # Below is some fucking about...  
34:  import string  
35:    
36:  print string.ascii_letters #a-zA-Z or maybe the other way around  
37:  print string.digits    # 0-9  
38:  print string.printable   # everything  
39:    
40:    
41:  # os.path is for whatever the current os is...  
42:  # can specify (why would you want to): ntpath, posixpath, macpath  
43:    
44:  abspath ="/home/stude2/s/slithgow/python/data2"  
45:    
46:  # print os.path.basename(abspath)  
47:  #       .exists / lexists <- second is True for broken symlinks  
48:  #                  (first is not)  
49:  #       .splitext <- returns tuple (root,ext) putting shit  
50:  #               in root if theres no ext  
51:    
52:  # s=set([iterable]) eg. s=set('abc')  
53:  # len(s)  
54:  # x in s / x not in s  
55:  # s.isdisjoint(s2)  
56:  # >,>=,<,<= - elementwise compare  
57:  # .issubset(s2) / .issuperset(s2)  
58:  # .union(s2) / .intersection(s2)  
59:    
60:    
ex18.py:
1:    
2:    
3:  #from sys import argv  
4:  #script, filename = argv  
5:    
6:              # Zed says:  
7:  def print_two(*args):  #  *args hactually means all remaining args  
8:    a1,a2 = args    #  so print_two(1,2,3,34,45,5,6,6,7,78) is valid  
9:    print "%r %r" % (a1,a2) # but it will fuck up in the above pattern match  
10:    
11:  def beacorn (*args):  
12:    print "arg1: %r, arg2: %r" % args  
13:    
14:  def print_2(a1,a2,*a3):  
15:    print "%r %r" % (a1,a2)  
16:    
17:  def print_one(a1):  
18:    print "%r" % a1  
19:    
20:  def print_none():  
21:    print "THERE CAN BE ONLY NONE!"  
22:    
23:    
24:  print_two("1.1","1.2") # adding extra args here doesnt seem to work.. ,"1.3")  
25:  print_2("2.1","2.2")  
26:  print_one("3.1")  
27:  print_none()  
28:  #beacorn("one","two","three","hahahaha you suck!")  
29:    
30:  print "something"  
31:    
ex19.py:
1:    
2:  def c(cheese_count, boxes_of_crackers):  
3:    print "You have %d cheeses!" % cheese_count  
4:    print "You have %d boxes of crackers!" % boxes_of_crackers  
5:    print "Man that's enough for a party!"  
6:    print "Get a blanket.\n"  
7:    
8:    
9:  #print "something"  
10:  c(20,30)  
11:    
12:  #print "OR, we can use variables from our script:"  
13:  amount_of_cheese = 10  
14:  amount_of_crackers = 50  
15:  c(amount_of_cheese, amount_of_crackers)  
16:    
17:  #print "We can even do math inside too:"  
18:  c(10 + 20, 5 + 6)  
19:    
20:  #print "And we can combine the two, variables and math:"  
21:  c(amount_of_cheese + 100, amount_of_crackers + 1000)  
22:    
23:    
24:  # one more func of own design  
25:  def newfunc(arg):  
26:    print "%r" % arg  
27:    
28:  # run it 10 different ways:  
29:  #1 iteratively  
30:  for x in range(10):  
31:    newfunc('  '+("%d"%x))  
32:    
33:  #2 hardcoded strings  
34:  newfunc("string")  
35:    
36:  #3 function pointers  
37:  newfunc(c)  
38:  newfunc(newfunc)  
39:    
40:  #4 predefined object  
41:  s = set('abcde')  
42:  newfunc(s)  
43:    
44:  #5 disposable object  
45:  newfunc(set('1234'))  
46:    
47:  #6 nested methods  
48:  newfunc(s.union(set('defgh')))  
49:    
50:  #7 inline hiding  
51:  print "%s" % "hey" and newfunc("hello")  
52:    
53:  #8 from user input  
54:  newfunc(raw_input("Anything:"))  
55:    
56:  #9 printing the reference to imported class chosen at runtime  
57:  newfunc(__import__(raw_input("A Python class:")))  
58:    
59:  #10 regex patten  
60:  import re  
61:  newfunc(re.compile('^((\S*)//)*(\S*)\.(\S*)'))  
62:    
ex20.py:
1:    
2:    
3:  from sys import argv  
4:    
5:  script, filename = argv  
6:    
7:  def print_all(f):  
8:    print f.read()  
9:  def rewind(f):  
10:    f.seek(0)  
11:  def print_a_line(l,f):  
12:    print l, f.readline()  
13:    
14:  peter_file = open(filename)  
15:  print_all(peter_file)  
16:  rewind(peter_file)  
17:  c = 1  
18:  while c<4:  
19:    print_a_line(c,peter_file)  
20:    c+=1  
21:    
22:    
23:  print "something"  
24:    
ex21.py:
1:    
2:  def add(a, b):  
3:    print "ADDING %d + %d" % (a, b)  
4:    return a + b  
5:    
6:  def subtract(a, b):  
7:    print "SUBTRACTING %d - %d" % (a, b)  
8:    return a - b  
9:    
10:  def multiply(a, b):  
11:    print "MULTIPLYING %d * %d" % (a, b)  
12:    return a * b  
13:    
14:  def divide(a, b):  
15:    print "DIVIDING %d / %d" % (a, b)  
16:    return a / b  
17:    
18:    
19:  print "Let's do some math with just functions!"  
20:    
21:  age = add(30, 5)  
22:  height = subtract(78, 4)  
23:  weight = multiply(90, 2)  
24:  iq = divide(100, 2)  
25:  print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)  
26:    
27:    
28:  # A puzzle for the extra credit, type it in anyway.  
29:  print "Here is a puzzle."  
30:    
31:  what = add(age, subtract(height, multiply(weight, divide(iq, 2))))  
32:    
33:  # first time through, i read subtract's shit backwards.  
34:  # for non-commutative functions, best to pay careful attention to  
35:  # order of arguments...  
36:  yes = height - iq /2 *weight+age  
37:  # not sure if that was what was expected for extra credit #2..  
38:    
39:  print "That becomes: ", what, "Can you do it by hand?", yes  
40:    
41:    
42:  # ugh... im not doing any of the other ones without infix support...  
43:  #  found this: http://dev-tricks.net/pipe-infix-syntax-for-python  
44:  #  looks perfect, but when I  
45:  #  from pipe import *  <- tried using this... it became apparent that  
46:  #  it requires the functions to be rewritten using 'yield' which we havent  
47:  #  covered yet... baby steps, baby steps.  
48:    

No comments:

Post a Comment