海外TECH |
MakeUseOf |
How to Enable and Find Your Windows Boot Log |
https://www.makeuseof.com/windows-boot-log-guide/
|
logwant |
2022-06-26 19:15:14 |
海外TECH |
DEV Community |
DATA STRUCTURES AND ALGORITHMS 102:DEEP DIVE INTO DATA STRUCTURES AND ALGORITHMS IN PYTHON. |
https://dev.to/violakithinji/data-structures-and-algorithms-102deep-dive-into-data-structures-and-algorithms-4n2f
|
DATA STRUCTURES AND ALGORITHMS DEEP DIVE INTO DATA STRUCTURES AND ALGORITHMS IN PYTHON In my last article on Introduction to data structures and algorithms I walked you through what algorithms and data structures are types classification properties characteristics operations and merits To get more insights read the articles here and this here In today s topic we will look at we will learn data structures abstract data types and their implementation Implementation of binary tree traversal technique in python Graph traversals techniques i e Depth first search and Breadth first search in python Implementation of sorting Algorithms in python Enhanced analytical skill and efficiently use searching and sorting algorithms in real applications Implementation of searching algorithms in python Implementation of ADT Abstract data type Abstract Data type ADT is a type or class for objects whose behavior is defined by a set of values and a set of operations The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations It is called “abstract because it gives an implementation independent view The process of providing only the essentials and hiding the details is known as abstraction user of data type does not need to know how that data type is implemented for example we have been using Primitive values like int float char data types only with the knowledge that these data type can operate and be performed on without any idea of how they are implemented So a user only needs to know what a data type can do but not how it will be implemented Think of ADT as a black box which hides the inner structure and design of the data type Now we ll define three ADTs namely List ADT Stack ADT Queue ADT List ADTThe data is generally stored in key sequence in a list which has a head structure consisting of count pointers and address of compare function needed to compare the data in the list The data node contains the pointer to a data structure and a self referential pointer which points to the next node in the list The List ADT Functions is given below get Return an element from the list at any given position insert Insert an element at any position of the list remove Remove the first occurrence of any element from a non empty list removeAt Remove the element at a specified location from a non empty list replace Replace an element at any position by another element size Return the number of elements in the list isEmpty Return true if the list is empty otherwise return false isFull Return true if the list is full otherwise return false Stack ADTIn Stack ADT Implementation instead of data being stored in each node the pointer to data is stored The program allocates memory for the data and address is passed to the stack ADT The head node and the data nodes are encapsulated in the ADT The calling function can only see the pointer to the stack The stack head structure also contains a pointer to top and count of number of entries currently in stack push Insert an element at one end of the stack called top pop Remove and return the element at the top of the stack if it is not empty peek Return the element at the top of the stack without removing it if the stack is not empty size Return the number of elements in the stack isEmpty Return true if the stack is empty otherwise return false isFull Return true if the stack is full otherwise return false Queue ADTThe queue abstract data type ADT follows the basic design of the stack abstract data type Each node contains a void pointer to the data and the link pointer to the next element in the queue The program s responsibility is to allocate memory for storing the data enqueue Insert an element at the end of the queue dequeue Remove and return the first element of the queue if the queue is not empty peek Return the element of the queue without removing it if the queue is not empty size Return the number of elements in the queue isEmpty Return true if the queue is empty otherwise return false isFull Return true if the queue is full otherwise return false Features of ADT Abstraction The user does not need to know the implementation of the data structure Better Conceptualization ADT gives us a better conceptualization of the real world Robust The program is robust and has the ability to catch errors implementation of searching AlgorithmsSearch algorithm is the set of procedures used to locate the specific data from the collection of data The searching algorithm is always considered to be the fundamental procedure of computing And hence it is always said that the difference between the fast application and slower application is often decided by the searching algorithm used by the application We have various types of search algorithms like linear Fibonacci binary exponential etc But today we are going look at linear search algorithm and binary search algorithm in depth Linear search algorithmLinear search is also known as a sequential searching algorithm to find the element within the collection of data The algorithm begins from the first element of the list starts checking every element until the expected element is found If the element is not found in the list the algorithm traverses the whole list and return “element not found Consider the python program below def LinearSearch array n k for j in range n if array j k return j return array k n len array result LinearSearch array n k if result print Element not found else print Element found at index result OutputElement found at index Time Complexity of Linear SearchThe running time complexity of the linear search algorithm is O n for N number of elements in the list as the algorithm has to travel through each and every element to find the desired element Applications of Linear SearchUsed to find the desired element from the collection of data when the dataset is smallThe searching operations is less than itemsBinary searchBinary search is used with a similar concept i e to find the element from the list of elements Binary search algorithms are fast and effective in comparison to linear search algorithms The most important thing to note about binary search is that it works only on sorted lists of elements If the list is not sorted then the algorithm first sorts the elements using the sorting algorithm and then runs the binary search function to find the desired output We have two binary search methods recursive and iterative method Below is an iterative method using python programdef binarySearch arr k low high while low lt high mid low high low if arr mid k return mid elif arr mid lt k low mid else high mid return arr k result binarySearch arr k len arr if result print Element is present at index str result else print Not found OutputElement is present at index Below is recursive method using a python programdef BinarySearch arr k low high if high gt low mid low high low if arr mid k return mid elif arr mid gt k return BinarySearch arr k low mid else return BinarySearch arr k mid high else return arr k result BinarySearch arr k len arr if result print Element is present at index str result else print Not found OutputElement is present at index Time complexity of Binary SearchThe running time complexity for binary search is different for each scenario The best case time complexity is O which means the element is located at the mid pointer The Average and Worst Case time complexity is O log n which means the element to be found is located either on the left side or on the right side of the mid pointer Here n indicates the number of elements in the list The space complexity of the binary search algorithm is O Applications of Binary SearchThe binary search algorithm is used in the libraries of Java C etc It is used in another additional program like finding the smallest element or largest element in the arrayIt is used to implement a dictionaryImplementation of binary traversal tree in pythonBinary tree is special type of hierarchal data structures defined using nodes Basically its extended version of linked list Its a tree data structure where each node is allowed to have maximum two children node generally referred as Left Child and Right Child Hashing routing data for network traffic data compression and binary search trees are some of its application Key terminologies usedRoot The Topmost nodeHeight Total Number of edges from root node to last deepest nodeLeaf Node with no childrenDepth of a Tree The number of edges from the tree s node to the root is Internal Node Node having at least one Child Type of Binary TreePerfect Binary TreeA Binary Tree with all the interior node all nodes except leaf node have two children and all leaf node has same depthBalanced Binary TreeEvery tree where the maximum difference between right and left subtree height is Complete Binary TreeAll binary tree where every node is completely filled with or node Degenerate Binary TreeEvery binary tree where every internal node has only single child Applications of Binary Tree Used in d Video Games Highly used in router for tabling purpose Scheduling processes in OS implementation of binary tree in pythonimplementing the codeclass BinaryTree def init self value self left None self right None self value value def insert self value if self value if data lt self value if self left is None self left BinaryTree value else self left insert value elif data gt self value if self right is None self right BinaryTree value else self right insert value else self value value def PrintTree self if self left self left PrintTree print self data if self right self right PrintTree root BinaryTree root insert root insert root insert root insert root insert root PrintTree Traversal operationWhen we print the values of every node here we are using preorder traversal where left first left most child is printed then root then the right child Traversal PreOrder TraversalInOrder TraversalPostOrder TraversalPostOrder Traversal Here the Left child is visited first then the Right child node and then Root node The minutes changes in the PrintTree method is following def PrintTree self if self left self left PrintTree if self right self right PrintTree print self value PreOrder TraversalHere the Root is visited first then left child node and then right child node The minutes changes in the PrintTree method is following def PrintTree self print self value if self left self left PrintTree if self right self right PrintTree Search OperationSearching in a Binary TreeSearching in a binary tree is a very simple step as we have already discussed traversing a binary tree so we can use the traversing technique to get all the elements in a tree and and find our required element Here we are using preorder traversal you guys can use anyone of them def PrintTree self element if self left self left PrintTree if self data element print Found self data return else continue if self right self right PrintTree Deletion operationDeleting a element from the binary treedef delete Node root key if not root return root if root val gt key root left delete Node root left key elif root val lt key root right delete Node root right key else if not root right return root left if not root left return root right temp val root right mini val temp val val while temp val left temp val temp val left mini val temp val val root right deleteNode root right root val return rootExplanationThe above programs explain the procedure to delete a particular element from the given binary tree Here root represents the root node and key represents the element that needs to be deleted or has been ordered by the user Graph traversals techniquesGraphs are very useful data structures in solving many important mathematical challenges Depth First TraversalAlso called depth first search DFS this algorithm traverses a graph in a depth ward motion and uses a stack to remember to get the next vertex to start a search when a dead end occurs in any iteration We implement DFS for a graph in python using the set data types as they provide the required functionalities to keep track of visited and unvisited nodes class graph def init self gdict None if gdict is None gdict self gdict gdict Check for the visisted and unvisited nodesdef dfs graph start visited None if visited is None visited set visited add start print start for next in graph start visited dfs graph next visited return visitedgdict a set b c b set a d c set a d d set e e set a dfs gdict a Breadth First TraversalAlso called breadth first search BFS this algorithm traverses a graph breadth ward motion and uses a queue to remember to get the next vertex to start a search when a dead end occurs in any iteration Please visit this link in our website to understand the details of BFS steps for a graph We implement BFS for a graph in python using queue data structure discussed earlier When we keep visiting the adjacent unvisited nodes and keep adding it to the queue Then we start dequeue only the node which is left with no unvisited nodes We stop the program when there is no next adjacent node to be visited Exampleimport collectionsclass graph def init self gdict None if gdict is None gdict self gdict gdictdef bfs graph startnode Track the visited and unvisited nodes using queue seen queue set startnode collections deque startnode while queue vertex queue popleft marked vertex for node in graph vertex if node not in seen seen add node queue append node def marked n print n The graph dictionarygdict a set b c b set a d c set a d d set e e set a bfs gdict a Implementation of sorting Algorithms Sorting is defined as an arrangement of data in a certain order Sorting techniques are used to arrange data mostly numerical in an ascending or descending order Some of the real life examples of sorting are Telephone Directory It is a book that contains telephone numbers and addresses of people in alphabetical order Dictionary It is a huge collection of words along with their meanings in alphabetical order Contact List It is a list of contact numbers of people in alphabetical order on a mobile phone The different types of order are Increasing Order A set of values are said to be increasing order when every successive element is greater than its previous element For example Here the given sequence is in increasing order Decreasing Order A set of values are said to be in increasing order when the successive element is always less than the previous one For Example Here the given sequence is in decreasing order Non Increasing Order A set of values are said to be in non increasing order if every ith element present in the sequence is greater than or equal to its i th element This order occurs whenever there are numbers that are being repeated For Example Here repeated two times Non Decreasing Order A set of values are said to be in non decreasing order if every ith element present in the sequence is less than or equal to its i th element This order occurs whenever there are numbers that are being repeated For Example Here repeated two times Sorting TechniquesThe different implementations of sorting techniques in Python are Bubble SortSelection SortInsertion SortBubble SortBubble Sort is a simple sorting algorithm This sorting algorithm repeatedly compares two adjacent elements and swaps them if they are in the wrong order It is also known as the sinking sort It has a time complexity of O n in the average and worst cases scenarios and O n in the best case scenario Bubble sort can be visualized as a queue where people arrange themselves by swapping with each other so that they all can stand in ascending order of their heights Or in other words we compare two adjacent elements and see if their order is wrong if the order is wrong we swap them i e arr i gt arr j for lt i lt j lt s where s is the size of the array if array is to be in ascending order and vice versa Example Here we sort the following sequence using bubble sortSequence First Iteration gt Here the first elements are compared and remain the same because they are already in ascending order gt Here nd and rd elements are compared and swapped is less than according to ascending order gt Here rd and th elements are compared and swapped is less than according to ascending orderAt the end of the first iteration the largest element is at the rightmost position which is sorted correctly Second Iteration gt Here again the first elements are compared and remain the same because they are already in ascending order gt Here nd and rd elements are compared and swapped is less than in ascending order At the end of the second iteration the second largest element is at the adjacent position to the largest element Third Iteration gt Here the first elements are compared and swap according to ascending order The remaining elements are already sorted in the first and second Iterations After the three iterations the given array is sorted in ascending order So the final result is Implementation of bubble sort Python program for Bubble Sort Algorithm Implementationdef bubbleSort arr n len arr For loop to traverse through all element in an array for i in range n for j in range n i Range of the array is from to n i Swap the elements if the element found is greater than the adjacent element if arr j gt arr j arr j arr j arr j arr j Driver code Example to test the above codearr bubbleSort arr print Sorted array is for i in range len arr print d arr i Selection SortThis sorting technique repeatedly finds the minimum element and sort it in order Bubble Sort does not occupy any extra memory space During the execution of this algorithm two subarrays are maintained the subarray which is already sorted and the remaining subarray which is unsorted During the execution of Selection Sort for every iteration the minimum element of the unsorted subarray is arranged in the sorted subarray Selection Sort is a more efficient algorithm than bubble sort Sort has a Time Complexity of O n in the average worst and in the best cases Example Here we sort the following sequence using the selection sortSequence gt In the first traverse it finds the minimum element i e and it is placed at st position gt In the second traverse it finds the nd minimum element i e and it is placed at nd position gt In the third traverse it finds the next minimum element i e and it is placed at rd position After the above iterations the final array is in sorted order i e Implementation of Selection Sort Selection Sort algorithm in Pythondef selectionSort array size for s in range size min idx s for i in range s size For sorting in descending order for minimum element in each loop if array i lt array min idx min idx i Arranging min at the correct position array s array min idx array min idx array s Driver codedata size len data selectionSort data size print Sorted Array in Ascending Order is print data Insertion SortThis sorting algorithm maintains a sub array that is always sorted Values from the unsorted part of the array are placed at the correct position in the sorted part It is more efficient in practice than other algorithms such as selection sort or bubble sort Insertion Sort has a Time Complexity of O n in the average and worst case and O n in the best case Example Here we sort the following sequence using the insertion sortSequence gt In the first iteration the first elements are compared here is less than so insert before gt In the second iteration the nd and rd elements are compared here is less than so insert before gt After the second iteration elements are not in ascending order so first these two elements are arranged So insert before gt During this iteration the last elements are compared and swapped after all the previous elements are swapped Implementation of Insertion Sort Creating a function for insertion sort algorithmdef insertion sort list Outer loop to traverse on len list for i in range len list a list i Move elements of list to i which are greater to one position ahead of their current position j i while j gt and a lt list j list j list j j list j a return list Driver codelist print The unsorted list is list print The sorted new list is insertion sort list Application of search and sorting in real applicationsSearching is the process of locating a given object or data within a large set of data Sorting on the other hand is the arrangement of data in a specific required order The common application of these algorithms is in databases and other computer applications ConculsionHave handled data structure and algorithms in depth Am open to additions corrections and questions I believe we learn through each other Happy coding |
2022-06-26 19:11:23 |
医療系 |
医療介護 CBnews |
看護師の重点配置でICUの質と経済性を高める-先が見えない時代の戦略的病院経営(173) |
https://www.cbnews.jp/news/entry/20220624180558
|
新型コロナウイルス |
2022-06-27 05:00:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
ディズニーと比べたNetflix“最大の弱点”とは?「Disney+」は魔法の杖だ - 会計サミット2022 |
https://diamond.jp/articles/-/305042
|
disney |
2022-06-27 04:50:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
中露の「権威主義」に日米欧の民主主義が負ける!?古代ギリシア史で占う新冷戦の行方 - 賢者は歴史に学ぶ! 歴史入門 |
https://diamond.jp/articles/-/305350
|
古代ギリシア |
2022-06-27 04:45:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
銀行・保険・証券のビジネスと出世が激変、金融業界「DX大戦」変われないと敗北! - 金融DX大戦 |
https://diamond.jp/articles/-/305387
|
|
2022-06-27 04:40:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
物流・部材調達の難問、豪雨災害による「供給網寸断」見据えたBCP構築法 - サプライチェーン難問山積 |
https://diamond.jp/articles/-/305444
|
|
2022-06-27 04:35:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
大規模修繕に強いマンション管理会社ランキング!8位三井不動産レジデンシャルサービス、1位は? - DIAMONDランキング&データ |
https://diamond.jp/articles/-/305375
|
|
2022-06-27 04:30:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
中国経済「ゼロコロナ」で軟調続く、23年の景気回復を阻みかねない3つのリスク - 政策・マーケットラボ |
https://diamond.jp/articles/-/305347
|
|
2022-06-27 04:25:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
日大「林真理子理事長」誕生の裏で生じた“権力の二重構造”、改革機運に暗雲 - ニュース3面鏡 |
https://diamond.jp/articles/-/305096
|
二重構造 |
2022-06-27 04:22:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
年収が高い銀行ランキング2021最新版【トップ5】3メガバンク押さえ1位の地銀は? - ニッポンなんでもランキング! |
https://diamond.jp/articles/-/305345
|
人口減少 |
2022-06-27 04:20:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
年収が高い銀行ランキング2021最新版【全国85行完全版】 - ニッポンなんでもランキング! |
https://diamond.jp/articles/-/305344
|
人口減少 |
2022-06-27 04:20:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「月イチで」「女性なら誰でも…」社外取“バブル”で兼務続出、高額報酬の呆れた実態 - 今週の週刊ダイヤモンド ここが見どころ |
https://diamond.jp/articles/-/305369
|
上場企業 |
2022-06-27 04:15:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「聞く力」を持つ人がやっている、聞くだけじゃない本当のこと - 組織の病気~成長を止める真犯人~ 秋山進 |
https://diamond.jp/articles/-/305370
|
自分 |
2022-06-27 04:10:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
JR東海が新幹線で大規模訓練、京王線殺傷事件で安全対策に「2つの変化」 - News&Analysis |
https://diamond.jp/articles/-/305443
|
newsampampanalysisjr |
2022-06-27 04:05:00 |
北海道 |
北海道新聞 |
縄文遺跡で永遠の愛誓う 世界遺産の函館・垣ノ島遺跡で結婚式 |
https://www.hokkaido-np.co.jp/article/698307/
|
世界文化遺産 |
2022-06-27 04:06:44 |
ビジネス |
東洋経済オンライン |
JR西、「他県より鉄分多め」で攻める岡山観光戦略 新たな観光列車に加えファン向け企画が続々 | 特急・観光列車 | 東洋経済オンライン |
https://toyokeizai.net/articles/-/599099?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
東洋経済オンライン |
2022-06-27 04:30:00 |
コメント
コメントを投稿