程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Introduction to Python data structure and algorithm

編輯:Python

When you hear about data structures , What do you think ?

A data structure is a container for organizing and grouping data by type . They differ based on variability and order . Variability is the ability to change objects after they are created . We have two types of data structures , Built in data structures and user-defined data structures .

What is data algorithm - Is a series of steps performed by a computer , Accept input and convert it to target output .

Built in data structure

list

The list is defined in square brackets , Contains comma separated data . The list is variable and ordered . It can contain a mixture of different data types .

months=['january','february','march','april','may','june','july','august','september','october','november','december']
print(months[0])#print the element with index 0
print(months[0:7])#all the elements from index 0 to 6
months[0]='birthday #exchange the value in index 0 with the word birthday
print(months)

Tuples

Tuples are another kind of container . It is the data type of an immutable sequence of ordered elements . Immutable , Because you can't add or remove elements from tuples , Or sort in place .

length, width, height =9,3,1 #We can assign multiple variables in one
shot
print("The dimensions are {} * {} * {}".format(length, width, height))

A group of

A set is a variable and unordered set of unique elements . It allows us to quickly remove duplicates from the list .

numbers=[1,2,3,4,6,3,3]
unique_nums = set(numbers)
print(unique_nums)
models ={'declan','gift','jabali','viola','kinya','nick',betty' }
print('davis' in models)#check if there is turner in the set models
models.add('davis')
print(model.pop())remove the last item#

Dictionaries

Dictionaries are variable and unordered data structures . It allows you to store a pair of items ( Key and value )

The following example shows the possibility of including containers in other containers to create composite data structures .

music={'jazz':{"coltrane": "In a sentiment mood",
"M.Davis":Blue in Green",
"T.Monk":"Don't Blame Me"},
"classical":{"Bach": "cello suit",
"Mozart": "lacrimosa",
"satle": "Gymnopedie"}}
print(music["jazz"]["coltrane'])#we select the value of the key coltrane
print(music["classical"] ['mozart"])

Stack using arrays stack is a linear data structure , The elements are arranged in order . It follows L.I.F.O The mechanism of , It means last in first out . therefore , The last inserted element will be deleted as the first element . These operations are :

  • Push element onto stack .
  • Remove an element from the stack .

Conditions to check

  • Spillage —— When we try to put another element in a stack that already has the largest element , This will happen .
  • Underflow condition —— When When we try to remove an element from an empty stack , This will happen .
class mystack:
def __init__(self):
self.data =[]
def length(self): #length of the list
return len(self.data)
def is_full(self): #check if the list is full or not
if len(self.data) == 5:
return True
else:
return False
def push(self, element):# insert a new element
if len(self.data) < 5:
self.data.append(element)
else:
return "overflow"
def pop(self): # # remove the last element from a list
if len(self.data) == 0:
return "underflow"
else:
return self.data.pop()
a = mystack() # I create my object
a.push(10) # insert the element
a.push(23)
a.push(25)
a.push(27)
a.push(11)
print(a.length())
print(a.is_full())
print(a.data)
print(a.push(31)) # we try to insert one more element in the list - the
output will be overflow
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop()) # try to delete an element in a list without elements - the
output will be underflow

Use an array to queue

A queue is a linear data structure , The elements are arranged in order . It follows the principle of first in, first out F.I.F.O Mechanism .

Describe aspects of queue characteristics

Both ends :

  • front end - Point to the starting element .
  • Point to last element .

There are two operations :

  • enqueue—— Insert elements into the queue . It will be done in the rear .
  • List out - Remove elements from the queue . This will be done at the front .

There are two conditions .

  • overflow - Insert into a full queue .
  • underflow - Delete... From the empty queue .
class myqueue:
def __init__(self):
self.data = []
def length(self):
return len(self.data)
def enque(self, element): # put the element in the queue
if len(self.data) < 5:
return self.data.append(element)
else:
return "overflow"
def deque(self): # remove the first element that we have put in queue
if len(self.data) == 0:
return "underflow"
else:
self.data.pop(0)
b = myqueue()
b.enque(2) # put the element into the queue
b.enque(3)
b.enque(4)
b.enque(5)
print(b.data)
b.deque()# # remove the first element that we have put in the queue
print(b.data)

Trees ( Common tree )

Trees are used to define hierarchies . It starts at the root node , following , The last node is called a child node .

In this paper , I mainly focus on binary trees . Binary tree is a tree data structure , Each node has at most two children , Called left child and right child .

 

# create the class Node and the attrbutes
class Node:
def __init__(self, letter):
self.childleft = None
self.childright = None
self.nodedata = letter
# create the nodes for the tree
root = Node('A')
root.childleft = Node('B')
root.childright = Node('C')
root.childleft.childleft = Node('D')
root.childleft.childright = Node('E')

Linked list

It is linear data with a series of connected nodes . Each node stores data and displays the route to the next node . They are used to implement undo and dynamic memory allocation .

class LinkedList:
def __init__(self):
self.head = None
def __iter__(self):
node = self.head
while node is not None:
yield node
node = node.next
def __repr__(self):
nodes = []
for node in self:
nodes.append(node.val)
return " -> ".join(nodes)
def add_to_tail(self, node):
if self.head == None:
self.head = node
return
for current_node in self:
pass
current_node.set_next(node)
def remove_from_head(self):
if self.head == None:
return None
temp = self.head
self.head = self.head.next
return temp
class Node:
def __init__(self, val):
self.val = val
self.next = None
def set_next(self, node):
self.next = node
def __repr__(self):
return self.val

Chart

  • This is a data structure , It collects nodes that have data connected to other nodes .

It includes :

  • A collection of vertices .
  • edge E Set , Expressed as an ordered pair of vertices (u,v)

Algorithm

In terms of algorithm , I won't go too far , Just state the method and type :

  • Divide and rule And —— Known for dividing problems into sub parts and solving them separately .
  • dynamic - It divides the problem into sub parts , Remember the results of the subparts , And apply it to similar problems .
  • Greedy algorithm —— Take the simplest steps to solve the problem , Without worrying about the complexity of the future .

The type of algorithm

  • Tree traversal algorithm is a nonlinear data structure . Characterized by roots and nodes . There are three types of sequential traversal , Preorder traversal and postorder traversal .
  • Sorting algorithm —— Used to sort data in a given order . It can be divided into merge sort and bubble sort .
  • search algorithm —— Used to find some elements that exist in a given dataset . Some types of search algorithms are : Linear search , Binary search and index search .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved