Warm tip: This article is reproduced from serverfault.com, please click

How to use infinity in python

发布于 2020-11-28 19:12:11

I am working with graphs in python. I am trying to get the distance between each vertex. I need to use the value INFINITY (represented using the string "-") for a situation in which there is no direct path between one vertex and another. I tried a couple of solutions. One was using a crazy large int to represent infinity. However, I researched and found that this is poor practice. I also saw several solutions on stack overflow that made use of the math module's infinity function. However, this is not appropriate for my problem, as my INFINITY value is being used in a UI and must look graphically pleasing. This is why my INFINITY must remain as the string "-". This is the error I am getting with my current line of code:

TypeError: '<' not supported between instances of 'str' and 'int'

I am not completely sure, but I think the < is coming from my use of the min() function.

This error is coming from the following code:

for i in range(length):
    for j in range(length):
        for k in range(length):
            #print('40:', int(temp[j][i]), int(temp[i][k]))
            temp[j][k] = min(temp[j][k], addWithInfinity(temp[j][i],temp[i][k]))

Temp just refers to a matrix which I received as an argument in the method I am currently working with. Here is my addWithInfinity method:

def addWithInfinity(a, b):
"""If a == INFINITY or b == INFINITY, returns INFINITY.
Otherwise, returns a + b."""
if a == LinkedDirectedGraph.INFINITY or b == LinkedDirectedGraph.INFINITY:
    return LinkedDirectedGraph.INFINITY
else: return a + b

My issue is that I am trying to compare infinity with an int. I tried to convert INFINITY to an int like this: int(INFINITY) ( or int('-') ) but I got the following error:

ValueError: invalid literal for int() with base 10: '-'

Any ideas how I can get away with the comparison between an int and INFINITY (which is a string)?

Questioner
Luke Sharon
Viewed
0
ti7 2020-11-29 03:40:54

Use float("inf") or math.inf

See also How can I represent an infinite number in Python?

>>> float("inf") > 5
True
>>> float("inf") < 10**100
False
>>> import math
>>> float("inf") == math.inf
True

If you need to use some other value than "inf" for infinity, such as '-' in your example, you could try/except it, either

  • checking if the initial value is your target string (if a == '-':)
  • parsing the error calling float on it (if "'-'" in str(err_string):)
try:
    a = float(a)
except ValueError as ex:
    # special-case for ValueError: could not convert string to float: '-'
    if "'-'" in str(ex).split(":")[-1]:
        a = float("inf")
    else:  # re-raise other ValueErrors
        raise ex