util.py Mon Jul 12 21:42: : # util.py 2: # : # Licensing Information: Please do not distribute or publish solutions to this 4: #
|
|
- Anastasia Washington
- 5 years ago
- Views:
Transcription
1 util.py Mon Jul 12 21:42: : # util.py 2: # : # Licensing Information: Please do not distribute or publish solutions to this 4: # project. You are free to use and extend these projects for educational 5: # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by 6: # John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). 7: # For more info, see cs188/sp09/pacman.html 8: 9: import sys 10: import inspect 11: import heapq, random 12: 13: 14: """ 15: Data structures useful for implementing SearchAgents 16: """ 17: 18: class Stack: 19: "A container with a last-in-first-out (LIFO) queuing policy." 20: def init (self): 21: self.list = [] 22: 23: def push(self,item): 24: "Push item onto the stack" 25: self.list.append(item) 26: 27: def pop(self): 28: "Pop the most recently pushed item from the stack" 29: return self.list.pop() 30: 31: def isempty(self): 32: "Returns true if the stack is empty" 33: return len(self.list) == 0 34: 35: class Queue: 36: "A container with a first-in-first-out (FIFO) queuing policy." 37: def init (self): 38: self.list = [] 39: 40: def push(self,item): 41: "Enqueue the item into the queue" 42: self.list.insert(0,item) 43: 44: def pop(self): 45: """ 46: Dequeue the earliest enqueued item still in the queue. This 47: operation removes the item from the queue. 48: """ 49: return self.list.pop() 50: 51: def isempty(self): 52: "Returns true if the queue is empty" 53: return len(self.list) == 0 54: 55: class PriorityQueue: 56: """ 57: Implements a priority queue data structure. Each inserted item 58: has a priority associated with it and the client is usually interested 59: in quick retrieval of the lowest-priority item in the queue. This 60: data structure allows O(1) access to the lowest-priority item. 61: 62: Note that this PriorityQueue does not allow you to change the priority 63: of an item. However, you may insert the same item multiple times with 64: different priorities. 65: """
2 util.py Mon Jul 12 21:42: : def init (self): 67: self.heap = [] 68: 69: def push(self, item, priority): 70: pair = (priority,item) 71: heapq.heappush(self.heap,pair) 72: 73: def pop(self): 74: (priority,item) = heapq.heappop(self.heap) 75: return item 76: 77: def isempty(self): 78: return len(self.heap) == 0 79: 80: class PriorityQueueWithFunction(PriorityQueue): 81: """ 82: Implements a priority queue with the same push/pop signature of the 83: Queue and the Stack classes. This is designed for drop-in replacement for 84: those two classes. The caller has to provide a priority function, which 85: extracts each item s priority. 86: """ 87: def init (self, priorityfunction): 88: "priorityfunction (item) -> priority" 89: self.priorityfunction = priorityfunction # store the priority function 90: PriorityQueue. init (self) # super-class initializer 91: 92: def push(self, item): 93: "Adds an item to the queue with priority from the priority function" 94: PriorityQueue.push(self, item, self.priorityfunction(item)) 95: 96: 97: def manhattandistance( xy1, xy2 ): 98: "Returns the Manhattan distance between points xy1 and xy2" 99: return abs( xy1[0] - xy2[0] ) + abs( xy1[1] - xy2[1] ) 100: 101: """ 102: Data structures and functions useful for various course projects 103: 104: The search project should not need anything below this line. 105: """ 106: 107: class Counter(dict): 108: """ 109: A counter keeps track of counts for a set of keys. 110: 111: The counter class is an extension of the standard python 112: dictionary type. It is specialized to have number values 113: (integers or floats), and includes a handful of additional 114: functions to ease the task of counting data. In particular, 115: all keys are defaulted to have value 0. Using a dictionary: 116: 117: a = {} 118: print a[ test ] 119: 120: would give an error, while the Counter class analogue: 121: 122: >>> a = Counter() 123: >>> print a[ test ] 124: 0 125: 126: returns the default 0 value. Note that to reference a key 127: that you know is contained in the counter, 128: you can still use the dictionary syntax: 129: 130: >>> a = Counter()
3 util.py Mon Jul 12 21:42: : >>> a[ test ] = 2 132: >>> print a[ test ] 133: 2 134: 135: This is very useful for counting things without initializing their counts, 136: see for example: 137: 138: >>> a[ blah ] += 1 139: >>> print a[ blah ] 140: 1 141: 142: The counter also includes additional functionality useful in implementing 143: the classifiers for this assignment. Two counters can be added, 144: subtracted or multiplied together. See below for details. They can 145: also be normalized and their total count and arg max can be extracted. 146: """ 147: def getitem (self, idx): 148: self.setdefault(idx, 0) 149: return dict. getitem (self, idx) 150: 151: def incrementall(self, keys, count): 152: """ 153: Increments all elements of keys by the same count. 154: 155: >>> a = Counter() 156: >>> a.incrementall([ one, two, three ], 1) 157: >>> a[ one ] 158: 1 159: >>> a[ two ] 160: 1 161: """ 162: for key in keys: 163: self[key] += count 164: 165: def argmax(self): 166: """ 167: Returns the key with the highest value. 168: """ 169: if len(self.keys()) == 0: return None 170: all = self.items() 171: values = [x[1] for x in all] 172: maxindex = values.index(max(values)) 173: return all[maxindex][0] 174: 175: def sortedkeys(self): 176: """ 177: Returns a list of keys sorted by their values. Keys 178: with the highest values will appear first. 179: 180: >>> a = Counter() 181: >>> a[ first ] = : >>> a[ second ] = 4 183: >>> a[ third ] = 1 184: >>> a.sortedkeys() 185: [ second, third, first ] 186: """ 187: sorteditems = self.items() 188: compare = lambda x, y: sign(y[1] - x[1]) 189: sorteditems.sort(cmp=compare) 190: return [x[0] for x in sorteditems] 191: 192: def totalcount(self): 193: """ 194: Returns the sum of counts for all keys. 195: """
4 util.py Mon Jul 12 21:42: : return sum(self.values()) 197: 198: def normalize(self): 199: """ 200: Edits the counter such that the total count of all 201: keys sums to 1. The ratio of counts for all keys 202: will remain the same. Note that normalizing an empty 203: Counter will result in an error. 204: """ 205: total = float(self.totalcount()) 206: if total == 0: return 207: for key in self.keys(): 208: self[key] = self[key] / total 209: 210: def divideall(self, divisor): 211: """ 212: Divides all counts by divisor 213: """ 214: divisor = float(divisor) 215: for key in self: 216: self[key] /= divisor 217: 218: def copy(self): 219: """ 220: Returns a copy of the counter 221: """ 222: return Counter(dict.copy(self)) 223: 224: def mul (self, y ): 225: """ 226: Multiplying two counters gives the dot product of their vectors where 227: each unique label is a vector element. 228: 229: >>> a = Counter() 230: >>> b = Counter() 231: >>> a[ first ] = : >>> a[ second ] = 4 233: >>> b[ first ] = 3 234: >>> b[ second ] = 5 235: >>> a[ third ] = : >>> a[ fourth ] = : >>> a * b 238: : """ 240: sum = 0 241: x = self 242: if len(x) > len(y): 243: x,y = y,x 244: for key in x: 245: if key not in y: 246: continue 247: sum += x[key] * y[key] 248: return sum 249: 250: def radd (self, y): 251: """ 252: Adding another counter to a counter increments the current counter 253: by the values stored in the second counter. 254: 255: >>> a = Counter() 256: >>> b = Counter() 257: >>> a[ first ] = : >>> a[ second ] = 4 259: >>> b[ first ] = 3 260: >>> b[ third ] = 1
5 util.py Mon Jul 12 21:42: d 261: >>> a += b 262: >>> a[ first ] 263: 1 264: """ 265: for key, value in y.items(): 266: self[key] += value 267: 268: def add ( self, y ): 269: """ 270: Adding two counters gives a counter with the union of all keys and 271: counts of the second added to counts of the first. 272: 273: >>> a = Counter() 274: >>> b = Counter() 275: >>> a[ first ] = : >>> a[ second ] = 4 277: >>> b[ first ] = 3 278: >>> b[ third ] = 1 279: >>> (a + b)[ first ] 280: 1 281: """ 282: addend = Counter() 283: for key in self: 284: if key in y: 285: addend[key] = self[key] + y[key] 286: else: 287: addend[key] = self[key] 288: for key in y: 289: if key in self: 290: continue 291: addend[key] = y[key] 292: return addend 293: 294: def sub ( self, y ): 295: """ 296: Subtracting a counter from another gives a counter with the union of all keys an 297: counts of the second subtracted from counts of the first. 298: 299: >>> a = Counter() 300: >>> b = Counter() 301: >>> a[ first ] = : >>> a[ second ] = 4 303: >>> b[ first ] = 3 304: >>> b[ third ] = 1 305: >>> (a - b)[ first ] 306: : """ 308: addend = Counter() 309: for key in self: 310: if key in y: 311: addend[key] = self[key] - y[key] 312: else: 313: addend[key] = self[key] 314: for key in y: 315: if key in self: 316: continue 317: addend[key] = -1 * y[key] 318: return addend 319: 320: def raisenotdefined(): 321: print "Method not implemented: %s" % inspect.stack()[1][3] 322: sys.exit(1) 323: 324: def normalize(vectororcounter):
6 util.py Mon Jul 12 21:42: : """ 326: normalize a vector or counter by dividing each value by the sum of all values 327: """ 328: normalizedcounter = Counter() 329: if type(vectororcounter) == type(normalizedcounter): 330: counter = vectororcounter 331: total = float(counter.totalcount()) 332: if total == 0: return counter 333: for key in counter.keys(): 334: value = counter[key] 335: normalizedcounter[key] = value / total 336: return normalizedcounter 337: else: 338: vector = vectororcounter 339: s = float(sum(vector)) 340: if s == 0: return vector 341: return [el / s for el in vector] 342: 343: def nsample(distribution, values, n): 344: if sum(distribution)!= 1: 345: distribution = normalize(distribution) 346: rand = [random.random() for i in range(n)] 347: rand.sort() 348: samples = [] 349: samplepos, distpos, cdf = 0,0, distribution[0] 350: while samplepos < n: 351: if rand[samplepos] < cdf: 352: samplepos += 1 353: samples.append(values[distpos]) 354: else: 355: distpos += 1 356: cdf += distribution[distpos] 357: return samples 358: 359: def sample(distribution, values = None): 360: if type(distribution) == Counter: 361: items = distribution.items() 362: distribution = [i[1] for i in items] 363: values = [i[0] for i in items] 364: if sum(distribution)!= 1: 365: distribution = normalize(distribution) 366: choice = random.random() 367: i, total= 0, distribution[0] 368: while choice > total: 369: i += 1 370: total += distribution[i] 371: return values[i] 372: 373: def samplefromcounter(ctr): 374: items = ctr.items() 375: return sample([v for k,v in items], [k for k,v in items]) 376: 377: def getprobability(value, distribution, values): 378: """ 379: Gives the probability of a value under a discrete distribution 380: defined by (distributions, values). 381: """ 382: total = : for prob, val in zip(distribution, values): 384: if val == value: 385: total += prob 386: return total 387: 388: def flipcoin( p ): 389: r = random.random()
7 util.py Mon Jul 12 21:42: : return r < p 391: 392: def choosefromdistribution( distribution ): 393: "Takes either a counter or a list of (prob, key) pairs and samples" 394: if type(distribution) == dict or type(distribution) == Counter: 395: return sample(distribution) 396: r = random.random() 397: base = : for prob, element in distribution: 399: base += prob 400: if r <= base: return element 401: 402: def nearestpoint( pos ): 403: """ 404: Finds the nearest grid point to a position (discretizes). 405: """ 406: ( current_row, current_col ) = pos 407: 408: grid_row = int( current_row ) 409: grid_col = int( current_col ) 410: return ( grid_row, grid_col ) 411: 412: def sign( x ): 413: """ 414: Returns 1 or -1 depending on the sign of x 415: """ 416: if( x >= 0 ): 417: return 1 418: else: 419: return : 421: def arrayinvert(array): 422: """ 423: Inverts a matrix stored as a list of lists. 424: """ 425: result = [[] for i in array] 426: for outer in array: 427: for inner in range(len(outer)): 428: result[inner].append(outer[inner]) 429: return result 430: 431: def matrixaslist( matrix, value = True ): 432: """ 433: Turns a matrix into a list of coordinates matching the specified value 434: """ 435: rows, cols = len( matrix ), len( matrix[0] ) 436: cells = [] 437: for row in range( rows ): 438: for col in range( cols ): 439: if matrix[row][col] == value: 440: cells.append( ( row, col ) ) 441: return cells 442: 443: def lookup(name, namespace): 444: """ 445: Get a method or class from any imported module from its name. 446: Usage: lookup(functionname, globals()) 447: """ 448: dots = name.count(. ) 449: if dots > 0: 450: modulename, objname =..join(name.split(. )[:-1]), name.split(. )[-1] 451: module = import (modulename) 452: return getattr(module, objname) 453: else: 454: modules = [obj for obj in namespace.values() if str(type(obj)) == "<type module
8 util.py Mon Jul 12 21:42: >"] 455: options = [getattr(module, name) for module in modules if name in dir(module)] 456: options += [obj[1] for obj in namespace.items() if obj[0] == name ] 457: if len(options) == 1: return options[0] 458: if len(options) > 1: raise Exception, Name conflict for %s 459: raise Exception, %s not found as a method or class % name 460: 461: def pause(): 462: """ 463: Pauses the output stream awaiting user feedback. 464: """ 465: print "<Press enter/return to continue>" 466: raw_input() 467: 468: 469: ## code to handle timeouts 470: import signal 471: class TimeoutFunctionException(Exception): 472: """Exception to raise on a timeout""" 473: pass 474: 475: class TimeoutFunction: 476: 477: def init (self, function, timeout): 478: "timeout must be at least 1 second. WHY??" 479: self.timeout = timeout 480: self.function = function 481: 482: def handle_timeout(self, signum, frame): 483: raise TimeoutFunctionException() 484: 485: def call (self, *args): 486: if not SIGALRM in dir(signal): 487: return self.function(*args) 488: old = signal.signal(signal.sigalrm, self.handle_timeout) 489: signal.alarm(self.timeout) 490: try: 491: result = self.function(*args) 492: finally: 493: signal.signal(signal.sigalrm, old) 494: signal.alarm(0) 495: return result
What is an algorithm?
Announcements CS 142 Stacks & Queues Program 3 has been assigned due 10/6 by 11:55pm Program details on website 2 Creating new Data Structures We ve used objects to create new data types such as Point,
More informationLecture 12 ADTs and Stacks
Lecture 12 ADTs and Stacks Modularity Divide the program into smaller parts Advantages Keeps the complexity managable Isolates errors (parts can be tested independently) Can replace parts easily Eliminates
More informationQueues. Queue ADT Queue Implementation Priority Queues
Queues Queue ADT Queue Implementation Priority Queues Queue A restricted access container that stores a linear collection. Very common for solving problems in computer science that require data to be processed
More informationAssignment#2 Uninformed Search in Pac-Man i Due Wednesday, September 27
Assignment#2 Uninformed Search in Pac-Man i Due Wednesday, September 27 There are two exercises in this lab: 1. Depth-First Search (DFS) 2. Breadth-First Search (BFS) Introduction As in the first assignment,
More informationWalk through previous lectures
Walk through previous lectures Tuple tuple_name = (value, value,..., value) A way of packing multiple values into a variable >>> x = 3 >>> y = -5 >>> p = (x, y, 42) >>> p (3, -5, 42) name, name,..., name
More information(b) If a heap has n elements, what s the height of the tree?
CISC 5835 Algorithms for Big Data Fall, 2018 Homework Assignment #4 1 Answer the following questions about binary tree and heap: (a) For a complete binary tree of height 4 (we consider a tree with just
More informationCS-141 Exam 2 Review November 10, 2017 Presented by the RIT Computer Science Community
CS-141 Exam 2 Review November 10, 2017 Presented by the RIT Computer Science Community http://csc.cs.rit.edu Linked Lists 1. You are given the linked sequence: 1 2 3. You may assume that each node has
More informationPriority Queue ADT. Revised based on textbook author s notes.
Priority Queue ADT Revised based on textbook author s notes. Priority Queues Some applications require the use of a queue in which items are assigned a priority. higher priority items are dequeued first.
More informationCS 206 Introduction to Computer Science II
CS 206 Introduction to Computer Science II 07 / 26 / 2016 Instructor: Michael Eckmann Today s Topics Comments/Questions? Stacks and Queues Applications of both Priority Queues Michael Eckmann - Skidmore
More informationPart I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming
2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float
More informationChapter 8 : Computer Science. Datastructures: Class XII ( As per CBSE Board) lists, stacks, queues. Visit : python.mykvs.in for regular updates
Chapter 8 : Computer Science Class XII ( As per CBSE Board) Datastructures: lists, stacks, queues It a way of organizing and storing data in such a manner so that it can be accessed and work over it can
More informationCSC148 Week 2. Larry Zhang
CSC148 Week 2 Larry Zhang 1 Admin Discussion board is up (link on the course website). 2 Outline for this week Abstract Data Type Stack Queue 3 Abstract Data Type (ADT) 4 What is an abstract data type
More informationCSCA48 Summer 2018 Week 3: Priority Queue, Linked Lists. Marzieh Ahmadzadeh University of Toronto Scarborough
CSCA48 Summer 2018 Week 3: Priority Queue, Linked Lists Marzieh Ahmadzadeh University of Toronto Scarborough Administrative Detail All practicals are up on course website. Term test # 1 and #2 schedule
More informationOutline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures
Outline Chapter 5: and Queues 1 Chapter 5: and Queues Chapter 5: and Queues The Stack ADT A Container Class for Last-In-First-Out Access A stack is a last in, first out (LIFO) structure, i.e. a list-like
More information1 P age DS & OOPS / UNIT II
UNIT II Stacks: Definition operations - applications of stack. Queues: Definition - operations Priority queues - De que Applications of queue. Linked List: Singly Linked List, Doubly Linked List, Circular
More informationCS 206 Introduction to Computer Science II
CS 206 Introduction to Computer Science II 03 / 31 / 2017 Instructor: Michael Eckmann Today s Topics Questions? Comments? finish RadixSort implementation some applications of stack Priority Queues Michael
More informationDo not turn this page until you have received the signal to start. In the meantime, please read the instructions below carefully.
CSC 148 H1 / L0101 Term Test # 2 13 March 2013 Duration: Aids Allowed: 50 minutes None Student Number: Last (Family) Name(s): First (Given) Name(s): Do not turn this page until you have received the signal
More informationPython. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline
Python Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar December 28, 2011 1 Outline Introduction Installation and Use Distinct Features Python Basics Functional Example Comparisons with
More informationDownload Python from Any version will do for this class
Let s Start Python Let s Start! Download Python from www.python.org Any version will do for this class By and large they are all mutually compatible Recommended version: 2.1.1 or 2.2 Oldest version still
More informationData Structures I: Linked Lists
Lab 4 Data Structures I: Linked Lists Lab Objective: Analyzing and manipulating data are essential skills in scientific computing. Storing, retrieving, and rearranging data take time. As a dataset grows,
More informationWhere does the insert method place the new entry in the array? Assume array indexing starts from 0(zero).
Suppose we have a circular array implementation of the queue,with ten items in the queue stored at data[2] through data[11]. The current capacity of an array is 12. Where does the insert method place the
More informationName CPTR246 Spring '17 (100 total points) Exam 3
Name CPTR246 Spring '17 (100 total points) Exam 3 1. Linked Lists Consider the following linked list of integers (sorted from lowest to highest) and the changes described. Make the necessary changes in
More informationStudent Number: Lab day:
CSC 148H1 Summer 2008 Midterm Test Duration 60 minutes Aids allowed: none Last Name: Student Number: Lab day: First Name: Lecture Section: L0101 Instructor: R. Danek Do not turn this page until you have
More informationCSCA48 Winter 2018 Week 3: Priority Queue, Linked Lists. Marzieh Ahmadzadeh, Nick Cheng University of Toronto Scarborough
CSCA48 Winter 2018 Week 3: Priority Queue, Linked Lists Marzieh Ahmadzadeh, Nick Cheng University of Toronto Scarborough Administrative Detail Term test # 1 and #2 schedule is now on course website We
More informationParsing Scheme (+ (* 2 3) 1) * 1
Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes
More informationQueues The Queue ADT. The Queue ADT is defined by the following operations: init Initialize a new empty queue.
Queues This chapter presents two ADTs: the Queue and the Priority Queue. In real life, a queue is a line of customers waiting for service of some kind. In most cases, the first customer in line is the
More informationStructure and Interpretation of Computer Programs Spring 2014 Final (with corrections)
CS 61A Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections) INSTRUCTIONS You have 3 hours to complete the exam. The exam is open book and open notes. You may not use a
More informationA linear-list Data Structure where - addition of elements to and - removal of elements from are restricted to the first element of the list.
A linear-list Data Structure where - addition of elements to and - removal of elements from are restricted to the first element of the list. the first element of the list a new element to (the Top of)
More informationLab 1 - Basic ipython Tutorial (EE 126 Fall 2014)
Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014) modified from Berkeley Python Bootcamp 2013 https://github.com/profjsb/python-bootcamp and Python for Signal Processing http://link.springer.com/book/10.1007%2f978-3-319-01342-8
More informationWeek 6. Data structures
1 2 3 4 5 n Week 6 Data structures 6 7 n 8 General remarks We start considering Part III Data Structures from CLRS. As a first example we consider two special of buffers, namely stacks and queues. Reading
More informationtable1 = [ [1, 2, 3, 4], [4, 5, 6, 7], [8, 9,10,11] ] we get: >>> sumcol(table1,0) 13 >>> sumcol(table1,1) 16
Algorithms and Data Structures : Week 1 Representations of data structures Multi-Dimensional Array Tasks Sum Columns of Table Write a function to sum the columns of a 2 dimensional array (i.e. a list of
More informationCS24 Week 4 Lecture 2
CS24 Week 4 Lecture 2 Kyle Dewey Overview Linked Lists Stacks Queues Linked Lists Linked Lists Idea: have each chunk (called a node) keep track of both a list element and another chunk Need to keep track
More informationDSC 201: Data Analysis & Visualization
DSC 201: Data Analysis & Visualization Arrays Dr. David Koop Class Example class Rectangle: def init (self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h def set_corner(self, x, y): self.x =
More informationData structure and algorithm in Python
Data structure and algorithm in Python Array-Based Sequences Xiaoping Zhang School of Mathematics and Statistics, Wuhan University Table of contents 1. Python s Sequence Types 2. Low-Level s Arrays 3.
More informationPriority Queues. Binary Heaps
Priority Queues An internet router receives data packets, and forwards them in the direction of their destination. When the line is busy, packets need to be queued. Some data packets have higher priority
More informationCSCA48 Term Test 1 Seminar
CSCA48 Term Test 1 Seminar Brian Chen and Joshua Concon January 30, 2017 Implementation class LLNode ( object ): A Node in a singly - linked list def init (self, data, link = None ): ( LLNode, object )
More informationCOSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor
COSC160: Data Structures: Lists and Queues Jeremy Bolton, PhD Assistant Teaching Professor Outline I. Queues I. FIFO Queues I. Usage II. Implementations II. LIFO Queues (Stacks) I. Usage II. Implementations
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationScope & Symbol Table. l Most modern programming languages have some notion of scope.
Scope & Symbol Table l Most modern programming languages have some notion of scope. l Scope defines the lifetime of a program symbol. l If a symbol is no longer accessible then we say that it is out of
More information50 MATHCOUNTS LECTURES (6) OPERATIONS WITH DECIMALS
BASIC KNOWLEDGE 1. Decimal representation: A decimal is used to represent a portion of whole. It contains three parts: an integer (which indicates the number of wholes), a decimal point (which separates
More informationIterators & Generators
Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:
More informationShort Python function/method descriptions:
Last Name First Name Student#. Short Python function/method descriptions: builtins : len(x) -> integer Return the length of the list, tuple, dict, or string x. max(l) -> value Return the largest value
More informationLecture no
Advanced Algorithms and Computational Models (module A) Lecture no. 3 29-09-2014 Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 28 Expressions, Operators and Precedence Sequence Operators The following
More information.:: UNIT 4 ::. STACK AND QUEUE
.:: UNIT 4 ::. STACK AND QUEUE 4.1 A stack is a data structure that supports: Push(x) Insert x to the top element in stack Pop Remove the top item from stack A stack is collection of data item arrange
More informationCOMP519 Web Programming Lecture 21: Python (Part 5) Handouts
COMP519 Web Programming Lecture 21: Python (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Functions
More informationCMSC Introduction to Algorithms Spring 2012 Lecture 7
CMSC 351 - Introduction to Algorithms Spring 2012 Lecture 7 Instructor: MohammadTaghi Hajiaghayi Scribe: Rajesh Chitnis 1 Introduction In this lecture we give an introduction to Data Structures like arrays,
More informationChapter 8 Long-term decision-making and search
Chapter 8 Long-term decision-making and search 6.01 Spring 2011 April 25, 2011 296 Chapter 8 Long-term decision-making and search In the lab exercises of this course, we have implemented several brains
More informationDATA STRUCTURE UNIT I
DATA STRUCTURE UNIT I 1. What is Data Structure? A data structure is a mathematical or logical way of organizing data in the memory that consider not only the items stored but also the relationship to
More informationDEEPIKA KAMBOJ UNIT 2. What is Stack?
What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you
More informationLecture 8: Simple Calculator Application
Lecture 8: Simple Calculator Application Postfix Calculator Dr Kieran T. Herley Department of Computer Science University College Cork 2016/17 KH (27/02/17) Lecture 8: Simple Calculator Application 2016/17
More information5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.
Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley
More informationADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )
ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) Unit - 2 By: Gurpreet Singh Dean Academics & H.O.D. (C.S.E. / I.T.) Yamuna Institute of Engineering & Technology, Gadholi What is a Stack? A stack is a
More informationSTACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:
STACKS A stack is a linear data structure for collection of items, with the restriction that items can be added one at a time and can only be removed in the reverse order in which they were added. The
More informationCSc 120. Introduction to Computer Programming II. 14: Stacks and Queues. Adapted from slides by Dr. Saumya Debray
CSc 120 Introduction to Computer Programming II Adapted from slides by Dr. Saumya Debray 14: Stacks and Queues linear data structures 2 Linear data structures A linear data structure is a collec6on of
More informationUnit 4: Stacks and Queues
Unit 4: Stacks and Queues Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland June 1, 2011 ENGI 4892 (MUN) Unit 4 June 1, 2011 1 / 24 1 Stacks
More informationCSC148-Section:L0301
Slides adapted from Professor Danny Heap course material winter17 CSC148-Section:L0301 Week#3-Monday Instructed by AbdulAziz Al-Helali a.alhelali@mail.utoronto.ca Office hours: Wednesday 11-1, BA2230.
More informationHere n is a variable name. The value of that variable is 176.
UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence
More informationPriority Queues and Heaps (continues) Chapter 13: Heaps, Balances Trees and Hash Tables Hash Tables In-class Work / Suggested homework.
Outline 1 Chapter 13: Heaps, Balances Trees and Hash Tables Priority Queues and Heaps (continues) Hash Tables Binary Heaps Binary Heap is a complete binary tree, whose nodes are labeled with integer values
More informationStructure and Flow. CS 3270 Chapter 5
Structure and Flow CS 3270 Chapter 5 Python Programs Are made up of modules One module is the main (top-level) module The first one loaded (even if it s the interpreter) Its module object has main as its
More informationLists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50
Lists, Stacks, and Queues (Lists, Stacks, and Queues ) Data Structures and Programming Spring 2016 1 / 50 Abstract Data Types (ADT) Data type a set of objects + a set of operations Example: integer set
More informationStructure and Interpretation of Computer Programs
CS 61A Fall 2013 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,
More informationData Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1
Data Structure using C++ Lecture 04 Reading Material Data Structures and algorithm analysis in C++ Chapter. 3 3.1, 3.2, 3.2.1 Summary Stack Operations on a stack Representing stacks Converting an expression
More informationCS6202 - PROGRAMMING & DATA STRUCTURES I Unit IV Part - A 1. Define Stack. A stack is an ordered list in which all insertions and deletions are made at one end, called the top. It is an abstract data type
More information1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures
1.00 Lecture 26 Data Structures: Introduction Stacks Reading for next time: Big Java: 19.1-19.3 Data Structures Set of primitives used in algorithms, simulations, operating systems, applications to: Store
More informationData structure and algorithm in Python
Data structure and algorithm in Python Stacks, Queues and Deques Xiaoping Zhang School of Mathematics and Statistics, Wuhan University Table of contents 1. Stacks 2. Queue 3. Double-Ended Queues 1 Stacks
More informationPython debugging and beautification
Python debugging and beautification #!/usr/bin/env python # # # THIS CODE DOES NOT WORK import sys def read(a): myfile = open(a,'r'): for i in myfile: yield i myfile.close() def count_chars(a): sum = 0
More informationCS3110 Spring 2016 Lecture 6: Modules
CS3110 Spring 2016 Lecture 6: Modules Modules are the O part of OCaml, influenced by objects in Java. We see the evolution: Classic ML, CambridgeML (CAML), and finally OCaml. David McQueen is writing the
More informationProgramming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras
Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 54 Assignment on Data Structures (Refer Slide
More informationOutline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators
Chapter 4: Linked Structures and Outline 1 Chapter 4: Linked Structures and Chapter 4: Linked Structures and Using the ListNode Class Ideas about Linked List Implementation We have a pretty good feeling
More informationComputer Science 9608 (Notes) Chapter: 4.1 Computational thinking and problem-solving
In Computer Science, an abstract data type (ADT) is a mathematical model for a certain data type or structures. This doesn t mean that the ADTs cannot be programmed. But that we must first understand them
More informationException Handling. Genome 559
Exception Handling Genome 559 Review - classes Use your own classes to: - package together related data - conceptually organize your code - force a user to conform to your expectations Class constructor:
More informationCSE030 Fall 2012 Final Exam Friday, December 14, PM
CSE030 Fall 2012 Final Exam Friday, December 14, 2012 3-6PM Write your name here and at the top of each page! Name: Select your lab session: Tuesdays Thursdays Paper. If you have any questions or need
More informationTry and Error. Python debugging and beautification
Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords
More informationBabu Madhav Institute of Information Technology, UTU 2015
Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?
More informationComputational Physics
Computational Physics numerical methods with C++ (and UNIX) 2018-19 Fernando Barao Instituto Superior Tecnico, Dep. Fisica email: fernando.barao@tecnico.ulisboa.pt Computational Physics 2018-19 (Phys Dep
More informationStacks and Queues. CSE Data Structures April 12, 2002
Stacks and Queues CSE 373 - Data Structures April 12, 2002 Readings and References Reading Section 3.3 and 3.4, Data Structures and Algorithm Analysis in C, Weiss Other References 12-Apr-02 CSE 373 - Data
More informationME/CS 132: Advanced Robotics: Navigation and Vision
ME/CS 132: Advanced Robotics: Navigation and Vision Lecture #5: Search Algorithm 1 Yoshiaki Kuwata 4/12/2011 Lecture Overview Introduction Label Correcting Algorithm Core idea Depth-first search Breadth-first
More informationImplementations. Priority Queues. Heaps and Heap Order. The Insert Operation CS206 CS206
Priority Queues An internet router receives data packets, and forwards them in the direction of their destination. When the line is busy, packets need to be queued. Some data packets have higher priority
More informationCSE 2123: Collections: Priority Queues. Jeremy Morris
CSE 2123: Collections: Priority Queues Jeremy Morris 1 Collections Priority Queue Recall: A queue is a specific type of collection Keeps elements in a particular order We ve seen two examples FIFO queues
More informationComputational Integer Programming. Lecture 4: Python. Dr. Ted Ralphs
Computational Integer Programming Lecture 4: Python Dr. Ted Ralphs Computational MILP Lecture 4 1 Why Python? Pros As with many high-level languages, development in Python is quick and painless (relative
More informationComputer Programming
Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: Recap of Arrays and Simultaneous Equations (S31 S35) Dr. Deepak B. Phatak & Dr.
More informationPython memento TI-Smart Grids
Python memento TI-Smart Grids Genoveva Vargas-Solar French Council of Scientific Research, LIG genoveva.vargas@imag.fr http://vargas-solar.com/data-centric-smart-everything/ * This presentation was created
More informationCS 331 Midterm Exam 2
CS 331 Midterm Exam 2 Friday, November 4 th, 2016 Please bubble your answers in on the provided answer sheet. Also be sure to write and bubble in your student ID number (without the leading A ). 1. What
More informationAbstract Data Types Chapter 1
Abstract Data Types Chapter 1 Part Two Bags A bag is a basic container like a shopping bag that can be used to store collections. There are several variations: simple bag grab bag counting bag 2 Bag ADT
More informationEEE2020 Data Structures and Algorithms Abstract Data Types: Stacks and Queues
EEE2020 Data Structures and Algorithms Abstract Data Types: Stacks and Queues W. Jinho Song School of Electrical & Electronic Engineering Yonsei University 1 Textbook Chapter and Objectives Textbook "Data
More informationCPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues
CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues Alan J. Hu (Slides borrowed from Steve Wolfman) Be sure to check course webpage! http://www.ugrad.cs.ubc.ca/~cs221 1 Lab 1 is available.
More informationStacks and queues (chapters 6.6, 15.1, 15.5)
Stacks and queues (chapters 6.6, 15.1, 15.5) So far... Complexity analysis For recursive and iterative programs Sorting algorithms Insertion, selection, quick, merge, (intro, dual-pivot quick, natural
More informationMEMOIZATION, RECURSIVE DATA, AND SETS
MEMOIZATION, RECURSIVE DATA, AND SETS 4b COMPUTER SCIENCE 61A July 18, 2013 1 Memoization Later in this class, you ll learn about orders of growth and how to analyze exactly how efficient (or inefficient)
More informationSTACKS AND QUEUES. Problem Solving with Computers-II
STACKS AND QUEUES Problem Solving with Computers-II 2 Stacks container class available in the C++ STL Container class that uses the Last In First Out (LIFO) principle Methods i. push() ii. iii. iv. pop()
More informationIntroduction to Python for Research Workflows
Introduction to Python for Research Workflows David A. Lifka, Ph.D. Cornell Center for Advanced Computing January 20, 2012 1/20/2012 www.cac.cornell.edu 1 Research Computing Ecosystem Desktop Tools Editors
More informationMUTABLE LISTS AND DICTIONARIES 4
MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable
More informationObject Model Comparisons
Object Model Comparisons 1 Languages are designed, just like programs Someone decides what the language is for Someone decides what features it's going to have Can't really understand a language until
More informationShort Python function/method descriptions:
Last Name First Name Student#. Short Python function/method descriptions: builtins : len(x) -> integer Return the length of the list, tuple, dict, or string x. max(l) -> value Return the largest value
More informationBinghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13
Introduction to C Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Problem: Too Many Details For example: Lab 7 Bubble Sort Needed to keep track of too many details! Outer Loop When do
More informationCreating a new data type
Appendix B Creating a new data type Object-oriented programming languages allow programmers to create new data types that behave much like built-in data types. We will explore this capability by building
More informationCSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills
CSCI 136 Data Structures & Advanced Programming Lecture 14 Fall 2018 Instructor: Bills Announcements Mid-Term Review Session Monday (10/15), 7:00-8:00 pm in TPL 203 No prepared remarks, so bring questions!
More informationMatriculation number:
Department of Informatics Prof. Dr. Michael Böhlen Binzmühlestrasse 14 8050 Zurich Phone: +41 44 635 4333 Email: boehlen@ifi.uzh.ch AlgoDat Repetition Exam Spring 2018 18.05.2018 Name: Matriculation number:
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 10 Thomas Wies New York University Review Last class ML Outline Modules Sources: PLP, 3.3.4, 3.3.5, 3.8 McConnell, Steve. Code Complete, Second Edition,
More informationThere are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:
Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited
More information*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN
PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN
More information