Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168694
Image: ubuntu2004

Mack Talcott

MATH480 Spring 2010

Homework 3

Problem 1

def remove_duplicates(l): result = [] for i in l: if not i in result: result.append(i) return result
remove_duplicates([3, 2, 1, [3], 2, [3], 5, 5, 5])
[3, 2, 1, [3], 5]

Problem 2

@interact def interact_print_table(f, ls): if not f or not ls: return print_table(f, ls) #specify function and list below after evaluating this cell
ls 
[removed]
[removed]
[removed]
[removed]

Problem 4

My solution doesn't work in Sage.  Change the type of the worksheet above to python before evaluating this problem, or run the file included in the email.

# DOESN'T WORK IN SAGE! def square_cube_prover(n): sum_to_square = 0 cubed_sum = 0 for i in xrange(1, n+1): sum_to_square += i cubed_sum += i**3 square = sum_to_square**2 if not square == cubed_sum: print "OH NO! (1 + ... + %i)^2 = %i; 1^3 + ... + %i^3 = %i!" % (i, square, i, cubed_sum) return if i % (n/10) == 0: # print progress every 10% of the way through print "True for 1 through %i" % (i)
square_cube_prover(2000)
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "_sage_input_8.py", line 9, in <module> exec compile(ur'open("___code___.py","w").write("# -*- coding: utf-8 -*-\n" + _support_.preparse_worksheet_cell(base64.b64decode("c3F1YXJlX2N1YmVfcHJvdmVyKDIwMDAp"),globals())+"\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single') File "", line 1, in <module> File "/tmp/tmpc3EGFg/___code___.py", line 3, in <module> exec compile(ur'square_cube_prover(_sage_const_2000 )' + '\n', '', 'single') File "", line 1, in <module> File "/tmp/tmpG7iPOB/___code___.py", line 13, in square_cube_prover if i % (n/_sage_const_10 ) == _sage_const_0 : File "rational.pyx", line 2290, in sage.rings.rational.Rational.__mod__ (sage/rings/rational.c:16853) TypeError: Argument 'self' has incorrect type (expected sage.rings.rational.Rational, got int)

Problem 5

To test that the contents of the log file are right, I'd just run the file included in the email.

class file_logger(object): def __init__(self, filename): self.__log = open(filename, "a") def __call__(self, f): def g(*args, **kwds): input = "args = %s; kwds = %s" % (repr(*args or None), str(**kwds)) output = repr(f(*args, **kwds)) self.__log.write("function: %s\ninput:\n%s\noutput:\n%s\n\n" % (f.__name__, input, output)) self.__log.flush() return g my_logger = file_logger("test_log.txt") @my_logger def f(input): return "THIS IS MY OUTPUT FOR INPUT '%s'" % str(input)