There are a few mistakes here, I will try to go over them one by one
Asking for the list
L=[int(x) for x in input("please enter a list:").split()]
This will throw a ValueError
when it gets fed a non-numeric type. This will also round any float
to int
Problem one can be solve by surrounding it with a while
loop and a try-catch block
while True:
try:
L=[int(x) for x in input("please enter a list:").split()]
break
except ValueError:
pass
The problem with the int
can be easily solved by changing int(x)
to float(x)
When using float
, beware of the nature of floating point numbers
Checking for arithmetic and geometric
In your solution, i
never gets incremented, so this only checks the first two values. Borrowing from @dex-ter's comment you can change this to
def is_arithmetic(l):
return all((i - j) == (j - k) for i, j, k in zip(l[:-2], l[1:-1], l[2:]))
For an explanation why on how this works, check the background of list splicing and zip
For is_geometric
you can easily adapt this solution.
This is also an excellent example where unittests
would've made this 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 only prints True or False is because that's what you tell your program to do. Your IsArithemeticOrGeometric()
has no return statement, so it always returns None
, which does not get printed. , so all the output comes from print(Arithemetic(L))
or print(Geometric(L))
A possible solution here would be something like 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))