iteration - Encapsulation and generalization function def mult_tasks(str_numbers) in python -
the question:
without altering mult_tasks, write definition mult_tasks_line doctests pass.
 so:
print mult_tasks("3469")  produce:
(3*3) (3*4) (3*6) (3*9) (4*3) (4*4) (4*6) (4*9) (6*3) (6*4) (6*6) (6*9) (9*3) (9*4) (9*6) (9*8)   def mult_tasks_line(first_num, str_numbers):      """     >>> mult_tasks_line("4", "3469")     '(4*3) (4*4) (4*6) (4*9) '     """     #add code here  def mult_tasks(str_numbers):      """     >>> mult_tasks("246")     '(2*2) (2*4) (2*6) \\n(4*2) (4*4) (4*6) \\n(6*2) (6*4) (6*6) \\n'     >>> mult_tasks("1234")     '(1*1) (1*2) (1*3) (1*4) \\n(2*1) (2*2) (2*3) (2*4) \\n(3*1) (3*2) (3*3) (3*4) \\n(4*1) (4*2) (4*3) (4*4) \\n'     """      #do not alter code in function     result_tasks = ""     ch in str_numbers:         result_tasks += mult_tasks_line(ch, str_numbers) + "\n"     return result_tasks   if __name__ == "__main__":     import doctest     doctest.testmod(verbose = true)   i have tried doing this:
def mult_tasks_line(first_num, str_numbers):     digits=0     num in str_numbers:         while digits<len(str_numbers):             print "("+first_num+"*"+str_numbers[digits]+")",             digits=digits+1  def mult_tasks(str_numbers):     result_tasks = ""     ch in str_numbers:         result_tasks += mult_tasks_line(ch, str_numbers),"\n"     return result_tasks   this tried, first function works pretty close, not have single quote. when run  mult_tasks_line("4", "3469”)  comes out (4*3) (4*4) (4*6) (4*9). 
but second function seems totally wrong. result second function :
mult_tasks("246”)
(2*2) (2*4) (2*6)   traceback (most recent call last): file "<pyshell#1>", line 1, in <module> mult_tasks("246") file "/users/huesfile/downloads/mastery test/2.py", line 25, in mult_tasks result_tasks += mult_tasks_line(ch, str_numbers),"\n"  typeerror: cannot concatenate 'str' , 'tuple' objects      
obviously mult_tasks contains incorrect line
result_tasks += mult_tasks_line(ch, str_numbers),"\n"   result_tasks string , here concatenated tuple (they constructed commas or without parentheses) mult_tasks_line(ch, str_numbers), "\n" leads exception.
you need modify line
result_tasks += mult_tasks_line(ch, str_numbers) + "\n"   another problem in code, mult_tasks_line doesn't return value, prints it. want this
def mult_tasks_line(first_num, str_numbers):     result = []     ch in str_numbers:         result.append('({}*{})'.format(first_num, ch))     return ' '.join(result)      
Comments
Post a Comment