- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在使用 dijkstra 时遇到了这个错误:TypeError:不可排序的类型:Vertex() < Vertex()
整个错误日志是:
Theo dõi (cuộc gọi gần đây nhất là cuộc gọi cuối cùng):
File "C:/Users/Dimitar/PycharmProjects/Dijkstra/Dijkstra.py", line 165, in
dijkstra(g, g.get_vertex('a'))
File "C:/Users/Dimitar/PycharmProjects/Dijkstra/Dijkstra.py", line 101, in dijkstra
heapq.heapify(unvisited_queue)
TypeError: unorderable types: Vertex() < Vertex()
Đây là mã của tôi:
nhập khẩu hệ thống
class Vertex:
def __init__(self, node):
self.id = node
self.adjacent = {}
# Set distance to infinity for all nodes
self.distance = sys.maxsize
# Mark all nodes unvisited
self.visited = False
# Predecessor
self.previous = None
def add_neighbor(self, neighbor, weight=0):
self.adjacent[neighbor] = weight
def get_connections(self):
return self.adjacent.keys()
def get_id(self):
return self.id
def get_weight(self, neighbor):
return self.adjacent[neighbor]
def set_distance(self, dist):
self.distance = dist
def get_distance(self):
return self.distance
def set_previous(self, prev):
self.previous = prev
def set_visited(self):
self.visited = True
def __str__(self):
return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent])
class Graph:
định nghĩa __init__(bản thân):
self.vert_dict = {}
self.num_vertices = 0
def __iter__(self):
return iter(self.vert_dict.values())
def add_vertex(self, node):
self.num_vertices = self.num_vertices + 1
new_vertex = Vertex(node)
self.vert_dict[node] = new_vertex
return new_vertex
def get_vertex(self, n):
if n in self.vert_dict:
return self.vert_dict[n]
khác:
return None
def add_edge(self, frm, to, cost=0):
if frm not in self.vert_dict:
self.add_vertex(frm)
if to not in self.vert_dict:
self.add_vertex(to)
self.vert_dict[frm].add_neighbor(self.vert_dict[to], cost)
self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)
def get_vertices(self):
return self.vert_dict.keys()
def set_previous(self, current):
self.previous = current
def get_previous(self, current):
return self.previous
def shortest(v, path):
''' make shortest path from v.previous'''
if v.previous:
path.append(v.previous.get_id())
shortest(v.previous, path)
trở lại
import heapq
# noinspection PyArgumentList
def dijkstra(aGraph, start):
print('''Dijkstra's shortest path''')
# Set the distance for the start node to zero
start.set_distance(0)
# Put tuple pair into the priority queue
unvisited_queue = [(v.get_distance(), v) for v in aGraph]
heapq.heapify(unvisited_queue)
while len(unvisited_queue):
# Pops a vertex with the smallest distance
uv = heapq.heappop(unvisited_queue)
current = uv[1]
current.set_visited()
for next in current.adjacent:
# if visited, skip
if next.visited:
Tiếp tục
new_dist = current.get_distance() + current.get_weight(next)
if new_dist < next.get_distance():
next.set_distance(new_dist)
next.set_previous(current)
in
('updated : current = %s next = %s new_dist = %s' \
% (current.get_id(), next.get_id(), next.get_distance()))
khác:
in
('not updated : current = %s next = %s new_dist = %s' \
% (current.get_id(), next.get_id(), next.get_distance()))
# Rebuild heap
# 1. Pop every item
while len(unvisited_queue):
heapq.heappop(unvisited_queue)
# 2. Put all vertices not visited into the queue
unvisited_queue = [(v.get_distance(), v) for v in aGraph if not v.visited]
heapq.heapify(unvisited_queue)
nếu __name__ == '__main__':
g = Graph()
g.add_vertex('a')
g.add_vertex('b')
g.add_vertex('c')
g.add_vertex('d')
g.add_vertex('e')
g.add_vertex('f')
g.add_edge('a', 'b', 7)
g.add_edge('a', 'c', 9)
g.add_edge('a', 'f', 14)
g.add_edge('b', 'c', 10)
g.add_edge('b', 'd', 15)
g.add_edge('c', 'd', 11)
g.add_edge('c', 'f', 2)
g.add_edge('d', 'e', 6)
g.add_edge('e', 'f', 9)
in
('Graph data:')
for v in g:
for w in v.get_connections():
vid = v.get_id()
wid = w.get_id()
in
('( %s , %s, %3d)' % ( vid, wid, v.get_weight(w)))
dijkstra(g, g.get_vertex('a'))
target = g.get_vertex('e')
path = [target.get_id()]
shortest(target, path)
print('The shortest path : %s' % (path[::-1]))
有人能解释一下为什么会出现这种错误吗?我是一个自学者,我将不胜感激。
导致错误的代码行是:heapq.heapify(unvisited_queue)
提前感谢所有对此主题发表评论的人。
最好的,迪米塔尔
câu trả lời hay nhất
自定义类型不会隐式定义其实例之间的顺序:
>>> v1 = Vertex(1)
>>> v2 = Vertex(2)
>>> v1 < v2
Theo dõi (cuộc gọi gần đây nhất là cuộc gọi cuối cùng):
Tệp "", dòng 1, trong
TypeError: unorderable types: Vertex() < Vertex()
你需要告诉 python 如何比较你的顶点。您需要实现 rich comparison这样做的方法。自 heapify
nhu cầu <
,你必须至少实现 __lt__
.
您还可以查看 @total_ordering
装饰器以避免实现所有这些。
类似的东西:
from functools import total_ordering
@total_ordering
class Vertex:
# Your current class code
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.distance == other.distance
return NotImplemented
def __lt__(self, other):
if isinstance(other, self.__class__):
return self.distance < other.distance
return NotImplemented
如果您需要将该类用作字典键,则需要添加 __hash__
方法。大概是这样的:
def __hash__(self):
return id(self)
关于python - 不可排序的类型 : Vertex() < Vertex(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33680224/
Tôi đang cố gắng ghi đầu ra xml đã được quét vào json. Việc tìm nạp không thành công vì mục này không thể tuần tự hóa được. Từ câu hỏi gợi ý rằng bạn cần xây dựng một đường dẫn, câu trả lời không được cung cấp nằm ngoài phạm vi của câu hỏi về trình tuần tự hóa vụn vặt SO. Địa điểm
Có cách nào để phân biệt xem một tham số có thể đánh giá được trong thời gian biên dịch hay chỉ có thể đánh giá được trong thời gian chạy bằng cách nạp chồng một hàm? Giả sử tôi có hàm sau: std::string lookup(int x) { return table::va
Tôi đang viết một ứng dụng sử dụng mẫu MVVM. Tôi cung cấp dữ liệu cho Chế độ xem bằng cách đặt thuộc tính DataContext của Chế độ xem thành một phiên bản của ViewModel. Nói chung tôi chỉ sử dụng Binding từ đó
Đối với một dự án, tôi đang thu thập nhiều lệnh hồng ngoại bằng cảm biến có mô-đun python đơn giản. . Tôi nhận được chuỗi byte sau: commando1= b'7g4770CQfwCTVT9bQDAzVEBMagGR
Tôi có một phương pháp tính thuế khi người dùng thanh toán bằng cách sử dụng Cartridge làm khung cửa hàng của tôi. tax = tax * phép tính thập phân(str(settings.SHOP_DEFAULT_TAX_RATE)) hoạt động tốt. Chạy
Tôi đang tạo một chương trình vẽ bằng pygame nơi tôi muốn cung cấp cho người dùng tùy chọn lưu trạng thái chính xác của chương trình và sau đó tải lại sau. Tại thời điểm này, tôi lưu một bản sao của từ điển chung của mình và sau đó lặp lại nó, chọn từng đối tượng. pyga
Trước C++ 11, tôi có thể tạo một lớp không thể sao chép bằng cách sử dụng: private: MyClass(const MyClass& operator=(const MyClass&);
Xin chào mọi người :) Tôi đang sử dụng 1.5.4-all (22-10-2014) (Trình biên dịch Microsoft Visual C++ 18.00.21005.1 cho nền tảng x86) trong dự án VC++ của tôi. TÔI
Tôi có một tệp python: analyze.py: def svm_analyze_AHE(file_name): # lấy tệp abp testdata = pd.
Câu hỏi này đã có câu trả lời: Làm cách nào để tuần tự hóa kết quả SqlAlchemy thành JSON? (37 câu trả lời) Đã đóng 4 năm trước. Tôi đang viết một truy vấn nhỏ để lấy dữ liệu từ cơ sở dữ liệu mysql,
Tôi là người mới bắt đầu sử dụng Python và tôi đang gặp một số vấn đề với JSON. Trong hướng dẫn tôi đang sử dụng có hai hàm: def read_json(filename): data = [] if os.pa
Tôi hiện đang phát triển một ứng dụng vẽ dựa trên HTML5 Canvas/JavaScript nhỏ cho iPad. Nó chạy trong Safari. Cho đến nay, mọi thứ đều diễn ra tốt đẹp ngoại trừ một điều. Nếu tôi xoay thiết bị,
Đoạn mã sau không được biên dịch bằng Visual Studio 2013: #include struct X { X() = default X(const X&) = delete;
Xin chào, tôi đã tạo một trình phân loại văn bản và tôi đã sử dụng nó trong đó và nó trả về một mảng và tôi muốn trả về jsonresponse nhưng dòng mã cuối cùng lại báo lỗi 'array(['cycling'], dtype =object) không phải khả thi
Tôi đang sử dụng Flask và Flask-Login để xác thực người dùng. Flask-Sqlalchemy lưu trữ các mô hình này trong cơ sở dữ liệu sqlite: ROLE_USER = 0 ROLE_ADMIN =
Nếu bạn cố gắng gửi một đối tượng không thể tuần tự hóa JSON (bất kỳ đối tượng nào ngoài danh sách, từ điển, số nguyên, v.v.), bạn sẽ nhận được thông báo lỗi sau: "errorMessage": "Đối tượng thuộc loại tập hợp không phải là JSON
Tôi gặp sự cố khi cố gắng di chuyển std::vector trong đó T rõ ràng là không thể di chuyển được (không có toán tử khởi tạo/gán di chuyển nào được xác định, nó chứa các con trỏ bên trong) nhưng tại sao hàm di chuyển của vectơ lại gọi T
Tôi đang cố gắng trả lại mã thông báo cho người dùng sau khi họ đăng nhập thành công nhưng tôi vẫn gặp phải lỗi sau: TypeError: Đối tượng thuộc loại 'byte' không thể tuần tự hóa JSON. Làm cách nào để khắc phục điều này? Đây là mã của tôi cho đến nay: nếu người dùng:
Tôi là một lập trình viên xuất sắc, rất giỏi!