0

I am trying to write a function that accepts list as an argument to my gcd function. Would something like this work?

def find_my_gcd(a_list):
    def gcd (x,y):
        while y!=0:
             x,y=y,x%y
        return x

Now,how do I make my gcd function step through a list,i.e a_list=[12,24,18,6], iterate through gcd(12,24), gcd(12,18),gcd(12,6) and returns a single value.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
R.abdhir
  • 75
  • 1
  • 4

1 Answers1

0

you have to keep the current value in a variable, and use that with the next value in the list, something like this

def find_my_gcd(a_list):
    def gcd (x,y):
        while y!=0:
            x,y=y,x%y
        return x
    acum = a_list[0]
    for e in a_list[1:]:
        acum = gcd(acum,e)
    return acum

you can also use reduce to keep the acumulated for you

def find_my_gcd(a_list):
    def gcd (x,y):
        while y!=0:
            x,y=y,x%y
        return x
    return reduce(gcd,a_list)

also you can find gcd in the math.gcd library in python 3.5+ and in previous versions is in fractions.gcd library so the your function can be reduced to

from functools import reduce
from math import gcd # from fractions import gcd in 3.4 or previous

def find_my_gcd(a_list):
    return reduce(gcd,a_list)
Copperfield
  • 8,131
  • 3
  • 23
  • 29