Skip to main content

Posts

Showing posts with the label Python

Python : Graph Implementation

class Vertex:         def __init__(self,node):         self.id = node         self.adjacent = {}         self.distance = 99999         self.visited = False         self.previous = None         def addNeighbour(self,neighbour,weight = 0):         self.adjacent[neighbour] = weight         def getConnections(self):         return self.adjacent.keys()             def getVertexID(self):         return self.id         def getWeight(self,neighbour):         return self.adjacent[neighbour]             def setDistance(self,dist):         self.distance = dist         def getDistance(self):         return self.distance             def setPrevious(self,prev):         self.previous = prev             def setVisited(self):         self.visited = True             def __str__(self):         return str(self.id) + 'adjacent:' + str([x.id for x in self.adjacent]) class Graph:     def __init__(self):         self.vertDictionary = {}         self.numVertices

Python : Simple graph implementation

class Graph:         def __init__(self):         self.list_edge = {}         self.list_vertex = {}             def add_node(self,node):         self.list_vertex[node] = True     def add_edge(self,node,nodenext):         try :             self.list_edge[node].append(nodenext)         except :             self.list_edge[node] = []             self.list_edge[node].append(nodenext)         try :             self.list_edge[nodenext].append(node)         except :             self.list_edge[nodenext] = []             self.list_edge[nodenext].append(node)         def neighbors(self,node):         try :             return self.list_edge[node]         except :             return []         def nodes(self):         return self.list_vertex.keys()     if __name__ == "__main__":     G = Graph()     G.add_node(1)     G.add_node(2)     G.add_node(3)     G.add_node(4)     G.add_node(5)         G.add_edge(1,2)     G.add_edge(2,3)     G.add_edge(3,4)     G.add_edge(1,4)     print G.neighbo

Python : Tree implementation

class Node:     def __init__(self,value):         self.left = None         self.data = value         self.right = None         class Tree:         def createNode(self,data):         return Node(data)             def insert(self,node,data):         if node is None:             return self.createNode(data)         if data < node.data:             node.left = self.insert(node.left,data)         elif data > node.data:             node.right = self.insert(node.right,data)                 return node         def traversePreorder(self,root):         if root is not None:             print root.data             self.traversePreorder(root.left)             self.traversePreorder(root.right)                     def main():     root = None     tree = Tree()     root = tree.insert(root,10)     print root     tree.insert(root,20)     tree.insert(root,30)     tree.insert(root,40)     tree.insert(root,70)             print "Traverse Inorder"    

Python : Example of class construct with main

class Numbers:     def __init__(self,number):         self.number = number             def find_number_type(self):         #print self.number         if self.number % 2 != 0:             print "Odd"         else:             print "Even" #End of class construct if __name__ == '__main__':     n = int(raw_input())     num1 = Numbers(n)     num1.find_number_type()

Python : A simple example of class

class Numbers: #Class name and declaration     def __init__(self,number):         #Initializing class members         self.number = number             def find_number_type(self):         if self.number % 2 == 0:             print "Even"         else:             print "Odd" #End of class construct num1 = Numbers(100) #Creating class object num1.find_number_type() #Calling class function

Python : Reading records from mysql table with python

To read records from a mysql table in python we can use the below code. Please refer to my previous post for the table structure and records inserted into the table in sql-inserting-records-into-mysql-table post. To connect to mysql database from python MySQLdb library is used. You can refer the post on how to install MySQLdb here . #!/usr/bin/python import MySQLdb dbconnection = MySQLdb.connect(host = "localhost" , user = "username" , passwd = "password" , db = "pydatabase" ) cursor = dbconnection.cursor() sql = "select * from pytable" cursor.execute(sql) for record in cursor.fetchall(): print record on running the program it fetches all the records from the table pytable and loads into a cursor. With a for loop the records are printed. The output of the above program is displayed here. (1L, 'Snikers' , 'CH' , datetime.date(2016, 8, 5), 100.0) (2L, 'Galaxy'

Python : How to write on same line in python

Usual print statement in python will write to screen on a different line each time it is called. eg : >>> print "hello"                print "world" This will print the following on screen : hello world Now to print on the same line we can use the below sys.stdout.write("hello" + " ") sys.stdout.write("world") This will print the following on screen : hello world

Python : reading json data in python

The below program shows how to read a json file and pull the data element for it in python. We make use json library for this. #!/usr/bin/python import json def get_id(): file = open("/home/python/json/js.json","r") json_file = file.read() parse_json = json.loads(json_file) a = parse_json['purchase'][0]['order_id'] print a get_id() #output : 1234 Sample json file {    "store" : "New York",      "purchase" :    [    {       "order_id" : "1234",       "customer" : "regular",         "amount" : "$123.45"    }    ] }

Python : List and related functions

List is a datatype in python which can store a set of values. Lets say we need to create a list as 'name' Initialize a list name = list() Alternate way is name = [] #This will make an empty list name = ['apple','orange','mango'] #This will make a list with 3 elements Various functions that can be performed on list APPEND(element) Adds an element to the list >>> name = ['apple','orange','mango'] >>> name.append('banana') >>>['apple','orange','mango','banana'] EXTEND(list) This function can be used to merge two or more list into one. lets says we have another list fruits = ['coconut','jackfruit'] >>> name = ['apple','orange','mango'] >>> name.extend(fruits) >>>['apple','orange','mango','coconut','jackfruit'] IN

Python : Find number of occurrence of word

This is a program to find the number of occurrence of a particular word using python.We read the contents of the file into a list and use the count function to get the count of words. #/usr/bin/python file = open("/home/Documents/alice.txt","r") word = file.read().split() print word print word.count("Alice") Here I have read the chapter 1 of story Alice in Wonderland by Lewis Carroll taken from the site www.gutenberg.org . The file is read in read mode and it is converted into a list called "word".The split() function will consider a space as default delimiter for split if nothing is specified. We have function like count() which can be used to apply directly on a list.Here the word which need to be searched "Alice" is given as argument.