Python Forum
comparing integers and fractions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
comparing integers and fractions
#1
I'm writing a script to get data from an aviation website. The problem is that, sometimes the value of 'visibility' could be an integer such as 10, but sometimes, the value of 'visibility' could be a fraction such as 10 3/4, or 10 1/2 depending on the visibility at the airport. Because of that, I'm getting an error when the value is a fraction. How can I fix this?

    for x in metar.split():
        if 'SM' in x:
            visibility = x.replace('SM', '')
            visibility = int(visibility)

        if 'SCT' in x or 'BKN' in x:
            ceiling = x.replace('SCT', '').replace('BKN', '')
            ceiling = int(ceiling)

    if visibility >= 10:
        flight_conditions = 'VFR'
        print(icao,name,flight_conditions)
    else:
        flight_conditions = 'IFR'
        print(icao,name,flight_conditions)
Quote: visibility = int(visibility)
ValueError: invalid literal for int() with base 10: '3/4'

I know I have
visibility = int(visibility)
, but how can I make it to accept fractions?
Reply
#2
(Oct-01-2019, 08:22 PM)tantony Wrote: The problem is that, sometimes the value of 'visibility' could be an integer such as 10, but sometimes, the value of 'visibility' could be a fraction such as 10 3/4, or 10 1/2 [ ... ] Because of that, I'm getting an error when the value is a fraction. How can I fix this?

Hi!

I've just had a similar problem with a very simple program, and then I learned that while for a whole number, as a string or not, the int() function returns the same value:
Output:
>>> int('3') 3 >>> int(3) 3
the same is not done, when the number is not a whole number:
Output:
>>> int(5.7) 5 >>> int('5.7')
Error:
Traceback (most recent call last): File "<pyshell#38>", line 1, in <module> int('5.7') ValueError: invalid literal for int() with base 10: '5.7'
So make the necessary modifications for the number to be used without the quotes.

Ah, also remember that if the numbers follow the format 10 3/4, that's also going to give you an error:
Output:
>>> int(10 3/4)
Error:
SyntaxError: invalid syntax
Output:
>>> int(10 * 3/4) 7
All the best,
newbieAuggie2019

"That's been one of my mantras - focus and simplicity. Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains."
Steve Jobs
Reply
#3
Just trying stupidly until it works Coffee

from fractions import Fraction


def to_float(value):
    value = value.strip() # remove whitespaces from left and right side
    try:
        value = float(value)
    except ValueError:
        # is not an float, trying next
        pass
    else:
        # is an float, just return it
        return value
    try:
        left, right = value.split()
        left = float(left)
        frac = Fraction(*map(int, right.split('/')))
    except ValueError:
        # hm, maybe only a fraction, let's try this
        pass
    else:
        # was ok, return it
        return left + frac
    try:
        frac = Fraction(*map(int, value.split('/')))
    except ValueError:
        # also not a single fraction
        pass
    else:
        return frac
Example:

Output:
In [26]: values = ['10 3/4', '10 1/2', '6', '42', 'garbage'] # parsed values as str In [27]: [to_float_or_int(v) for v in values] Out[27]: [Fraction(43, 4), Fraction(21, 2), 6, 42, None]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
I wrote a function that converts fractions to float, and so far it seems like its working. Similar to what DeaD_EyE had Big Grin

def fraction_to_float(num):
    if ' ' in num:
        convert = num.split(' ')
        fraction = convert[1].split('/')
        divide = float(fraction[0]) / float(fraction[1])
        divide = float(convert[0]) + divide
        return round(divide, 2)
    else:
        num = num
        return num

print(fraction_to_float('1 1/4'))
1.25


def fraction_to_float(num):
    if ' ' in num:
        convert = num.split(' ')
        fraction = convert[1].split('/')
        divide = float(fraction[0]) / float(fraction[1])
        divide = float(convert[0]) + divide
        return round(divide, 2)
    else:
        num = num
        return num

print(fraction_to_float('1'))
1
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  My program subtracts fractions, but for some reason isn't simplifying them RedSkeleton007 9 5,857 Mar-03-2018, 11:45 AM
Last Post: Gribouillis
  Logic error when comparing randomly generated integers SadoDeomeoon 5 4,662 Jun-05-2017, 02:38 PM
Last Post: SadoDeomeoon

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020