elDucUrraca elDucUrraca - 1 year ago 73
Python Question

Comparing tuple to int on Python

I'm traing to compare the components of an tuple in Python to find bigest and the smallest, but my code just returns the two latest components of the touple, and I have no idea why:

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers2=numbers.split()
numbers2=tuple(numbers2)
i=0
gran=numbers2[0]
petit=numbers2[0]
for i in range (len(numbers2)):
if numbers2[i]>gran:
gran=numbers2[i]
print(gran)
j=0
for j in range (len(numbers2)):
if numbers[j]<petit:
petit=numbers2[j]
print(petit)
resultat= gran+" "+petit
print(resultat)


I got "6 -6" in return. Any help? Thanks

Answer Source

Convert your splitted string into integers before turning it into a tuple.

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers2=[int(x) for x in numbers.split()]
numbers2=tuple(numbers2)
...

You can also merge those two operations into a single line.

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers2=tuple([int(x) for x in numbers.split()])
...