Question

In: Computer Science

The functions are tested in the following main(): def recSum1(somelist): if len(somelist) == 1: return somelist[0]...

The functions are tested in the following main():

def recSum1(somelist):
    if len(somelist) == 1:
        return somelist[0]
    else:
        a = recSum1(somelist[:len(somelist)//2])
        b = recSum1(somelist[len(somelist)//2:])
        return a + b

def recSum2(somelist):
    if len(somelist) == 1:
        return somelist[0]
    else:
        return somelist[0] + recSum2(somelist[1:])
import random

def main():
    N = 100
    myList = [random.randint(-500, 500) for i in range(N)]

    print(myList)
    print("The sum of the numbers is: " + str(sum(myList)))
    print("The sum of the numbers using recSum1 is: " + str(recSum1(myList)))
    print("The sum of the numbers using recSum2 is: " + str(recSum2(myList)))

if __name__ == "__main__":
    main()

1. Using the recSum1() function as a template, create a recursive function that will find the minimum value of the values in a list. The minimum value is the smaller of minimums of the two halves. You will need to modify the main to test your new function.

2. Create a recursive function that will compute xn, (x to the nth power) where n is an integer. If n is an integer, then the xn can be defined as:

This means that, if you compute recursive x to the half of n, then the answer is that result times itself if n is even, or the answer is that result times itself times x if n is odd.

Solutions

Expert Solution

Problem 1:

The following is the code for above question. It involves the concept of divide and conquer where we can reduce the time complexity to log n.

def find_min(l,left,right,min): #here left and right indicates the positions of elements in the list
  if left==right:  #if left and right elements are equal
    if min>l[right]:
      min=l[right]
    return min
  if right-left==1:        
    if l[left]<l[right]:  # If the element at left is less than the element at right
      if min>l[left]:   
        min=l[left]
    else:
      if min>l[right]:  # If min is greater the element at the right of list
        min=l[right]
  mid=(left+right)//2  #mid is nothing but the element at half of the list
  a=find_min(l,left,mid,min) #find the min for the first half of the list
  b=find_min(l,mid+1,right,min) #find the min for the last half of the list
  if a>b: #compare minimum among a and b
    min=b
  else:
    min=a
  return min  #return min
l=[4,3,6,2,8,2,8]
find_min(l,0,len(l)-1,l[0])

Output and Screenshots:

Problem 2:

The following is the code for above question. It also involves the concept of divide and conquer.

def power(x,n):
  if n==0:  #if n is 0, return 1 i.e any number power 0 is 1
    return 1
  if x==0:  #if any number is 0, then result will be 0. i.e 0 power anything is 0
    return 0
  if n%2==0:  # if power is even, then the answer is that result times itself 
    return power(x*x,n//2)
  else:  #else, n is odd, then answer is that result times itself times x 
    return x*power(x*x,n//2)

if __name__=="__main__":
  p=power(3,5)
  print("The result x^n is: "+str(p)) #print the result

Output and Screenshots:

#Please dont forget to upvote if you find the solution helpful. Feel free to ask doubts if any, in the comments section. Thank you.


Related Solutions

def myLength(mylist):    count = 0    for index in range(len(myList)):        print(myList[index])       ...
def myLength(mylist):    count = 0    for index in range(len(myList)):        print(myList[index])        count = count + 1    return count def myLength2(mylist):    count = 0    for element in myList:        print(element)        count = count + 1    return count       Use these two functions as examples to write your Python function below! Function 1: Write a function called myCount that takes in two parameters (a list and an item) like...
def annoying_factorial(n): if n == 0 or n == 1: return 1 if n == 2:...
def annoying_factorial(n): if n == 0 or n == 1: return 1 if n == 2: return 2 if n == 3: return 6 if n == 4: return 4 * annoying_factorial(3) if n == 5: return 5 * annoying_factorial(4) if n == 6: return 6 * annoying_factorial(5) else: return n * annoying_factorial(n-1) def annoying_fibonacci(n): if n==0: return 0 if n==1: return 1 if n==2: return 1 if n==3: return 2 if n==4: return annoying_fibonacci(4-1)+annoying_fibonacci(4-2) if n==5: return annoying_fibonacci(5-1)+annoying_fibonacci(5-2) if...
def longest(string): start=0;end=1;i=0; while i<len(string): j=i+1 while j<len(string) and string[j]>string[j-1]: j+=1 if end-start<j-i: #update if current...
def longest(string): start=0;end=1;i=0; while i<len(string): j=i+1 while j<len(string) and string[j]>string[j-1]: j+=1 if end-start<j-i: #update if current string has greater length than #max start and end end=j start=i i=j; avg=0 for i in string[start:end]: avg+=int(i) print('The longest string in ascending order is',string[start:end]) print('Teh average is',avg/(end-start)) s=input('Enter a string') longest(s) i need a definition and explanation of this code that how it works?
def check(s): #Conditions applied 1,5,6 if len(s)=9 and s[0].isupper() and s[-1].isdigit(): upper_count = sum(1 for c...
def check(s): #Conditions applied 1,5,6 if len(s)=9 and s[0].isupper() and s[-1].isdigit(): upper_count = sum(1 for c in s if c.isupper()) lower_count = sum(1 for c in s if c.islower()) number_count = sum(1 for c in s if c.isdigit()) #Conditions 2,3,4 if upper_count=3 and lower_count==3 and number_count==3: #Condition 7 { Two consecutive alphabets can’t be small } for i in range(1,len(s)): if s[i-1].islower() and s[i].islower() : return 'reject' else: return 'reject' #All conditions satisfies here, so accept return 'accept' else: return...
def anagramSolution1(s1,s2): alist = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and...
def anagramSolution1(s1,s2): alist = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and stillOK: pos2 = 0 found = False while pos2 < len(alist) and not found: if s1[pos1] == alist[pos2]: found = True else: pos2 = pos2 + 1 if found: alist[pos2] = None else: stillOK = False pos1 = pos1 + 1 return stillOK include all operations and calculate the Big-O and the values for c and n0.
def mystery(L, x): if L==[]: return False if L[0] == x: return True L.pop(0) return mystery(L,...
def mystery(L, x): if L==[]: return False if L[0] == x: return True L.pop(0) return mystery(L, x) What is the input or length size of the function mystery? What is the final output of mystery([1,3,5,7], 0)? Explain in one sentence what mystery does? What is the smallest input that mystery can have? Does the recursive call have smaller inputs? Why? Assuming the recursive call in mystery is correct, use this assumption to explain in a few sentences why mystery is...
def main():     # keeping asking user for a word or name until user enters 0    ...
def main():     # keeping asking user for a word or name until user enters 0     while True:         word = input('Enter a word/name to convert (enter 0 to quit): ').upper()       if word == '0': break         print(convert_to_soundex(word)) Whenever i try to run the program it tells me unintend doesn't match any outer identation level !!!!
Exercise: Write a program named factorial.py that contains the following two functions: def while_factorial(num) def for_factorial(num)...
Exercise: Write a program named factorial.py that contains the following two functions: def while_factorial(num) def for_factorial(num) These should calculate the factorial of a given number represented by the argument num using a while loop and a for loop respectively.
Inheritance - Method Calls Consider the following class definitions. class C1(): def f(self): return 2*self.g() def...
Inheritance - Method Calls Consider the following class definitions. class C1(): def f(self): return 2*self.g() def g(self): return 2 class C2(C1): def f(self): return 3*self.g() class C3(C1): def g(self): return 5 class C4(C3): def f(self): return 7*self.g() obj1 = C1() obj2 = C2() obj3 = C3() obj4 = C4() For this problem you are to consider which methods are called when the f method is called. Because the classes form part of an inheritance hierarchy, working out what happens will...
Inheritance - Method Calls Consider the following class definitions. class C1(): def f(self): return 2*self.g() def...
Inheritance - Method Calls Consider the following class definitions. class C1(): def f(self): return 2*self.g() def g(self): return 2 class C2(C1): def f(self): return 3*self.g() class C3(C1): def g(self): return 5 class C4(C3): def f(self): return 7*self.g() obj1 = C1() obj2 = C2() obj3 = C3() obj4 = C4() For this problem you are to consider which methods are called when the f method is called. Because the classes form part of an inheritance hierarchy, working out what happens will...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT