pythoniterationencapsulationgeneralization

Encapsulation and generalization function def mult_tasks(str_numbers) in python


The Question:

Without altering mult_tasks, write a definition for mult_tasks_line so that the doctests pass.
So:

print mult_tasks("3469") will 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 your 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 any code in this function
    result_tasks = ""
    for 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 already tried doing this:

def mult_tasks_line(first_num, str_numbers):
    digits=0
    for 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 = ""
    for ch in str_numbers:
        result_tasks += mult_tasks_line(ch, str_numbers),"\n"
    return result_tasks

This is what I tried, the first function works pretty close, but it does not have the single quote. when run mult_tasks_line("4", "3469”) it comes out (4*3) (4*4) (4*6) (4*9).

But the second function seems totally wrong. this is the result for the 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' and 'tuple' objects

Solution

  • Obviously mult_tasks contains an incorrect line

    result_tasks += mult_tasks_line(ch, str_numbers),"\n"
    

    result_tasks is a string and here it is concatenated with a tuple (They are constructed by commas with or without parentheses) mult_tasks_line(ch, str_numbers), "\n" which leads to exception.

    You need to modify this line to

    result_tasks += mult_tasks_line(ch, str_numbers) + "\n"
    

    Another problem in your code, is that mult_tasks_line doesn't return value, but simply prints it. You want to do something like this

    def mult_tasks_line(first_num, str_numbers):
        result = []
        for ch in str_numbers:
            result.append('({}*{})'.format(first_num, ch))
        return ' '.join(result)