请帮助我,我真的很绝望,我不知道该怎么办。
所以我们在大学里有一项任务是用 python 编写 dijkstra 算法。
INVALID_NODE = -1 #Define the initial variables to -1 and a very high number.
INFINITY = 1000000
#A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6
#network[0][1] is the cell that contains edge value for going from A to B
class Node:
previous = INVALID_NODE #With each node created, define it's initial variables to -1 and a very high number.
distFromSource = INFINITY
visited = False #Every node except starting node should be univisited by default.
def populateNetwork(filename):
network = [] #Create an empty array to store the network file.
networkfile = open(filename, "r") #Open the network file.
for line in networkfile: #For every line in network file, remove \n's and split the data on every comma, then add everything to the array.
line = line.replace("\n","")
line = line.split(',')
line = map(int, line)
network.append(line)
return network
def populateNodeTable(network, startNode): #Populate the nodeTable with node objects based on the network file.
nodeTable = []
for node in network:
nodeTable.append(Node())
nodeTable[startNode].distFromSource = 0 #Initialize the startNode distance from source and mark it as visited.
nodeTable[startNode].visited = True
return nodeTable
def findNeighbours(network, nodeTable, currentNode): #Function to find neighbours of the currentNode.
nearestNeighbour = [] #Empty array to store neighbour indexes.
columnIndex = 0
for entry in network[currentNode]: #check each node if it has a link to the currentNode and if it's unvisited, if both are true, add to the array.
if entry != 0 and nodeTable[columnIndex].visited == False:
nearestNeighbour.append(columnIndex)
columnIndex += 1
return nearestNeighbour
def calculateTentative(network, nodeTable, currentNode, nearestNeighbours):
#Calculate the distance from currentNode to each node in neighborous list
#Work out distance from source for each node
#If lower than current entry in nodeTable for that node, update
for neighbour in nearestNeighbours:
tentativeDistance = nodeTable[currentNode].distFromSource + network[currentNode][neighbour]
if nodeTable[neighbour].distFromSource > tentativeDistance:
nodeTable[neighbour].distFromSource = tentativeDistance
nodeTable[neighbour].previous = currentNode
return nodeTable
def findNextNode(nodeTable): #Find the next node from the neighbouring nodes with the lowest distFromSource.
currentDistance = INFINITY
nodeIndex = 0
currentNode = INVALID_NODE
for node in nodeTable: #If it's distFromSource is less than distFromSource of the currentNode, make it the currentNode.
if(node.distFromSource < currentDistance) and (node.visited == False):
currentNode = nodeIndex
currentDistance = node.distFromSource
nodeIndex += 1
return currentNode
####################
#Pseudocode from the internet for reference
#function Dijkstra(network, start):
# for each node v in network:
# distFromSource[v]:=infinity #initial distance from source to vertex v is set to infinite
# previous[v]:=undefined (-1) #previous node in optimal path from source
#
# distFromSource[source]:= 0 #distance from source to source
# Q:= the set of all nodes in Graph #all nodes in the graph are unoptimized - thus are in Q
#
# while Q is not empty: #main loop
# u:=node in Q with smallest dist[]
# remove u from Q
#
# for each neighbour v of u: #where v has not yet been removed from Q
# alt:=dist[u] + dist_between(u,v)
# if alt < dist[v]
# dist[v]:=alt #relax(u,v)
# previous[v]:=u
# return previous[]
#
####################
#Files
network = populateNetwork("network.txt") #Populate the network array with network defined in netwowrk.txt file.
routefile = "route.txt" #Load the route information.
letters = ["A", "B", "C", "D", "E",
"F", "G", "H", "I", "J", "K", "L", #Array of letters for easy conversion between integers and letters.
"M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z"]
options = { "A": 0, "B": 1, #Dictionary to convert the initial route file to integers for much easier manipulation
"C": 2, "D": 3, #within the program.
"E": 4, "F": 5,
"G": 6, "H": 7,
"I": 8, "J": 9,
"K": 10, "L": 11,
"M": 12, "N": 13,
"O": 14, "P": 15,
"Q": 16, "R": 17,
"S": 18, "T": 19,
"U": 20, "V": 21,
"W": 22, "X": 23,
"Y": 24, "Z": 25,
}
####################
#Initial data and initialisation
print("Network file:") #Print the entire network.txt file to the screen line by line.
itr = 0 #Iterator for line labeling.
for line in network:
print(letters[itr], ".", line) #Prints letters associated with each node.
itr = itr + 1
with open(routefile, "r") as rfile: #Open route.txt and split it into two variables.
routeData = rfile.read().split(">")
routeData[0] = routeData[0].rstrip("\n") #Strip route data from additional \n's that can occur at the end of the file.
routeData[1] = routeData[1].rstrip("\n")
startNode = options[routeData[0]] #Save both numbers as start and end nodes.
endNode = options[routeData[1]]
print("\nRoute:\n%s to %s\n" %(letters[startNode], letters[endNode])) #Print start and end nodes to the user to make sure that
#the file was loaded correctly.
#Populate node table with the network data and starting node.
currentNode = startNode #Initialize currentNode to the start node.
print("Starting node: %s\nDestination node: %s" %(network[startNode], network[endNode])) #Prints the starting and end nodes.
####################
nodeTable = populateNodeTable(network, currentNode) #Populates nodeTable with node objects from the network.
while currentNode is not endNode: #While loop running as long as the currentNode isn't the destination.
neighbours = findNeighbours(network, nodeTable, currentNode) #Examine neighbours of the currentNode.
nodeTable = calculateTentative(network, nodeTable, currentNode, neighbours) #Calculate tentative distances for the neighbours of the currentNode.
nodeTable[currentNode].visited = True #Mark current node as visited.
currentNode = findNextNode(nodeTable) #Jump to the next neighbour.
#print "\nChecking node: " #Print node the program is currently working on.
#print letters[currentNode]
####################
#New variable for the while loop.
routeList = [] #Array to store final route data.
routeList.append(letters[currentNode]) #Add the final node to the array.
while currentNode is not startNode: #Add all the nodes used in the final travel to the array using the nodetable[i].previous variable.
routeList.append(letters[nodeTable[currentNode].previous])
currentNode = nodeTable[currentNode].previous
print("\nShortest route between start and end nodes: ")
for entry in reversed(routeList): #Print the array backwards for more intuitive output.
print(entry,)
print("\n\nTotal distance traveled:",) #Print the total distance traveled.
print(nodeTable[endNode].distFromSource)
####################
#Utility
print("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") #separator line for easier debugging
我是在我的笔记本电脑上做的(它运行的是 debian),它运行得非常好,脚本正在做它应该做的事情并给我正确的输出。
当我运行它时,它说:
TypeError: 'map' object is not subscriptable
但这就是问题所在:我在 3 小时内收到了它,我现在要上传它,我尝试在我的台式电脑 (windows 10) 上运行它,只是为了确保我得到了正确的文件。
但它正在运行并吐出一个错误我完全不知道它是什么,因为我只是 python 的初学者,这是我使用它的第一个学期......
请帮帮我!我试图弄清楚为什么它不能在 Windows 上运行,但这超出了我的知识范围。
虽然它在 Linux 上可以 100% 正常工作...
请帮助我,我真的不想让模块失败,即使我做了所有的工作......
最佳答案
- line = map(int, line)
# in Python 3+ you will get the map object <map object at 0x.....>
+ line = list(map(int, line))
关于Python 脚本适用于 linux 但不适用于 windows,我真的很绝望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41064591/
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我有一个在Linux服务器上运行的ruby脚本。它不使用rails或任何东西。它基本上是一个命令行ruby脚本,可以像这样传递参数:./ruby_script.rbarg1arg2如何将参数抽象到配置文件(例如yaml文件或其他文件)中?您能否举例说明如何做到这一点?提前谢谢你。 最佳答案 首先,您可以运行一个写入YAML配置文件的独立脚本:require"yaml"File.write("path_to_yaml_file",[arg1,arg2].to_yaml)然后,在您的应用中阅读它:require"yaml"arg
我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm
这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub
当我使用has_one时,它工作得很好,但在has_many上却不行。在这里您可以看到object_id不同,因为它运行了另一个SQL来再次获取它。ruby-1.9.2-p290:001>e=Employee.create(name:'rafael',active:false)ruby-1.9.2-p290:002>b=Badge.create(number:1,employee:e)ruby-1.9.2-p290:003>a=Address.create(street:"123MarketSt",city:"SanDiego",employee:e)ruby-1.9.2-p290
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht