Difference between revisions of "CSC111 Midterm Solution Programs"

From dftwiki3
Jump to: navigation, search
Line 109: Line 109:
 
</source>
 
</source>
  
 +
==Output==
 +
 +
<code><pre>
 +
f6
 +
0
 +
0
 +
1
 +
1
 +
2
 +
2
 +
2
 +
3
 +
4
 +
done!
 +
f7
 +
i= 0
 +
i= 1
 +
-1
 +
i= 2
 +
-2
 +
-1
 +
done!
 +
 +
</pre></code>
 
<br />
 
<br />
 
<br />
 
<br />

Revision as of 14:47, 20 March 2010

--D. Thiebaut 17:15, 20 March 2010 (UTC)


from graphics import *

def f1( L ):
   L.sort()
   print L[0], L[1], L[len(L)/2], L[-2], L[-1]

def f2( x, y ):
   x = x + 3
   y = y - x
   return y, x

def f3():
    win = GraphWin( "midterm", 100, 100 )
    r = Rectangle( Point( 10, 10 ), Point( 20, 20 ) )
    r.draw( win )
    r.setFill( "black" )
    win.getMouse()
    win.close()

def f4():
    win = GraphWin( "midterm", 100, 100 )
    for x in range( 10, 60, 20 ):
       for y in range( 10, 60, 20 ):
          r = Rectangle( Point( x, y ), Point( x+10, y+10 ) )
          r.draw( win )
          r.setFill( "black" )
    win.getMouse()
    win.close()

def f5():
   L = [ ['a', 1, 10], ['b',1, 100], ['c', 3, 3], ['f', 4, 5], ['d', 2, 4] ]
   newL = []
   for name, val1, val2 in L:
      newL.append( [ val1/val2, name ] )
   newL.sort()
   val, name = newL[ 0 ]
   print "The item with the smallest relative value is", name

def f6():
   print "f6"
   for i in range( 3 ):
      print i
      for j in range( i+1 ):
         print i+j
   print "done!"

def f7():
   print "f7"
   for i in range( 3 ):
      print "i=", i
      for j in range( -i, 0 ):
         print j
   print "done!"


def f8():
   L = [ 
      #          1         2         3                  
      #012345678901234567890123456789012345
      "alpha               102       50",
      "beta                33        100",
      "gamma               160       22",
      "delta               100       34" ]
   newL = []
   for line in L:
      name = line[0:20].strip() # remove extra space
      num1 = int( line[20:30].strip() )
      newL.append( (num1, name) )
   newL.sort()
   print newL[-1][1]   # print 2nd item in last pair

def f9():
   print "f9()"
   print "0         1         2         3"
   print "012345678901234567890123456789012345"
   L = [ ("alpha", 102, 50), ( "beta", 33, 100), ("gamma", 160, -22), ("delta", 100, 340000 )]
   for name, v1, v2 in L:
      print "%-20s%-10d%-10d" % ( name, v1, v2 )

def main():
    #--- Pb 1 ---
    f1( [ 10, 3, -1, 2, 6, 11, 5]  )
    f1( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, -1] )

    #--- Pb 2 ---
    a = 10 # input( "a? " )
    b = 20 # input( "b? " )
    x, y = f2( a, b )
    print x, y

    f3()
    f4()
    
    f5()

    f6()
    f7()
    f8()
    f9()


main()

Output

f6
0
0
1
1
2
2
2
3
4
done!
f7
i= 0
i= 1
-1
i= 2
-2
-1
done!