arithmetic or geometric sequence in python -


do know how can write code in python including function takes list , find out if arithmetic or geometric? wrote code boolean , doesn't arithmetic or geometric , has output.

l=[int(x) x in input("please enter list:").split()]  def arithemetic(l):   i=1   if(l[0]+l[i]==l[i+1]):     return true   i+=1  def geometric(l):   i=1   if(l[0]*l[i]==l[i+1]):     return true   i+=1  def isarithemeticorgeometric(l):   if(arithemetic(l)):     print(arithemetic(l))   elif(geometric(l)):     print(geometric(l))  print(isarithemeticorgeometric(l)) 

there few mistakes here, try go on them 1 one

asking list

l=[int(x) x in input("please enter list:").split()] 

this throw valueerror when gets fed non-numeric type. round float int

problem 1 can solve surrounding while loop , try-catch block

while true:     try:         l=[int(x) x in input("please enter list:").split()]         break     except valueerror:         pass 

the problem int can solved changing int(x) float(x)

when using float, beware of the nature of floating point numbers

checking arithmetic , geometric

in solution, i never gets incremented, checks first 2 values. borrowing @dex-ter's comment can change to

def is_arithmetic(l):     return all((i - j) == (j - k) i, j, k in zip(l[:-2], l[1:-1], l[2:])) 

for explanation why on how works, check background of list splicing , zip

for is_geometric can adapt solution.

this excellent example unittests would've made error clear

assert is_geometric((1,2)) assert is_geometric((1,2, 4)) assert is_geometric((1,2, 4, 8)) assert not is_geometric((1,2, 4, 9)) try:     is_geometric((1, 2, 'a'))     raise assertionerror('should throw typeerror') except typeerror:     pass 

the result

your result prints true or false because that's tell program do. isarithemeticorgeometric() has no return statement, returns none, not printed. , output comes print(arithemetic(l)) or print(geometric(l))

a possible solution here this:

def is_arithmetic_or_geometric(l):     if is_arithmetic(l):         return 'arithmetic'     if is_geometric(l):         return 'geometric'  print(is_arithmetic_or_geometric(l)) 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -