okoro.russ
okoro.russ

Reputation: 1

is recursion the only solution to my algorithm implementation?

this is my task:

Create a function find_largest to implement the algorithm below

  1. Get a list of numbers L1, L2, L3....LN as argument
  2. Assume L1 is the largest, Largest = L1
  3. Take next number Li from the list and do the following
  4. If Largest is less than Li
  5. Largest = Li
  6. If Li is last number from the list then
  7. return Largest and come out
  8. Else repeat same process starting from step 3

and this is my code:

def get_algorithm_result(n):
  if type(n) == type([]):
    largest = n[0]
  for item in n:
    if largest < item:
      largest = item
    elif largest == n[-1]:
      return largest
    else:
      pass
  return largest

Although the code runs i haven't implemented step 8 which says i should repeat the same process starting from step 3. how can i do that

Upvotes: 0

Views: 138

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

You just need to use a for loop and keep track of the largest value seen as you iterate, updating the mx each time you encounter a larger element.

def get_algorithm_result(n):
    mx = n[0]
    for item in n[1:]:
        if item > mx:
            mx = item
    return mx

Your solution stops if elif largest == n[-1]: evaluates to True so for [1,2,3,4,1] you return 1 as the largest number which is incorrect. You reach L[-1] when the loops ends, checking if a number is == L[-1] does not mean that number is actually the last number in the list.

There is no need for recursion but if you wanted to implement it, the logic would be the same, you would have to look at every number:

def get_rec(n, mx):
    if not n:
        return mx
    return get_rec(n[1:],n[0]) if n[0] > mx else  get_rec(n[1:], mx)

You don't take the instructions literally:

def get_algorithm_result(n): 
        mx = n[0] # 2. Assume L1(n[0]) is the largest 
        for item in n[1:]:  # 3/8 get next number/ Else repeat same process starting from step 3
            if item > mx: 4 # If Largest is less than Li
                mx = item # 5 Largest = Li
        return mx # 6/7 If Li is last number from the list then return Largest and come out

Upvotes: 1

Related Questions