Grokking Algorithms



Download 6,4 Mb.
Pdf ko'rish
bet67/120
Sana21.12.2022
Hajmi6,4 Mb.
#893167
1   ...   63   64   65   66   67   68   69   70   ...   120
Bog'liq
Grokking Algorithms An Illustrated Guide for Programmers and Other

Chapter 7
 
 
I
 
 
Dijkstra’s algorithm
How do you represent the weights of those edges? Why not just use 
another hash table?
graph[“start”] = {}
graph[“start”][“a”] = 6
graph[“start”][“b”] = 2
So 
graph[“start”]
is a hash table. You can get all the neighbors for 
Start like this:
>>> print graph[“start”].keys()
[“a”, “b”]
here’s an edge from Start to A and an edge from Start to B. What if you 
want to ind the weights of those edges?
>>> print graph[“start”][“a”]
2
>>> print graph[“start”][“b”]
6
Let’s add the rest of the nodes and their neighbors to the graph:
graph[“a”] = {}
graph[“a”][“fin”] = 1
graph[“b”] = {}
graph[“b”][“a”] = 3
graph[“b”][“fin”] = 5
graph[“fin”] = {}
The finish node doesn’t have any neighbors.


133
Implementation
he full graph hash table looks like this.
Next you need a hash table to store the costs for each node.
he 
cost
of a node is how long it takes to get to that 
node from the start. You know it takes 2 minutes from 
Start to node B. You know it takes 6 minutes to get to 
node A (although you may ind a path that takes less 
time). You don’t know how long it takes to get to the 
inish. If you don’t know the cost yet, you put down 
ininity. Can you represent 
ininity
in Python? Turns 
out, you can:
infinity = float(“inf”)
Here’s the code to make the costs table:
infinity = float(“inf”)
costs = {}
costs[“a”] = 6
costs[“b”] = 2
costs[“fin”] = infinity
You also need another hash table for the parents:


134

Download 6,4 Mb.

Do'stlaringiz bilan baham:
1   ...   63   64   65   66   67   68   69   70   ...   120




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish