Skip to content Skip to sidebar Skip to footer

Initializing Integer Variables For Comparisons

I'm working my way through the MIT Open Courseware class Introduction to Computer Science and Programming in Python and I've spent an embarrassing amount of time trying to wrap my

Solution 1:

None seems fine if you're going to do it this way. (I'd say it's safer than using a large negative number.) You can get round the code duplication with None as e.g.

if largest isNoneor y > largest:
    largest = y

Couple of things, compare to None with is. Second, if the first part of an or is True, the second part won't be executed (called short-circuiting), so you won't get an error trying to compare a None using >.

Solution 2:

Or don't initialize it at all - just keep a Boolean to keep track of whether an odd number has been found yet.

still_looking = Trueif x % 2:
    largest, still_looking = x, Falseif y % 2and (still_looking or y > largest):
    largest, still_looking = y, Falseif z % 2and (still_looking or z > largest):
    largest, still_looking = z, Falseif still_looking:
    print('There are no odd numbers.')
else:
    print('The largest odd number is', largest)

The repetitious code at the start then screams to be replaced with a uniform loop:

still_looking = True
forvalin x, y, z:
    ifval % 2 and (still_looking or val > largest):
        largest, still_looking = val, False

Solution 3:

I guess using a very large negative number, to make sure you're good. doing something like :

largest = -float('inf')

and by the end checking this :

if largest == -float('inf'):
  print("There are no odd numbers")
else:
  print(largest)

Solution 4:

I would do:

x=int(input('Enter your first number:'))
y=int(input('Enter your second number:'))
z=int(input('Enter your third number:'))

li=[e for e in (x,y,z) if e % 2]   # find all odd numbers from x,y,zprint('{} is largest odd number'.format(max(li)) if li else'all input even')

This works because an empty container in Python is False and the list li will be empty if there are no odd numbers. You can use max to find the largest odd number if there are any and the Python ternary of [if true clause] if [boolean test] else [what do do otherwise]

You can do the same thing this way:

li=[e for e in (x,y,z) if e % 2]
if li:
    print ('The largest odd number is', max(li))
else:
    print ('There are no odd numbers.') 

If you don't want to use the max function, you can write your own:

defmymax(li):
    max_=Noneif li:
        max_=li[0]
    for e in li:
        if e>max_: max_=e
    return max_     

Solution 5:

Instead of putting:

largest = None

you should put:

largest = -1 * sys.maxsize + 1

Post a Comment for "Initializing Integer Variables For Comparisons"