Hướng dẫn loop defaultdict python

I have the following code which makes topological order:

from collections import defaultdict 

class Graph: 
    def __init__(self): 
        self.graph = defaultdict(list)
        self.V = 0  #number of nodes

    def addEdge(self,u,v): 
        self.graph[u].append(v) 
        self.V = self.V + 1

    def topologicalSortUtil(self,v,visited,stack): 

        visited[v] = True

        for i in self.graph[v]: 
            if visited[i] == False: 
                self.topologicalSortUtil(i,visited,stack) 

        stack.insert(0,v) 

    # topologicalSortUtil() 
    def topologicalSort(self): 
        # Mark all the vertices as not visited 
        visited = [False]*self.V 
        stack =[] 

        for i in range(self.V): 
            if visited[i] == False: 
                self.topologicalSortUtil(i,visited,stack) 

        print stack 

g= Graph() 
g.addEdge(5, 2); 
g.addEdge(5, 0); 
g.addEdge(4, 0); 
g.addEdge(4, 1); 
g.addEdge(2, 3); 
g.addEdge(3, 1); 

g.topologicalSort() 

It gives:

[5, 4, 3, 2, 1, 0]

Now, I want my code to be able to handle with strings as keys:

g.addEdge('f', 'c')
g.addEdge('f', 'a')
g.addEdge('e', 'a')
g.addEdge('e', 'b')
g.addEdge('c', 'd')
g.addEdge('d', 'b')

(just change the digits to letters... 0='a', 1='b' etc..) However this doesn't work.

It should give:

['f', 'e', 'd', 'c', 'b', 'a']

The problem is here:

for i in range(self.V):
    if visited[i] is False:
        self.topologicalSortUtil(i, visited, stack)

The code iterates over range and not over the actual node keys.

I tried to convert it to:

for i in self.graph.items():

but it doesn't work.

TypeError: list indices must be integers or slices, not tuple

How can I fix this?

Hướng dẫn loop defaultdict python

Hướng dẫn web crawler python

91 / 100 Cách crawl dữ liệu web hay cách thu thập dữ liệu web là một thắc mắc của khá nhiều bạn. Lý do bởi hiện nay, có vô vàn các website ở đủ mọi lĩnh ...

Hướng dẫn loop defaultdict python

Hướng dẫn python open ansi file

MS Notepad gives the user a choice of 4 encodings, expressed in clumsy confusing terminology:Unicode is UTF-16, written little-endian. Unicode big endian is UTF-16, written big-endian. In both ...

Hướng dẫn loop defaultdict python

Can you change float to int in python?

IntroductionIn Python, data types are used to classify one particular type of data, determining the values that you can assign to the type and the operations you can perform on it. When programming, ...

Hướng dẫn loop defaultdict python

What is an attribute in python class?

I had a programming interview recently, a phone-screen in which we used a collaborative text editor.I was asked to implement a certain API, and chose to do so in Python. Abstracting away the problem ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng looping definition python

Nội dung chính2- Tổng quan các vòng lặp trong Python 2- Vòng lặp while 3- Vòng lặp for với range 4- Sử dụng for và mảng 5- Sử dụng lệnh break trong vòng lặp 6- Sử ...

Hướng dẫn loop defaultdict python

Hướng dẫn loop defaultdict python

Hướng dẫn ab testing python package

Nội dung chínhFrom experimental design to hypothesis testing1. Designing our experimentFormulating a hypothesisChoosing the variablesChoosing a sample size2. Collecting and preparing the data3. ...

Hướng dẫn loop defaultdict python

How do you comment out everything in python?

Programming with Python is exciting. Writing code and sharing it with others can lead to amazing things. But before our programs can grow, we need to make sure they are easy to read. That’s why ...

Hướng dẫn loop defaultdict python

Hướng dẫn conda biopython

Trong bài viết này tôi để lại một Hướng dẫn cài đặt Anaconda và cách sử dụng trình quản lý gói Conda của bạn. Với điều này, chúng ta có thể tạo môi ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng python nonetype python

Trong Python, không có vô giá trị từ khóa, nhưng có Không có. Không có giá trị trả về của hàm doesn’t return anything. None is often used to represent the absence of a ...

Hướng dẫn loop defaultdict python

Hướng dẫn selenium python

Trong lĩnh vực công nghệ thông tin những năm gần đây, ngôn ngữ lập trình Python đang ngày càng trở nên phổ biến. Với bất kỳ lập trình viên nào, việc tự ...

Hướng dẫn loop defaultdict python

Hướng dẫn count python

Hàm count() trong Python trả về số lần xuất hiện của chuỗi con trong khoảng [start, end]. Đếm xem chuỗi str này xuất hiện bao nhiêu lần trong chuỗi string hoặc ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng cast python python

Specify a Variable TypeThere may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng np absolute python

Có thể là do có một hàm dựng sẵn có cùng tên, abs . Điều này cũng đúng với np.amax, np.amin và np.round_.Nội dung chính2. Các phép toán số học trong NumPyCác hàm ...

Hướng dẫn loop defaultdict python

How to call a class function in python

EDIT2: Thank you all for your help! EDIT: on adding @staticmethod, it works. However I am still wondering why i am getting a type error here. I have just started OOPS and am completely new to it. I ...

Hướng dẫn loop defaultdict python

Hướng dẫn python strptime format

Nội dung chínhChuyển string sang datetime trong pythonCú pháp chuyển string sang datetime trong pythonBảng định dạng ngày tháng năm trong chuỗi pythonChuyển string sang ...

Hướng dẫn loop defaultdict python

Hướng dẫn dtype trong python

Đối tượng kiểu dữ liệu dtype là một thực thể (instance) của lớp numpy.dtype. Nó có thể được tạo ra qua numpy.dtype.Cho đến nay, chúng ta đã sử dụng trong ...

Hướng dẫn loop defaultdict python

Hướng dẫn split array python

Trong bài trước chúng ta đã tìm hiểu về cách nối, xếp chồng mảng trong numpy. Bài này chúng ta sẽ đi tìm hiểu về cách chia, tách mảng trong numpy.Split array trong ...

Hướng dẫn loop defaultdict python

Hướng dẫn loop defaultdict python

Hướng dẫn python android

Trong bài viết này, Học viện Agile sẽ cùng bạn giải đáp câu hỏi liệu Python có phải là ngôn ngữ hữu dụng để lập trình ứng dụng Android? Có những công ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng looped meaning python

Nội dung chính2- Tổng quan các vòng lặp trong Python 2- Vòng lặp while 3- Vòng lặp for với range 4- Sử dụng for và mảng 5- Sử dụng lệnh break trong vòng lặp 6- Sử ...

Hướng dẫn loop defaultdict python

How to round up float in python

For those who doesnt want to use import.For a given list or any number:x = [2, 2.1, 2.5, 3, 3.1, 3.5, 2.499,2.4999999999, 3.4999999,3.99999999999] You must first evaluate if the number is equal to ...

Hướng dẫn loop defaultdict python

Hướng dẫn python enumerate

Ví dụ về Python EnumerateTrong bài viết này, bạn sẽ tìm hiểu cách sử dụng enumerate trong Python để có một bộ đếm trong một vòng lặp và các trường hợp sử ...

Hướng dẫn loop defaultdict python

How do you raise error in try except in python?

Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax ...

Hướng dẫn loop defaultdict python

Hướng dẫn python timer start stop

Tuy nhiên, khoảng thời gian được khởi tạo cho timer có thể sẽ không phải là tức thời, khi hành động thực sự được thực hiện bởi trình thông dịch, bởi ...

Hướng dẫn loop defaultdict python

What does rng do in python?

Source code: Lib/random.pyThis module implements pseudo-random number generators for various distributions.For integers, there is uniform selection from a range. For sequences, there is uniform ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng clear list python

Bài này mình sẽ giới thiệu phương thức list clear() trong Python, phương thức này dùng để xóa tất cả các item bên trong list.Bài viết này được đăng tại ...

Hướng dẫn loop defaultdict python

How do you fit a line in python?

You can use the following basic syntax to plot a line of best fit in Python:#find line of best fit a, b = np.polyfit(x, y, 1) #add points to plot plt.scatter(x, y) #add line of best fit to ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng txt file python

Python cung cấp các chức năng cơ bản và phương thức cần thiết để thao tác các file. Bài viết này tôi xin giới thiệu những thao tác cơ bản nhất với file trong ...

Hướng dẫn loop defaultdict python

Hướng dẫn loop defaultdict python

Correlation coefficient matrix in python

Correlation coefficients quantify the association between variables or features of a dataset. These statistics are of high importance for science and technology, and Python has great tools that you ...

Hướng dẫn loop defaultdict python

Hướng dẫn loop defaultdict python

How do you print the first row in python?

HowToPython Pandas HowtosGet the First Row of Dataframe Pandas Created: January-16, 2021 | Updated: February-21, 2021 Get the First Row of a Pandas DataFrame Using pandas.DataFrame.iloc PropertyGet ...

Hướng dẫn loop defaultdict python

Hướng dẫn partition in python example

Mục đíchChia một mảng ra thành hai cụm: một cụm thỏa điều kiện, và cụm còn lại.Cài đặtSử dụng mảng phụdef partition(a, pred): head = [x for x in a if ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng define imput python

Hướng dẫn sử dụng def trong python. Bạn sẽ học được cách sử dụng def để khai báo hàm trong python, cũng như cách gọi hàm trong python đã được khai báo sau ...

Hướng dẫn loop defaultdict python

Matlab or python for data science

Matlab and Python both can do quite different and incredible things, which makes the question of “Matlab versus Python” interesting. When considering Matlab or Python, the best question to ask is ...

Hướng dẫn loop defaultdict python

Hướng dẫn ddos python github

ndbiawMột tập lệnh Python để DDOS một trang web bằng phương pháp HTTP Flood, một trang web bình thường chỉ cần 5s để sập hoàn toàn!Cách Dùng:Tập lệnh này có ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng np.dstack python

Trong bài viết trước tôi đã giới thiệu cho bạn về NumPy, lợi ích của nó, cách cài đặt nó để sử dụng, tìm hiểu về Mảng trong NumPy, kiểu dữ liệu trong ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng c# encoding python

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

Hướng dẫn loop defaultdict python

Hướng dẫn dùng minuscule def python

Mục lụcNội dung chínhMục lục1- Python Function 2- Ví dụ với Function 3- Hàm với tham số bắt buộc 4- Hàm với tham số mặc định 5- Hàm có tham số với độ dài ...