# Osum0 else osum0 for x in rangelensquare

• 7
• 100% (1) 1 out of 1 people found this document helpful

This preview shows page 5 - 7 out of 7 pages.

o_sum=0else:o_sum=0for x in range(len(square)):o_sum=o_sum+square[x][x]if o_sum != f_sum:check_number=1o_sum=0else:o_sum=0for x in range(len(square)):o_sum=o_sum+square[len(square)-x-1][x]if o_sum!=f_sum:check_number=1else:o_sum = 0if check_number==0:print("It's a magic square")else:print("It's not a magic square")checkmagic(matrix)Notethat the sum of each of the rows, columns, and diagonals is 15. This square is not unique. If you flip the rows for the columns (transpose the square) you will get amagic square. If you add a constant value to each element you will get a magic square, and so on.Part 2 – Recursion [14 points, 7 points each] When we multiply x * y, where x > 0 and y > 0, we are simply adding x a total ofy times. We can define x * y recursivelyas follows:x * y = x, if y = 1x * y = x + x*(y-1), if y > 1Complete the following Python program to compute num1 * num2 recursivelydef main():# Local variablesnum1 = 0num2 = 05 | am/cpsc111-F18-Asg3.docx Assigned: Saturday Nov. 3, 2018:
CPSC111-Introduction to computing By Dr. Ahmed Malki – Asg. #3 (Fall-2018)# Get the first positive nonzero integer from# user.while num1 <= 0:num1 = int(input("number1="))# Get the second positive nonzero integer from # user.while num2 <= 0:num2 = int(input("number2="))# Call the multiply function to compute num1 * num2 recursively, # and display the product.print(multiply(num1,num2))def multiply(num_1,num_2):# You complete this function recursivelyif num_2==1:return num_1if num_2>1:return num_1+multiply(num_1,num_2-1)main() We can determine how many digits a positive integer has by repeatedly dividing by 10 (without keeping the remainder) until the number is less than 10, consisting of only 1 digit. We add 1 to this value for each time we divided by 10. Here is the recursivealgorithm:1. If n < 10 return 1.2. Otherwise, return 1 + the number of digits in n/10 (ignoring the fractional part).Implement this recursivealgorithm in Python and test it using a main function thatcalls this with the values 715, 747745, and 17711. (HINT: Remember that if n is an integer, n/10 will be an integer without the fractional part.)
• • • 