Chapter 5 Hashes and databases. File contains more than numbers NameScore Johnny8.65 Juan9.12 Joseph8.45 Stacey7.81 Aideen8.05 Zack7.21 Aaron8.31.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to Arrays Chapter What is an array? An array is an ordered collection that stores many elements of the same type within one variable.
Two-Dimensional Arrays Chapter What is a two-dimensional array? A two-dimensional array has “rows” and “columns,” and can be thought of as a series.
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Arrays.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Programming with Collections Collections in Java Using Arrays Week 9.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 8 Arrays.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
7ex.1 Hashes. 7ex.2 Let's say we want to create a phone book... Enter a name that will be added to the phone book: Eyal Enter a phone number:
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
8ex.1 References and complex data structures. 8ex.2 An associative array (or simply – a hash) is an unordered set of key=>value pairs. Each key is associated.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui SWEN 432 Advanced Database Design and Implementation MongoDB Read Lecturer.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
Lists in Python.
Program structure Four different storage-class specifications: –Automatic (auto): local to a function, normally declared variables are automatic. Does.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
Session 7 JavaScript/Jscript: Arrays Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Chapter 7 One-Dimensional Arrays 7.1 Arrays in C One of the more useful features of C is the ability to create arrays for storing a collection of related.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Freemarker ● Introduction ● Core features ● Java part example ● Template example ● Expressions ● Builtins ● Assigning value ● Conditions ● Loops ● Macros.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
HTML, PHP, and MySQL: Putting It All Together. Making a Form Input tags Types: “text” “radio” “checkboxes” “submit”
Built-in Data Structures in Python An Introduction.
PHP Constructs Advance Database Management Systems Lab no.3.
And other languages….  Array literals/initialization a = [1,2,3] a2 = [-10..0, 0..10] a3 = [[1,2],[3,4]] a4 = [w*h, w, h] a5 = [] empty = Array.new zeros.
Introduction to C++ Programming Language Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University,
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Computer Programming TCP1224 Chapter 11 Arrays. Objectives Using Arrays Declare and initialize a one-dimensional array Manipulate a one-dimensional array.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Perl Chapter 5 Hashes. Outside of world of Perl, know as associative arrays Also called hash tables Perl one of few languages that has hashes built-in.
CSCI 6962: Server-side Design and Programming JSF DataTables and Shopping Carts.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
More Perl Data Types Scalar: it may be a number, a character string, or a reference to another data type. -the sigil $ is used to denote a scalar(or reference)
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Visual C++ Programming: Concepts and Projects Chapter 8A: Binary Search (Concepts)
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 11P. 1Winter Quarter Arrays Lecture 11.
Dynamic Programming & Memoization. When to use? Problem has a recursive formulation Solutions are “ordered” –Earlier vs. later recursions.
Chapter 8: Part 3 Collections and Two-dimensional arrays.
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
Arrays and variables 1.Representing tables as arrays in MATLAB 2.Concept of array dimension 3.Correspondence of array dimension to rows and columns 4.Picking.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 5 Murach's JavaScript and jQuery, C1© 2012, Mike Murach & Associates, Inc.Slide 1.
Today… Files from the Web! Dictionaries. Lists of lists. Winter 2016CISC101 - Prof. McLeod1.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Python Fundamentals: Complex Data Structures Eric Shook Department of Geography Kent State University.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 8.
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Python I/O.
File Handling Programming Guides.
Data Structures – 1D Lists
Lists in Python Creating lists.
functions: argument, return value
Introduction to Computer Science
Presentation transcript:

Chapter 5 Hashes and databases

File contains more than numbers NameScore Johnny8.65 Juan9.12 Joseph8.45 Stacey7.81 Aideen8.05 Zack7.21 Aaron8.31

Who won the surfing contest? scores=[ ] result_f=open(“results.txt”) for line in result_f: (name, score)=line.split() scores.append(float(score))result_f.close()scores.sort(reverse=True) print(“The top scores are: “) ??? print(scores[0])print(scores[1])print(scores[2])

Rewrite the program scores=[ ] names=[ ] result_f=open(“results.txt”) for line in result_f: (name, score)=line.split() scores.append(float(score))names.append(name)result_f.close()scores.sort(reverse=True)names.sort(reverse=True) print(“The top scores are: “) ??? print(names[0]+’ with ‘ +str(scores[0])) print(names[1]+’ with ‘ +str(scores[1])) print(names[2]+’ with ‘ +str(scores[2]))

Associate name and score NameScore Johnny8.65 Juan9.12 Joseph8.45 Stacey7.81 Aideen8.05 Zack7.21 Aaron8.31 Need a different data structure!!!

Hash A variable that has exactly two columns and (potentially) many rows of data key – value A data structure that associates a name with a value Other names in different programming languages: mappingdictionary association array key-value list

Using a hash # Start with an empty hash: scores={} # Add data # Put the key inside the square brackets # put the value to the right of the assignment op scores[8.45]=‘Joseph’ # New row of data is added to the hash # No explicit “append()” method like arrays

Using a hash Can use a for loop to iterate over each of the rows in a hash: for key in scores.keys(): print(scores[key]+’ had a score of ‘+str(key)) keys() – built-in method that returns an array of the keys of the hash. values() – built-in method that returns an array of the values of the hash.

Using a hash Use the square brackets to refer to a value associated with a key: print(scores[9.12]) items() – Another hash method that returns key-value pair. (one can use it with the for loop) for score,surfer in scores.items(): print(surfer + ‘ had a score of ‘ + str(score))

The new program scores={}result_f=open(‘results.txt’) for line in result_f: (name,score)=line.split() ??? scores[score]=nameresult_f.close() print(“The top scores were”) for each_score in scores.keys(): print(‘Surfer ‘+scores[each_score]+’ scored ‘+each_score)

Sorting data in a has No sort() method BUT There is a function called sorted() sorted() – bulit-in function that has the ability to sort any data structure for each_score in sorted(scores.keys(),reverse=True): print(‘Surfer ‘+scores[each_score]+’ scored ‘+each_score)

The new program scores={}result_f=open(‘results.txt’) for line in result_f: (name,score)=line.split() Hurray!!! scores[score]=nameresult_f.close() print(“The top scores were”) for each_score in sorted(scores.keys(), reverse=True): print(‘Surfer ‘+scores[each_score]+’ scored ‘+each_score)

When data gets complex Data file (competition id, name, country, average score, board type, age): 101;Johnny 'wave-boy' Jones;USA;8.32;Fish;21 102;Juan Martino;Spain;9.01;Gun;36 103;Joseph 'smitty' Smyth;USA;8.85;Cruizer;18 104;Stacey O'Neill;Ireland;8.91;Malibu;22 105;Aideen 'board babe' Wu;Japan;8.65;Fish;24 106;Zack 'bonnie-lad' MacFadden;Scotland;7.82;Thruster;26 107;Aaron Valentino;Italy;8.98;Gun;19 Problem: Find and display a surfer’s data based on competition ID

Printing surfer’s data line=“101;Johnny ‘wave-boy’ Jones;USA;8.32;Fish;21” Display: ID:101 Name:Johnny ‘wave-boy’ Jones Country:USA Average:8.32 Board type:Fish Age:21

Printing surfer’s data line=“101;Johnny ‘wave-boy’ Jones;USA;8.32;Fish;21” s={}#create an empty hash (s[‘id’],s[‘name’],s[‘country’],s[‘average’].s[‘board’],s[‘age’])=line.split(“,”) print(“ID:“+s[‘id’]) print(“Name:“+s[‘name’]) print(“Country:“+s[‘country’]) print(“Average:“+s[‘average’]) print(“Board type:“+s[‘board’]) print(“Age:“+s[‘age’])

Processing ALL lines in data file Problem: Write a function that takes the surfer ID as a parameter, searches the file one line at a time for a matching ID, and then returns the found data to the caller. How to return the data ??? 1. as a string 2. as a hash Which one should we use???

Processing ALL lines in data file Problem: Write a function that takes the surfer ID as a parameter, searches the file one line at a time for a matching ID, and then returns the found data to the caller. How to return the data ??? 1. as a string 2. as a hash Which one should we use??? Answer: A hash – It allows the calling code to simply pick out the information it needs without further processing.

find_details function def find_details(id2find): surfers_f=open(“surfing_data.csv”) for each_line in surfers_f: s={}(s[‘id’],s[‘name’],s[‘country’],s[‘average’].s[‘board’],s[‘age’])=line.split(“,”) if id2find == int (s[‘id’]): surfers_f.close()return(s)surfers_f.close() return ({})

Testing the function lookup_id=int(input(“Enter the id of the surfer: “)) surfer=find_details(lookup_id) if surfer: print(“ID:“+s[‘id’]) print(“Name:“+s[‘name’]) print(“Country:“+s[‘country’]) print(“Average:“+s[‘average’]) print(“Board type:“+s[‘board’]) print(“Age:“+s[‘age’])

Using data from a database import sqlite3 def find_details(id2find): db = sqlite3.connect("surfersDB.sdb") db.row_factory = sqlite3.Row cursor = db.cursor() cursor.execute("select * from surfers") rows = cursor.fetchall() for row in rows: if row['id'] == id2find: s = {} s['id'] = str(row['id']) s['name'] = row['name'] s[ 'country'] = row['country'] s['average'] = str(row['average']) s['board'] = row['board'] s['age'] = str(row['age']) cursor.close() return(s) cursor.close() return({})