上述代码报错invalid literal for int() with base 10: '1.5'
时间: 2023-08-10 11:19:50 浏览: 72
Python ValueError: invalid literal for int() with base 10 实用解决方法
很抱歉,这是因为输入的距离值是浮点数,而代码中使用了int()转换为整数,导致报错。我们可以将这一行代码修改为:
```
v1, v2, weight = input('请输入存在路径的两个单位以及相通两个单位间的距离(用空格隔开):').split()
v1, v2, weight = int(v1), int(v2), float(weight)
```
将weight的类型改为浮点数即可。修改后的完整代码如下:
```
class Graph:
def __init__(self, n, e):
self.n = n
self.e = e
self.arc = [[float('inf')]*n for _ in range(n)]
self.freq = [0]*n
self.name = ['']*n
def add_edge(self, v1, v2, weight):
self.arc[v1][v2] = weight
self.arc[v2][v1] = weight
def set_freq(self, v, freq):
self.freq[v] = freq
def set_name(self, v, name):
self.name[v] = name
def floyd(graph):
n = graph.n
arc = graph.arc
for k in range(n):
for i in range(n):
for j in range(n):
if arc[i][j] > arc[i][k] + arc[k][j]:
arc[i][j] = arc[i][k] + arc[k][j]
return arc
n = int(input('请输入图中顶点个数:'))
e = int(input('请输入图中边的条数:'))
t = Graph(n, e)
for i in range(n):
name = input('请输入第%d个单位的名称:' % (i+1))
t.set_name(i, name)
freq = int(input('请输入第%d个单位的去超市的频度:' % (i+1)))
t.set_freq(i, freq)
for i in range(e):
v1, v2, weight = input('请输入存在路径的两个单位以及相通两个单位间的距离(用空格隔开):').split()
v1, v2, weight = int(v1), int(v2), float(weight)
t.add_edge(v1, v2, weight*t.freq[v2])
arc = floyd(t)
min_row = float('inf')
min_row_index = 0
for i in range(n):
row_sum = sum(arc[i])
if row_sum < min_row:
min_row = row_sum
min_row_index = i
print('学校超市最佳选址是:', t.name[min_row_index])
```
希望这次修改能够解决问题。如果还有其他疑问,欢迎随时提出。
阅读全文