Introduction to Python! Lecture 3

Size: px
Start display at page:

Download "Introduction to Python! Lecture 3"

Transcription

1 Introduction to Python Lecture 3

2 Summary Summary Dictionaries Lists comprehensions Dictionaries comprehensions Files Comparisons Lists repetition

3 0 Arrays Characteristics: contiguous memory zones arrays hold elements of the same type Advantages: access elements in a single step, based on index [O(1)] Disadvantages: the size of the array is established from the beginning no guarantee that the memory zone after the last element in the array will be available to extend the array, so growing an array is difficult

4 Linked lists Linked lists Characteristics: non-contiguous memory zones unlimited number of elements Advantages: unlimited number of elements growing a list is dynamically and easy Disadvantages: accessing an element involves iterating the list [O(n) in the worst case, when the desired element is the last in list]

5 Hash tables Big Picture Can we store and access data in one single step, no matter how many elements we have? The answer is YES, using hash tables. Data Hash Function Hashtable

6 Hash tables A hash table is basically an array coupled with a hash function Hash Function 27 The hash function takes a piece of data as input, called a key, and computes a result called a hash value. hash(16) = 0 hash(11) = 3 hash(27) = 3 hash(19) = 3 hash(22) = 6 hash(6) = 6 Key collision hash(key) = hash_value To avoid key collision, we need a strong hash function that produces unique hash values

7 Hash tables Accessing data in a hash table Hash Function 27 Supposing we need to access the element 27 in the hash table, we have to do the following operations: 1. compute hash(27) which is 3, in our case 2. we noticed that at that index there is a linked list, due to some key collisions 3. search in list the element 27 Conclusion: the best case, accessing an element in hash O(1) worst case, accessing an element in hash O(n) insertion an element in hash O(1) deletion an element in hash, between O(1) and O(n)

8 Dictionaries Dictionaries: the most flexible built-in data type in Python collection of unordered elements elements are stored and fetched based on keys instead of off-sets dictionaries have variable length heterogenous, can contain all kind of objects they are arbitrarily nested mutable-mapping (can be change in place, based on key, not on index)

9 Creating a dictionary Creating a dictionary music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} print(music) print(type(music)) {'year': 1973, 'album': 'Dark Side of the Moon', 'band': 'Pink Floyd } <class 'dict'> Note that the internal order in the dictionary is NOT necessarily the same as the defined one. Python performs some optimisations in order to support a fast key lookup. This is why some operations assuming a fixed left-to-right order (slicing, concatenation) do not work with dictionaries.

10 Creating a dictionary Python dictionaries do not support duplicate keys music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973, 'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} print(music) {'year': 1973, 'album': 'Dark Side of the Moon', 'band': 'Pink Floyd } <class 'dict'> Python dictionaries do not support duplicate keys, so if we try to add a key having the same name with an existing one, the operation will fall in an update operation, so the already existing key will receive the value from the new key with the same name.

11 Dictionaries Accessing an element from the dictionary music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} band = music['band'] print(band) Pink Floyd The same convention of square bracketing used for lists, but instead of indexes, we use keys Adding an element in the dictionary music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} music['components'] = ["Roger Waters", "David Gilmour", "Richard Wright", "Nick Mason"] print(music) {'year': 1973, 'components': ['Roger Waters', 'David Gilmour', 'Richard Wright', 'Nick Mason'], 'album': 'Dark Side of the Moon', 'band': 'Pink Floyd'}

12 Dictionaries Deleting an element from dictionary music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} del music['year'] print(music) {'album': 'Dark Side of the Moon', 'band': 'Pink Floyd'} Modifying elements in dictionary music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} music['album'] = 'The Wall' music['year'] = 1979 print(music) {'band': 'Pink Floyd', 'year': 1979, 'album': 'The Wall'}

13 Dictionaries Obtaining all the keys in a dictionary music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973, 'band' : 'Pink Floyd', 'album' : 'The Wall', 'year' : 1979} print(music.keys()) dict_keys(['year', 'album', 'band']) Obtaining all the values in a dictionary music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973, 'band' : 'Pink Floyd', 'album' : 'The Wall', 'year' : 1979} print(values()) dict_values(['the Wall', 'Pink Floyd', 1979])

14 Dictionaries Obtaining all the keys and values pairs in a dictionary music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973, 'band' : 'Pink Floyd', 'album' : 'The Wall', 'year' : 1979} print(music.items()) dict_items([('album', 'The Wall'), ('band', 'Pink Floyd'), ('year', 1979)]) Method Python 2.7 Python 3 dict.keys() list dict_key dict.values() list dict_value dict.items() list dict_items they are called views Lists in 2.7 are just snapshots of the dictionary content. If the dictionary changes while iterating over the list, the list content remains unchanged. The views change dynamically as the dictionary changes.

15 Dictionaries Iterating over a view music = {'band' : 'Pink Floyd', 'album' : 'The Wall', 'year' : 1979} keys = music.keys() for k in keys: print(k) album year band Iterating over the items view music = {'band' : 'Pink Floyd', 'album' : 'The Wall', 'year' : 1979} keys = music.items() for k,v in keys: print(k, v) year 1979 band Pink Floyd album The Wall Note the special way in which we can use the for iterator

16 More on accessing elements from a dictionary What happens if we try to access a key that does not exist? music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} element = music['hasdvd'] print(element) Traceback (most recent call last): File "/lect-examples.py", line 27, in <module> element = music['hasdvd'] KeyError: 'hasdvd' To avoid this situation, use get() method music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} element_default = music.get('hasdvd') element_custom = music.get('hasdvd', 'Yes, it has') print(element_default) print(element_custom) None Yes, it has The get() method returns None or a passedin default value if the requested key does not exist

17 Operations on dictionaries Merging two dictionaries music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} literature = {'author' : 'Erich Maria Remarque', 'book' : "The Black Obelisk"} music.update(literature) print(music) {'band': 'Pink Floyd', 'year': 1973, 'book': 'The Black Obelisk', 'author': 'Erich Maria Remarque', 'album': 'Dark Side of the Moon'} Delete an element of a dictionary using pop() music = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon', 'year' : 1973} deleted_val = music.pop('year') print(deleted_val) print(music) 1973 {'band': 'Pink Floyd', 'album': 'Dark Side of the Moon'}

18 Dictionaries Other ways to create dictionaries d1 = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon'} d2 = {} d2['band'] = 'Pink Floyd' d2['album'] = 'Dark Side of the Moon' d3 = dict(band='pink Floyd', album='dark Side of the Moon') d4 = dict([('band', 'Pink Floyd'), ('album', 'Dark Side of the Moon')]) print(d1) print(d2) print(d3) print(d4) {'album': 'Dark Side of the Moon', 'band': 'Pink Floyd'} {'album': 'Dark Side of the Moon', 'band': 'Pink Floyd'} {'album': 'Dark Side of the Moon', 'band': 'Pink Floyd'} {'album': 'Dark Side of the Moon', 'band': 'Pink Floyd'}

19 Simulate a switch statement in Python Python does not have a switch statement, but sometimes we need such functionality for the clarity of the code. Do not despair, we can simulate a switch using dictionaries. Suppose we have a program displaying a menu like below: 1 - Do something 2 - Do something else 3 - Do something different than the other options 4 - Exit

20 Switch simulation Input a number: 2 Hello from func2 def func1(): print("hello from func1") def func2(): print("hello from func2") def func3(): print("hello from func3") def func4(): print("exit") def error_handler(): print("inexistent option, retry") options = {1 : func1, 2 : func2, 3 : func3, 4 : func4} user_input = int(input("input a number: ")) func = options[user_input] func() Input a number: 7 Traceback (most recent call last): File "switch-sim.py", line 19, in <module> func = options[user_input] KeyError: 7 Option between 1-4 Option greater than 4

21 Switch simulation Input a number: 2 Hello from func2 def func1(): print("hello from func1") def func2(): print("hello from func2") def func3(): print("hello from func3") def func4(): print("exit") def error_handler(): print("inexistent option, retry") options = {1 : func1, 2 : func2, 3 : func3, 4 : func4} user_input = int(input("input a number: ")) func = options.get(user_input, error_handler) func() Input a number: 7 Inexistent option, retry Option between 1-4 Option greater than 4

22 List comprehensions List comprehension refers to a way to construct lists in a very natural, easy way, very close to the mathematical language S = [x ** 2 for x in range(0, 10)] print(s) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] T = ['alfa', 'beta', 'gamma'] U = [x.upper() for x in T] print(u) ['ALFA', 'BETA', 'GAMMA']

23 List Comprehensions Other examples l = ['x', 'y', 'z'] comprehended = ['---' + c + '---' for c in l] print(comprehended) ['---x---', '---y---', '---z---'] Create a new list using map() function def dash(c): return '---' + c + '---' l = list(map(dash, ['x', 'y', 'z'])) print(l) ['---x---', '---y---', '---z---']

24 Dictionary Comprehensions Creating a dictionary in one step, using zip() method d = dict(zip(['album', 'band', 'year'], ['Dark Side of the Moon', 'Pink Floyd', 1973])) print(d) {'band': 'Pink Floyd', 'album': 'Dark Side of the Moon', 'year': 1973} Create a new list using map() function d = {k:v for (k,v) in zip(['album', 'band', 'year'], ['Dark Side of the Moon', 'Pink Floyd', 1973])} print(d) {'band': 'Pink Floyd', 'year': 1973, 'album': 'Dark Side of the Moon'}

25 Files Another built-in type that provides a way to interact with the computer files inside Python programs. Files are distinct from all the other built-in types, they export only some methods for common processing operations like input from and output to an external file, associated with a file object in Python programs. Open file Process data Close file Time sequence for file processing

26 Opening a file 1. The file exists and we want to read from it f = open("/myfile.txt", "r") f = open("/myfile.txt") (default is r ) 2. The file exists or not and we want to write in it f = open("/myfile.txt", "w") 3. The file exists or not and we want to append data in it 4. The file content is binary f = open("/myfile.txt", "a") f = open("/myfile.txt", "ab") if the file exists and it is opened for writing, the old content is overwritten if the file exists and it is opened for appending, data is written at the end of the file b modifier added 5. The file is opened both for reading and writing f = open("/myfile.txt", "a+") + modifier added

27 Writing into and reading from a file Writing something into a file f = open("/myfile.txt", "w") f.write("hello,\n") f.write("is there anybody in there?") f.close() Reading from the file above, line by line f = open( /myfile.txt", "r") print(f.readline()) print(f.readline()) Hello, Is there anybody in there? Reading from the file above in a string f = open( /myfile.txt", "r") print(f.read()) Hello, Is there anybody in there? Not a good idea for big files

28 Some comments regarding closing a file Do we really need to close a file after using it? Python reclaims all the memory space of the objects that are no longer referenced. So, when a file object is reclaimed, Python closes the file object automatically. Therefore, using close() method is optional. However: Closing a file manually, using close() method is a very good habit, especially in the big systems. So, as a rule of thumb, use close() every time you deal with files. Method 1 f = None f = open("/myfile.txt", "w") try: f.write("written from try/finally block") finally: if f is not None: f.close() Method 2 with open("/myfile.txt", "w") as f: f.write("this is a text.") f is an alias Using with statement, the file is closed immediately after the block execution ends.

29 Reading a text file text-file.txt "In the moment when I truly understand my enemy, understand him well enough to defeat him, then in that very moment I also love him. I think it s impossible to really understand somebody, what they want, what they believe, and not love them the way they love themselves. And then, in that very moment when I love them... I destroy them." --Andrew Ender Wiggin (Orson Scott Card - Ender's Game) file_obj = open("text-file.txt", "r") print("first pass \n + file_obj.read()) print("second_pass \n + file_obj.read()) file_obj.close() print("third pass " + file_obj.read()) What about the output of this code?

30 Program Output first pass "In the moment when I truly understand my enemy, understand him well enough to defeat him, then in that very moment I also love him. I think it s impossible to really understand somebody, what they want, what they believe, and not love them the way they love themselves. And then, in that very moment when I love them... I destroy them." --Andrew Ender Wiggin (Orson Scott Card - Ender's Game) second_pass Traceback (most recent call last): File "/Users/adriancopie/Google Drive/Python/Projects/files-and-more/example-one.py", line 17, in <module> print("third pass " + file_obj.read()) ValueError: I/O operation on closed file. Nothing printed at the second pass Why? Error at the third pass

31 Modified program file_obj = open("text-file.txt", "r") print("first pass \n" + file_obj.read()) # reset the position pointer file_obj.seek(0) # only after resetting positional pointer it is possible # to print the file content again print("second_pass \n" + file_obj.read()) file_obj.close() What about the new output of this code?

32 Program Output first pass "In the moment when I truly understand my enemy, understand him well enough to defeat him, then in that very moment I also love him. I think it s impossible to really understand somebody, what they want, what they believe, and not love them the way they love themselves. And then, in that very moment when I love them... I destroy them." --Andrew Ender Wiggin (Orson Scott Card - Ender's Game) second_pass "In the moment when I truly understand my enemy, understand him well enough to defeat him, then in that very moment I also love him. I think it s impossible to really understand somebody, what they want, what they believe, and not love them the way they love themselves. And then, in that very moment when I love them... I destroy them." --Andrew Ender Wiggin (Orson Scott Card - Ender's Game) Second pass has now the desired output

33 Other methods on file objects read(size), seek(), tell() with open("text-file.txt") as f: txt = f.read(7) print(txt) print(f.tell()) f.seek(15) print(f.tell()) txt = f.read(5) print(txt) "In the 7 15 when read(size) - tell() - reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode) returns an integer giving the file object s current position in the file seek() - changes the file object s position

34 Reading and writing from and into files Reading a file using iterators f = open("/myfile.txt", "r") for line in f: print(line) Hello, Is there anybody in there? This is the recommended method for reading files Writing various Python objects to a file f = open("/myfile.txt", "w") day, month, year = 21, 10, 2017 lst = ['Monty', 'Python', 'and', 'the', 'Holy', 'Grail'] dct = {'band' : 'Pink Floyd', 'album' : 'Dark Side of the Moon'} f.write("today is {0}/{1}/{2}\n".format(day, month, year)) f.write(str(lst) + '\n') f.write(str(dct) + \n') f.close() File content: Today is 21/10/2017 ['Monty', 'Python', 'and', 'the', 'Holy', 'Grail'] {'album': 'Dark Side of the Moon', 'band': 'Pink Floyd'}

35 Copying two files Copying a text file with open('text-file.txt', 'r') as rf: with open('copy-text-file.txt', 'w') as wf: for line in rf: wf.write(line) Copying a binary file (version 1) with open('binary-file.png', 'rb') as rf: with open('copy-binary-file.png', 'wb') as wf: for line in rf: wf.write(line) Copying a binary file (version 2) with open('binary-file.png', 'rb') as rf: with open('copy-binary-file.png', 'wb') as wf: chunk_size = 4096 read_chunk = rf.read(chunk_size) while len(read_chunk) > 0: wf.write(read_chunk) read_chunk = rf.read(chunk_size)

36 More on list comprehension on files Suppose we need to create a list from the content of a file. The file s content looks as below: Version 1 Note that after reading a line from a file, a new line char is appended at the end of the line File content: Monty Python and the Holy Grail l = [] with open('myfile.txt') as f: for x in f: l.append(x) print(l) ['Monty\n', 'Python\n', 'and\n', 'the\n', 'Holy\n', 'Grail']

37 More on lists comprehensions on files Version 2 with list comprehension q = [] with open('myfile.txt') as f: q = [x.strip() for x in f] print(q) ['Monty', 'Python', 'and', 'the', 'Holy', 'Grail'] Version 3 with list comprehension r = [x.strip() for x in open( myfile.txt')] print(r) ['Monty', 'Python', 'and', 'the', 'Holy', 'Grail']

38 List comprehension on files, with filtering Suppose we need to create a list from the content of a file, but only with some of the lines, fulfilling a certain condition. Example: based on the content of the file in the previous example, build a list containing only the lines beginning with M and P r = [x.strip() for x in open('myfile.txt') if x[0] == 'M' or x[0] == 'P'] print(r) ['Monty', 'Python'

39 Comparison Python always inspects all the compound parts of the objects until it can come with a result in what concerns the equality of two objects. If the objects are compound, Python traverses all the structures, applying left to right comparisons until a first difference is encountered. list1 = [1, 2, 3] list2 = [1, 2, 3] print(list1 == list2) print(list1 is list2) True False The == operator tests value equivalence The is operator tests object identity list1 = [1, 2, 3] list2 = [1, 2, 3] print(id(list1)) print(id(list2))

40 Comparison Relative magnitude comparison: list1 = [1, ('x', 1)] list2 = [1, ('x', 2)] print(list1 < list2) print(list1 == list2) print(list1 > list2) True False False Numbers - compared by relative magnitude Strings - compared lexicographically Lists and tuples - comparing each element, from left to right and recursively for nested structures, until a mismatch is found Sets - they are equal if they contain the same items Dictionaries - they are equal if their sorted (key, value) lists are equal

41 True and False in Python Numbers are false if zero, true otherwise Other objects are false if empty, true otherwise Object Value python" True " False [1, 2] True [] False { a : 1} True {} False 1 True 0 False None False

42 The None object None is a special object in Python and it always considered to be false It serves as an empty placeholder (similar with NULL in C or null in Java) Use case: suppose you want to assign an element in a list at a specified offset. But you can perform this operation only if that offset exists, otherwise an index out of bound error occurs. Solution: preallocate the list with None objects. l = [None] * 5 l[2] = 2 print(l) [None, None, 2, None, None] Note: The list could be preallocated with any other value (like 0-es) but the good practice recommends the use of None. None does not mean undefined. It is a real object, occupying a real memory address. print(sys.getsizeof(l[0])) print(sys.getsizeof(l[1])) print(sys.getsizeof(l[2]))

43 Lists repetition Repeating a list is similar with adding it to itself multiple times. However, when it comes to deal with nested mutable sequences, the effect is different. l = [1, 2, 3] q = l * 4 r = [l] * 4 print(q) print(r) l[1] = 0 print(q) print(r) [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] [[1, 0, 3], [1, 0, 3], [1, 0, 3], [1, 0, 3]]

44 Changing a list Suppose we want to change a list by incrementing its every element by 1 l = [1, 2, 3, 4] for i in l: i += 1 print(l) [1, 2, 3, 4]? What happened?

45 Changing a list We can solve this issue by using indexes l = [1, 2, 3, 4] for i in range(len(l)): l[i] += 1 print(l) [2, 3, 4, 5] range() generates indexes, so we can use positional list update i = 0 l[0] = l[0] = 2

46 Conclusions Conclusions Dictionaries are the most flexible types in Python Lists and dictionary comprehensions offer a method for effectively creating lists and dictionaries Files are another type in Python, exposing methods for reading and writing Object are compared for equality based on specific rules

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1 Turn In Homework 2 Homework

More information

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12 List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE 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 information

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There 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

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries Assignment: Lab 12 Tuples and Dictionaries Due Date: During discussion, November 30 th through December 3 rd Value: 1% of final grade Part 1: Data Types

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

Lecture Agenda. Objects. But First... Immutable Types and Nesting. Immutable Types and Nesting

Lecture Agenda. Objects. But First... Immutable Types and Nesting. Immutable Types and Nesting COMP10001 Foundations of Computing Objects and Types: A Closer Look (Advanced Lecture) Semester 1, 2017 Tim Baldwin & Egemen Tanin Lecture Agenda This lecture: Making sense of strings, lists and functions

More information

Introducing Hashing. Chapter 21. Copyright 2012 by Pearson Education, Inc. All rights reserved

Introducing Hashing. Chapter 21. Copyright 2012 by Pearson Education, Inc. All rights reserved Introducing Hashing Chapter 21 Contents What Is Hashing? Hash Functions Computing Hash Codes Compressing a Hash Code into an Index for the Hash Table A demo of hashing (after) ARRAY insert hash index =

More information

MEIN 50010: Python Data Structures

MEIN 50010: Python Data Structures : Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing

More information

Working with Lists 4

Working with Lists 4 CS 61A Lecture 10 Announcements Lists ['Demo'] Working with Lists 4 Working with Lists >>> digits = [1, 8, 2, 8] 4 Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] 4

More information

ECE 122. Engineering Problem Solving Using Java

ECE 122. Engineering Problem Solving Using Java ECE 122 Engineering Problem Solving Using Java Lecture 27 Linear and Binary Search Overview Problem: How can I efficiently locate data within a data structure Searching for data is a fundamental function

More information

Python Basics. 1 of 7 9/5/2018, 8:51 AM. txt1 = "ada lovelace, english mathematician and writer" print(txt1)

Python Basics. 1 of 7 9/5/2018, 8:51 AM. txt1 = ada lovelace, english mathematician and writer print(txt1) 1 of 7 9/5/2018, 8:51 AM Python Basics In [1]: txt1 = "ada lovelace, english mathematician and writer" print(txt1) ada lovelace, english mathematician and writer Here txt1 is a variable and "ada lovelace,

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

Lecture #21: Search and Sets. Last modified: Wed Mar 9 15:44: CS61A: Lecture #21 1

Lecture #21: Search and Sets. Last modified: Wed Mar 9 15:44: CS61A: Lecture #21 1 Lecture #21: Search and Sets Last modified: Wed Mar 9 15:44:55 2016 CS61A: Lecture #21 1 Announcements My office hours this Thursday (only) are 3 4PM. Homework 5 to be released later today. Many problems

More information

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 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 information

Notes on the Exam. Question 1. Today. Comp 104:Operating Systems Concepts 11/05/2015. Revision Lectures (separate questions and answers)

Notes on the Exam. Question 1. Today. Comp 104:Operating Systems Concepts 11/05/2015. Revision Lectures (separate questions and answers) Comp 104:Operating Systems Concepts Revision Lectures (separate questions and answers) Today Here are a sample of questions that could appear in the exam Please LET ME KNOW if there are particular subjects

More information

Hacettepe University Computer Engineering Department. Programming in. BBM103 Introduction to Programming Lab 1 Week 7. Fall 2018

Hacettepe University Computer Engineering Department. Programming in. BBM103 Introduction to Programming Lab 1 Week 7. Fall 2018 Hacettepe University Computer Engineering Department Programming in BBM103 Introduction to Programming Lab 1 Week 7 Fall 2018 Collections A Collection Groups Similar Things List: ordered Set: unordered,

More information

CSE wi: Practice Midterm

CSE wi: Practice Midterm CSE 373 18wi: Practice Midterm Name: UW email address: Instructions Do not start the exam until told to do so. You have 80 minutes to complete the exam. This exam is closed book and closed notes. You may

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

More information

Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers)

Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers) Comp 204: Computer Systems and Their Implementation Lecture 25a: Revision Lectures (separate questions and answers) 1 Today Here are a sample of questions that could appear in the exam Please LET ME KNOW

More information

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries Chapter 1 Data types In this chapter you will: learn about data types learn about tuples, lists and dictionaries make a magic card trick app. Data types In Python Basics you were introduced to strings

More information

File I/O, Benford s Law, and sets

File I/O, Benford s Law, and sets File I/O, Benford s Law, and sets Matt Valeriote 11 February 2019 Benford s law Benford s law describes the (surprising) distribution of first digits of many different sets of numbers. Read it about it

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression 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 information

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for

More information

COMP10001 Foundations of Computing Functions

COMP10001 Foundations of Computing Functions COMP10001 Foundations of Computing Functions Semester 1, 2017 Tim Baldwin & Egemen Tanin version: 1093, date: March 21, 2017 2017 The University of Melbourne Announcements Project 1 now out Live Tutor

More information

Python for Everybody. Exploring Data Using Python 3. Charles R. Severance

Python for Everybody. Exploring Data Using Python 3. Charles R. Severance Python for Everybody Exploring Data Using Python 3 Charles R. Severance 8.14. DEBUGGING 103 In this example you could also use the built-in function sorted, which returns a new, sorted list and leaves

More information

Topic 7: Lists, Dictionaries and Strings

Topic 7: Lists, Dictionaries and Strings Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

A linked list grows as data is added to it. In a linked list each item is packaged into a node.

A linked list grows as data is added to it. In a linked list each item is packaged into a node. Lesson 4 Data Structures What is a data structure? A data structure is a particular way of organizing data in a computer. A data structure that we have already encountered is the array. An array stores

More information

DSC 201: Data Analysis & Visualization

DSC 201: Data Analysis & Visualization DSC 201: Data Analysis & Visualization Classes Dr. David Koop Tuple, List, Dictionary, or Set? [1,2,"abc"] 2 Tuple, List, Dictionary, or Set? {"a", 1, 2} 3 Tuple, List, Dictionary, or Set? {} 4 Tuple,

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Randomized Algorithms, Hash Functions

Randomized Algorithms, Hash Functions Randomized Algorithms, Hash Functions Lecture A Tiefenbruck MWF 9-9:50am Center 212 Lecture B Jones MWF 2-2:50pm Center 214 Lecture C Tiefenbruck MWF 11-11:50am Center 212 http://cseweb.ucsd.edu/classes/wi16/cse21-abc/

More information

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I ECE 364 Software Engineering Tools Laboratory Lecture 4 Python: Collections I 1 Lecture Summary Lists Tuples Sets Dictionaries Printing, More I/O Bitwise Operations 2 Lists list is a built-in Python data

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Advanced Database Systems

Advanced Database Systems Lecture IV Query Processing Kyumars Sheykh Esmaili Basic Steps in Query Processing 2 Query Optimization Many equivalent execution plans Choosing the best one Based on Heuristics, Cost Will be discussed

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Data Types Joseph Cappadona University of Pennsylvania September 03, 2015 Joseph Cappadona (University of Pennsylvania) CIS 192 September 03, 2015 1 / 32 Outline 1 Data Types

More information

Question 1. Notes on the Exam. Today. Comp 104: Operating Systems Concepts 11/05/2015. Revision Lectures

Question 1. Notes on the Exam. Today. Comp 104: Operating Systems Concepts 11/05/2015. Revision Lectures Comp 104: Operating Systems Concepts Revision Lectures Today Here are a sample of questions that could appear in the exam Please LET ME KNOW if there are particular subjects you want to know about??? 1

More information

Python Review IPRE

Python Review IPRE Python Review Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information

Lecture 21. Chapter 12 More Python Containers

Lecture 21. Chapter 12 More Python Containers Lecture 21 Chapter 12 More Python Containers 12.1 Two Familiar Containers: list and tuple 12.2 Dictionaries 12.3 Containers of containers 12.4 Set and Frozenset 12.5 Arrays Chapter 12 More Python Containers

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

EXAMINATION REGULATIONS and REFERENCE MATERIAL for ENCM 339 Fall 2017 Section 01 Final Examination

EXAMINATION REGULATIONS and REFERENCE MATERIAL for ENCM 339 Fall 2017 Section 01 Final Examination EXAMINATION REGULATIONS and REFERENCE MATERIAL for ENCM 339 Fall 2017 Section 01 Final Examination The following regulations are taken from the front cover of a University of Calgary examination answer

More information

Directory of C:\Users\Ami\Documents\Python Scripts

Directory of C:\Users\Ami\Documents\Python Scripts Chapter 8: Files and I/O Up to this point, all input and output has taken place using the keyboard and the command console. Specifically, the function input() has been used to collect user data, and the

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Hash Tables. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Data Dictionary Revisited

Hash Tables. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Data Dictionary Revisited Unit 9, Part 4 Hash Tables Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Data Dictionary Revisited We've considered several data structures that allow us to store and search for data

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech

More information

Chapter 6. Files and Exceptions I

Chapter 6. Files and Exceptions I Chapter 6 Files and Exceptions I What is a file? a file is a collection of data that is stored on secondary storage like a disk or a thumb drive accessing a file means establishing a connection between

More information

introduction to records in touchdevelop

introduction to records in touchdevelop introduction to records in touchdevelop To help you keep your data organized, we are introducing records in release 2.8. A record stores a collection of named values called fields, e.g., a Person record

More information

Physics 514 Basic Python Intro

Physics 514 Basic Python Intro Physics 514 Basic Python Intro Emanuel Gull September 8, 2014 1 Python Introduction Download and install python. On Linux this will be done with apt-get, evince, portage, yast, or any other package manager.

More information

Python: Short Overview and Recap

Python: Short Overview and Recap Python: Short Overview and Recap Benjamin Roth CIS LMU Benjamin Roth (CIS LMU) Python: Short Overview and Recap 1 / 39 Data Types Object type Example creation Numbers (int, float) 123, 3.14 Strings this

More information

Python Evaluation Rules

Python Evaluation Rules Python Evaluation Rules UW CSE 160 https://courses.cs.washington.edu/courses/cse160/15sp/ Michael Ernst and Isaac Reynolds mernst@cs.washington.edu April 1, 2015 Contents 1 Introduction 2 1.1 The Structure

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Python. Karin Lagesen.

Python. Karin Lagesen. Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set

More information

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values. Chapter 8 Dictionaries Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values. Creating a Dictionary To create a dictionary, you need

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

More information

Python Review IPRE

Python Review IPRE Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information

COMP171. Hashing.

COMP171. Hashing. COMP171 Hashing Hashing 2 Hashing Again, a (dynamic) set of elements in which we do search, insert, and delete Linear ones: lists, stacks, queues, Nonlinear ones: trees, graphs (relations between elements

More information

Randomized Algorithms: Element Distinctness

Randomized Algorithms: Element Distinctness Randomized Algorithms: Element Distinctness CSE21 Winter 2017, Day 24 (B00), Day 16-17 (A00) March 13, 2017 http://vlsicad.ucsd.edu/courses/cse21-w17 Element Distinctness: WHAT Given list of positive integers

More information

Script language: Python Data structures

Script language: Python Data structures Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015 Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision

More information

DATA STRUCTURE AND ALGORITHM USING PYTHON

DATA STRUCTURE AND ALGORITHM USING PYTHON DATA STRUCTURE AND ALGORITHM USING PYTHON Advanced Data Structure and File Manipulation Peter Lo Linear Structure Queue, Stack, Linked List and Tree 2 Queue A queue is a line of people or things waiting

More information

(Refer Slide Time: 01.26)

(Refer Slide Time: 01.26) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture # 22 Why Sorting? Today we are going to be looking at sorting.

More information

Lecture 1. 1 Notation

Lecture 1. 1 Notation Lecture 1 (The material on mathematical logic is covered in the textbook starting with Chapter 5; however, for the first few lectures, I will be providing some required background topics and will not be

More information

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program: Question 1. Part (a) [4 marks] Consider this program: [13 marks] def square(x): (number) -> number Write what this program prints, one line per box. There are more boxes than you need; leave unused ones

More information

Reading and writing files

Reading and writing files C H A P T E R 1 3 Reading and writing files 131 Opening files and file objects 131 132 Closing files 132 133 Opening files in write or other modes 132 134 Functions to read and write text or binary data

More information

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( ) Review CSE 143 Java Hashing Want to implement Sets of objects Want fast contains( ), add( ) One strategy: a sorted list OK contains( ): use binary search Slow add( ): have to maintain list in sorted order

More information

Overview.

Overview. Overview day one 0. getting set up 1. text output and manipulation day two 2. reading and writing files 3. lists and loops day three 4. writing functions 5. conditional statements day four today day six

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

More information

Data Structures - CSCI 102. CS102 Hash Tables. Prof. Tejada. Copyright Sheila Tejada

Data Structures - CSCI 102. CS102 Hash Tables. Prof. Tejada. Copyright Sheila Tejada CS102 Hash Tables Prof. Tejada 1 Vectors, Linked Lists, Stack, Queues, Deques Can t provide fast insertion/removal and fast lookup at the same time The Limitations of Data Structure Binary Search Trees,

More information

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013 CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Python Mini Lessons last update: May 29, 2018

Python Mini Lessons last update: May 29, 2018 Python Mini Lessons last update: May 29, 2018 From http://www.onlineprogramminglessons.com These Python mini lessons will teach you all the Python Programming statements you need to know, so you can write

More information

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Python Lists: Example 1: >>> items=[apple, orange,100,25.5] >>> items[0] 'apple' >>> 3*items[:2] Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

Fundamentals of Programming (Python) File Processing. Ali Taheri Sharif University of Technology Spring 2018

Fundamentals of Programming (Python) File Processing. Ali Taheri Sharif University of Technology Spring 2018 Fundamentals of Programming (Python) File Processing Ali Taheri Sharif University of Technology Outline 1. Sources of Input 2. Files 3. Opening a File 4. Opening Modes 5. Closing a File 6. Writing to a

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision

More information

Python Programming: Lecture 2 Data Types

Python Programming: Lecture 2 Data Types Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)

More information

Algorithms and Programming

Algorithms and Programming Algorithms and Programming Lecture 2 Procedural Programming Camelia Chira Last time Programming process What is programming? Basic elements of Python Python programs Data types: string, number Variables

More information

CS1 Lecture 11 Feb. 9, 2018

CS1 Lecture 11 Feb. 9, 2018 CS1 Lecture 11 Feb. 9, 2018 HW3 due Monday morning, 9:00am for #1 I don t care if you use 1, 2, or 3 loops. Most important is clear correct code for #3, make sure all legal situations are handled. Think

More information

CPSC 211, Sections : Data Structures and Implementations, Honors Final Exam May 4, 2001

CPSC 211, Sections : Data Structures and Implementations, Honors Final Exam May 4, 2001 CPSC 211, Sections 201 203: Data Structures and Implementations, Honors Final Exam May 4, 2001 Name: Section: Instructions: 1. This is a closed book exam. Do not use any notes or books. Do not confer with

More information

Sets and Dictionaries. Modules and File I/O

Sets and Dictionaries. Modules and File I/O Sets and Dictionaries Modules and File I/O get excited! CS 112 @ GMU Sets some allowed set values: numbers, strings, and tuples some disallowed set values: lists, dictionaries, other sets not allowed in

More information

HASH TABLES. Hash Tables Page 1

HASH TABLES. Hash Tables Page 1 HASH TABLES TABLE OF CONTENTS 1. Introduction to Hashing 2. Java Implementation of Linear Probing 3. Maurer s Quadratic Probing 4. Double Hashing 5. Separate Chaining 6. Hash Functions 7. Alphanumeric

More information

Fundamentals of Programming. Week 5 - Lecture 2: Efficiency continued. Merge sort. Sets. Dictionaries.

Fundamentals of Programming. Week 5 - Lecture 2: Efficiency continued. Merge sort. Sets. Dictionaries. 15-112 Fundamentals of Programming Week 5 - Lecture 2: Efficiency continued. Merge sort. Sets. Dictionaries. February 11, 2016 Measuring running time How to properly measure running time > Input length/size

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

CSE100. Advanced Data Structures. Lecture 21. (Based on Paul Kube course materials)

CSE100. Advanced Data Structures. Lecture 21. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 21 (Based on Paul Kube course materials) CSE 100 Collision resolution strategies: linear probing, double hashing, random hashing, separate chaining Hash table cost

More information

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013 CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation

More information

(Refer Slide Time: 01:12)

(Refer Slide Time: 01:12) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #22 PERL Part II We continue with our discussion on the Perl

More information

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS 1. Define global declaration? The variables that are used in more

More information