python - Turning my function into a class -


i have function works how want to, course work, have turn function class that:

  • must have function called solveit,
  • returns following 2 values:
    • a boolean true if you've solved knapsack problem, and
    • the knapsack object correct values in it.

the class must have __str__() function returns string this. first line size, , second comma-separated list of elements:

10 4,1,9,2,0,4,4,4,3,7 

i dont understand classes well, appreciated. here function have right now:

from itertools import combinations  def com_subset_sum(seq, target):     if target == 0 or target in seq:         print(target)         return true      r in range(len(seq),1,-1):         subset in combinations(seq, r):             if sum(subset) == target:                 print(subset)                 return true     return false  print(com_subset_sum([4,1,9,2,0,4,4,4,3,7],10)) 

one obvious way transform function class turn function parameters (or of them) object attributes. example:

class knapsack(object):     def __init__(self, seq, target):         self.seq = seq         self.target = target         self.solution = none     def solveit(self):         if self.target == 0 or self.target in self.seq:             self.solution = (target,)             return true, self.solution         r in range(len(self.seq),1,-1):             subset in combinations(self.seq, r):                 if sum(subset) == self.target:                    self.solution = subset                    return true, self.solution         return false, () 

now can this:

>>> knapsack = knapsack([4,1,9,2,0,4,4,4,3,7],10) >>> print(knapsack.solveit()) (true, (4, 1, 2, 0, 3)) 

and then, adding __str__ method simple:

def __str__(self):     if self.solution none:         self.solveit()     return '{}\n{}'.format(len(self.seq),                             ','.join(map(str, self.solution))) 

the reason added self.solution calling __str__ on , on won't keep calculating results on , over. drop member , write this:

def __str__(self):     solved, solution = self.solveit()     return '{}\n{}'.format(len(self.seq),                             ','.join(map(str, solution))) 

either way, i'm not sure how better function. (in fact, it's strictly worse: function, can use functools.partial bind in sequence, or both sequence , target, or of course bind in neither, whereas class, have bind in both.)

maybe professor has given kind of hints on how you'd want use object might help? or maybe professor idiot doesn't know how come motivating assignment teaching classes…


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -