1

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)?

Luke Sharon
  • 140
  • 1
  • 7
  • 22
  • 3
    Does the value need to be an `int`? `float('inf')` will compare larger than any `int` value. – chepner Nov 28 '20 at 19:14
  • 1
    Does this answer your question? [How can I represent an infinite number in Python?](https://stackoverflow.com/questions/7781260/how-can-i-represent-an-infinite-number-in-python) – Pablo C Nov 28 '20 at 19:30
  • 2
    There are different wait to represent infinity. Aside from that, you should separate your display from your computation/dataframe. There is no need to code infinity in the computation/dataframe as the string '-' for esthetics. You can code it as an infinity as math.inf or float('inf') and then display it as whatever you want. – Mathieu Nov 28 '20 at 19:31

2 Answers2

3

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
ti7
  • 16,375
  • 6
  • 40
  • 68
1

String "-" is not infinity even you mean it. In Python, you can obtain the type in two ways:

float("inf")

or

import math
math.inf

Your problem is not related to the usage or use cases of infinity type, but it is the representation issue. I believe you should use the normal infinity type in your math and create a property in your class that returns "-" and then use it only when you need to represent it on UI but not in your math.

The issue that you have is more about the decoupling of representation and logic.

I159
  • 29,741
  • 31
  • 97
  • 132