Introduction to Computing Using Python More Built-in Container Classes  Container Class dict  Encoding of String Characters  Randomness and Random Sampling.

Slides:



Advertisements
Similar presentations
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Advertisements

Dictionaries: Keeping track of pairs
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information.
1 Lab Session-IV CSIT-120 Spring 2001 Lab 3 Revision and Exercises Rev: Precedence Rules Lab Exercise 4-A Machine Language Programming The “Micro” Machine.
מבנה מחשב תרגול 2 ייצוג תווים בחומרה. A programmer that doesn’t care about characters encoding in not much better than a medical doctor who doesn’t believe.
1 Lab Session-III CSIT-120 Spring 2001 Revising Previous session Data input and output While loop Exercise Limits and Bounds GOTO SLIDE 13 Lab session.
CIS 234: Character Codes Dr. Ralph D. Westfall April, 2011.
CHARACTERS Data Representation. Using binary to represent characters Computers can only process binary numbers (1’s and 0’s) so a system was developed.
Introduction to Computing Using Python Dictionary container class + modules  Container Class dict  Modules, revisited.
Connecting with Computer Science 2 Objectives Learn why numbering systems are important to understand Refresh your knowledge of powers of numbers Learn.
Introduction to Computing Using Python Chapter 6  Encoding of String Characters  Randomness and Random Sampling.
Introduction to Computing Using Python More Built-in Container Classes  Container Class dict  Container Class set  Container Class tuple  Encoding.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
Announcements Project 2 Available Tomorrow (we will send mail) Will be due 11:59PM October 9 th (Sunday) Week 6 ( I will be traveling this week) Review.
The Data Element. 2 Data type: A description of the set of values and the basic set of operations that can be applied to values of the type. Strong typing:
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Computer Math CPS120: Data Representation. Representing Data The computer knows the type of data stored in a particular location from the context in which.
Computer Science 111 Fundamentals of Programming I Number Systems.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
STRINGS CMSC 201 – Lab 3. Overview Objectives for today's lab:  Obtain experience using strings in Python, including looping over characters in strings.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 6 Value-Returning.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CPS120: Introduction to Computer Science
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Computing Science 1P Large Group Tutorial: Lab Exam & Class Test Simon Gay Department of Computing Science University of Glasgow 2006/07.
A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University ©2011 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 3 Mathematical Functions, Strings, and Objects.
Data Representation. What is data? Data is information that has been translated into a form that is more convenient to process As information take different.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
14. DICTIONARIES AND SETS Rocky K. C. Chang 17 November 2014 (Based on from Charles Dierbach, Introduction to Computer Science Using Python and Punch and.
Introduction to Computing Using Python Dictionaries: Keeping track of pairs  Class dict  Class tuple.
Characters CS240.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
Data Abstraction UW CSE 160 Spring What is a program? – A sequence of instructions to achieve some particular purpose What is a library? – A collection.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Introduction to Python Developed by Dutch programmer Guido van Rossum Named after Monty Python Open source development project Simple, readable language.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
Binary Representation in Text
Binary Representation in Text
Chapter 8 & 11: Representing Information Digitally
CMSC201 Computer Science I for Majors Lecture 22 – Binary (and More)
Representing Characters
Topics Introduction to File Input and Output
Ch2: Data Representation
String Encodings and Penny Math
Introduction to Java, and DrJava part 1
Digital Encodings.
Introduction to Java, and DrJava
CS190/295 Programming in Python for Life Sciences: Lecture 3
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
functions: argument, return value
Dictionaries: Keeping track of pairs
15-110: Principles of Computing
String Encodings and Penny Math
Chapter 17 JavaScript Arrays
Introduction to Java, and DrJava part 1
Topics Introduction to File Input and Output
CS 100: Roadmap to Computing
Presentation transcript:

Introduction to Computing Using Python More Built-in Container Classes  Container Class dict  Encoding of String Characters  Randomness and Random Sampling

>>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee[' '] ['Yu', 'Tsun'] >>> employee[' '] ['Anna', 'Karenina'] >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee[' '] ['Yu', 'Tsun'] >>> employee[' '] ['Anna', 'Karenina'] Introduction to Computing Using Python User-defined indexes and dictionaries >>> employee[ ] ['Yu', 'Tsun'] >>> employee[ ] ['Anna', 'Karenina'] >>> employee[ ] ['Hans', 'Castorp'] >>> employee[ ] ['Yu', 'Tsun'] >>> employee[ ] ['Anna', 'Karenina'] >>> employee[ ] ['Hans', 'Castorp'] Goal: a container of employee records indexed by employee SS# Problems: the range of SS#s is huge SS#s are not really integers Solution: the dictionary class dict A dictionary contains (key, value) pairs keyvalue ' '['Anna', 'Karenina'] ' '['Yu', 'Tsun'] ' '['Hans', 'Castorp'] A key can be used as an index to access the corresponding value

>>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> employee[' '] = 'Holden Cafield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Cafield'} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> employee[' '] = 'Holden Cafield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Cafield'} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> employee[' '] = 'Holden Cafield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Cafield'} >>> employee[' '] = 'Holden Caulfield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Caulfield’} >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> employee[' '] = 'Holden Cafield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Cafield'} >>> employee[' '] = 'Holden Caulfield' >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': 'Holden Caulfield’} >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> >>> employee = { ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun'], ' ': ['Hans', 'Castorp']} >>> employee {' ': ['Hans', 'Castorp'], ' ': ['Anna', 'Karenina'], ' ': ['Yu', 'Tsun']} >>> >>> employee = {[1,2]:1, [2,3]:3} Traceback (most recent call last): File " ", line 1, in employee = {[1,2]:1, [2,3]:3} TypeError: unhashable type: 'list' >>> employee = {[1,2]:1, [2,3]:3} Traceback (most recent call last): File " ", line 1, in employee = {[1,2]:1, [2,3]:3} TypeError: unhashable type: 'list' Introduction to Computing Using Python Properties of dictionaries Dictionaries are not ordered Dictionaries are mutable new (key,value) pairs can be added Dictionaries are mutable new (key,value) pairs can be added the value corresponding to a key can be modified The empty dictionary is {} Dictionary keys must be immutable

Introduction to Computing Using Python Dictionary operators >>> days = {'Mo':1, 'Tu':2, 'W':3} >>> days['Mo'] 1 >>> days['Th'] = 5 >>> days {'Mo': 1, 'Tu': 2, 'Th': 5, 'W': 3} >>> days['Th'] = 4 >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> 'Fr' in days False >>> len(days) 4 >>> days = {'Mo':1, 'Tu':2, 'W':3} >>> days['Mo'] 1 >>> days['Th'] = 5 >>> days {'Mo': 1, 'Tu': 2, 'Th': 5, 'W': 3} >>> days['Th'] = 4 >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> 'Fr' in days False >>> len(days) 4 Class dict supports some of the same operators as class list Class dict does not support all the operators that class list supports + and * for example

>>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> for val in vals: print(val, end=' ') >>> >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> for val in vals: print(val, end=' ') >>> Introduction to Computing Using Python Dictionary methods >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> OperationExplanation d.items() Returns a view of the (key, value) pairs in d d.keys() Returns a view of the keys of d d.pop(key) Removes the (key, value) pair with key key from d and returns the value d.update(d2) Adds the (key, value) pairs of dictionary d2 to d d.values() Returns a view of the values of d The containers returned by d.items(), d.keys(), and d.values() (called views) can be iterated over

Introduction to Computing Using Python Dictionary vs. multi-way if statement Uses of a dictionary: container with custom indexes def complete(abbreviation): 'returns day of the week corresponding to abbreviation' if abbreviation == 'Mo': return 'Monday' elif abbreviation == 'Tu': return 'Tuesday' elif else: # abbreviation must be Su return 'Sunday' def complete(abbreviation): 'returns day of the week corresponding to abbreviation' if abbreviation == 'Mo': return 'Monday' elif abbreviation == 'Tu': return 'Tuesday' elif else: # abbreviation must be Su return 'Sunday' def complete(abbreviation): 'returns day of the week corresponding to abbreviation' days = {'Mo': 'Monday', 'Tu':'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Fr': 'Friday', 'Sa': 'Saturday', 'Su':'Sunday'} return days[abbreviation] def complete(abbreviation): 'returns day of the week corresponding to abbreviation' days = {'Mo': 'Monday', 'Tu':'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Fr': 'Friday', 'Sa': 'Saturday', 'Su':'Sunday'} return days[abbreviation] Uses of a dictionary: container with custom indexes alternative to the multi-way if statement

Introduction to Computing Using Python Dictionary as a container of counters >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] >>> frequency(grades) {96: 1, 90: 1, 100: 3, 85: 1, 95: 3} >>> >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] >>> frequency(grades) {96: 1, 90: 1, 100: 3, 85: 1, 95: 3} >>> Problem: computing the number of occurrences of items in a list Solution: Iterate through the list and, for each grade, increment the counter corresponding to the grade. Problems: impossible to create counters before seeing what’s in the list how to store grade counters so a counter is accessible using the corresponding grade Solution: a dictionary mapping a grade (the key) to its counter (the value) Uses of a dictionary: container with custom indexes alternative to the multi-way if statement container of counters

def frequency(itemList): 'returns frequency of items in itemList' counters = {} def frequency(itemList): 'returns frequency of items in itemList' counters = {} def frequency(itemList): 'returns frequency of items in itemList' counters = {} for item in itemList: if item in counters: # increment item counter counters[item] += 1 else: # create item counter counters[item] = 1 return counters def frequency(itemList): 'returns frequency of items in itemList' counters = {} for item in itemList: if item in counters: # increment item counter counters[item] += 1 else: # create item counter counters[item] = 1 return counters >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ Introduction to Computing Using Python Dictionary as a container of counters Problem: computing the number of occurrences of items in a list 95 1 counters

Introduction to Computing Using Python Exercise def numChars(filename): 'returns the number of characters in file filename' infile = open(filename, 'r') content = infile.read() infile.close() return len(content) def numChars(filename): 'returns the number of characters in file filename' infile = open(filename, 'r') content = infile.read() infile.close() return len(content) Implement function wordcount() that takes as input a text—as a string— and prints the frequency of each word in the text; assume there is no punctuation in the text. def wordCount(text): 'prints frequency of each word in text' wordList = text.split() # split text into list of words counters ={} # dictionary of counters for word in wordList: if word in counters: # counter for word exists counters[word] += 1 else: # counter for word doesn't exist counters[word] = 1 for word in counters: # print word counts if counters[word] == 1: print('{:8} appears {} time.'.format(word, counters[word])) else: print('{:8} appears {} times.'.format(word, counters[word])) def wordCount(text): 'prints frequency of each word in text' wordList = text.split() # split text into list of words counters ={} # dictionary of counters for word in wordList: if word in counters: # counter for word exists counters[word] += 1 else: # counter for word doesn't exist counters[word] = 1 for word in counters: # print word counts if counters[word] == 1: print('{:8} appears {} time.'.format(word, counters[word])) else: print('{:8} appears {} times.'.format(word, counters[word])) >>> text = 'all animals are equal but some animals are more equal than other' >>> wordCount(text) all appears 1 time. animals appears 2 times. some appears 1 time. equal appears 2 times. but appears 1 time. other appears 1 time. are appears 2 times. than appears 1 time. more appears 1 time. >>> >>> text = 'all animals are equal but some animals are more equal than other' >>> wordCount(text) all appears 1 time. animals appears 2 times. some appears 1 time. equal appears 2 times. but appears 1 time. other appears 1 time. are appears 2 times. than appears 1 time. more appears 1 time. >>>

Introduction to Computing Using Python Exercise Implement function lookup() that implements a phone book lookup application. Your function takes, as input, a dictionary representing a phone book, mappingtuples (containing the first and last name) to strings (containing phone numbers) def lookup(phonebook): '''implements interactive phone book service using the input phonebook dictionary''' while True: first = input('Enter the first name: ') last = input('Enter the last name: ') person = (first, last) # construct the key if person in phonebook: # if key is in dictionary print(phonebook[person]) # print value else: # if key not in dictionary print('The name you entered is not known.') def lookup(phonebook): '''implements interactive phone book service using the input phonebook dictionary''' while True: first = input('Enter the first name: ') last = input('Enter the last name: ') person = (first, last) # construct the key if person in phonebook: # if key is in dictionary print(phonebook[person]) # print value else: # if key not in dictionary print('The name you entered is not known.') >>> phonebook = { ('Anna','Karenina'):'(123) ', ('Yu', 'Tsun'):'(901) ', ('Hans', 'Castorp'):'(321) '} >>> lookup(phonebook) Enter the first name: Anna Enter the last name: Karenina (123) Enter the first name: >>> phonebook = { ('Anna','Karenina'):'(123) ', ('Yu', 'Tsun'):'(901) ', ('Hans', 'Castorp'):'(321) '} >>> lookup(phonebook) Enter the first name: Anna Enter the last name: Karenina (123) Enter the first name:

Introduction to Computing Using Python Character encodings A string ( str ) object contains an ordered sequence of characters which can be any of the following: lowercase and uppercase letters in the English alphabet: a b c … z and A B C … Z decimal digits: punctuation:,. : ; ‘ “ ! ? etc. Mathematical operators and common symbols: = + - / * $ # & etc. More later Each character is mapped to a specific bit encoding, and this encoding maps back to the character. For many years, the standard encoding for characters in the English language was the American Standard Code for Information Interchange (ASCII)

Introduction to Computing Using Python ASCII For many years, the standard encoding for characters in the English language was the American Standard Code for Information Interchange (ASCII) The code for a is 97, which is in binary or 0x61 in hexadecimal notation The encoding for each ASCII character fits in 1 byte (8 bits)

>>> ord('a') 97 >>> ord('?') 63 >>> ord('\n') 10 >>> >>> ord('a') 97 >>> ord('?') 63 >>> ord('\n') 10 >>> >>> ord('a') 97 >>> ord('?') 63 >>> ord('\n') 10 >>> chr(10) '\n' >>> chr(63) '?' >>> chr(97) 'a' >>> >>> ord('a') 97 >>> ord('?') 63 >>> ord('\n') 10 >>> chr(10) '\n' >>> chr(63) '?' >>> chr(97) 'a' >>> Introduction to Computing Using Python Built-in functions ord() and char() Function ord() takes a character (i.e., a string of length 1) as input and returns its ASCII code Function chr() takes an ASCII encoding (i.e., a non-negative integer) and returns the corresponding character

Introduction to Computing Using Python Beyond ASCII A string object contains an ordered sequence of characters which can be any of the following: lowercase and uppercase letters in the English alphabet: a b c … z and A B C … Z decimal digits: punctuation:,. : ; ‘ “ ! ? etc. Mathematical operators and common symbols: = + - / * $ # & etc. Characters from languages other than English Technical symbols from math, science, engineering, etc. There are only 128 characters in the ASCII encoding Unicode has been developed to be the universal character encoding scheme

>>> '\u0061' 'a' >>> >>> '\u0061' 'a' >>> >>> '\u0061' 'a' >>> '\u0064\u0061d' 'dad' >>> >>> '\u0061' 'a' >>> '\u0064\u0061d' 'dad' >>> >>> '\u0061' 'a' >>> '\u0064\u0061d' 'dad' >>> '\u0409\u0443\u0431\u043e\u043c\u 0438\u0440' 'Љубомир' >>> >>> '\u0061' 'a' >>> '\u0064\u0061d' 'dad' >>> '\u0409\u0443\u0431\u043e\u043c\u 0438\u0440' 'Љубомир' >>> >>> '\u0061' 'a' >>> '\u0064\u0061d' 'dad' >>> '\u0409\u0443\u0431\u043e\u043c\u 0438\u0440' 'Љубомир' >>> '\u4e16\u754c\u60a8\u597d!' ' 世界您好 !' >>> >>> '\u0061' 'a' >>> '\u0064\u0061d' 'dad' >>> '\u0409\u0443\u0431\u043e\u043c\u 0438\u0440' 'Љубомир' >>> '\u4e16\u754c\u60a8\u597d!' ' 世界您好 !' >>> Introduction to Computing Using Python Unicode In Unicode, every character is represented by an integer code point. The code point is not necessarily the actual byte representation of the character; it is just the identifier for the particular character The code point for letter a is the integer with hexadecimal value 0x0061 Unicode conveniently uses a code point for ASCII characters that is equal to their ASCII code With Unicode, we can write strings in english With Unicode, we can write strings in english cyrillic With Unicode, we can write strings in english cyrillic chinese … escape sequence \u indicates start of Unicode code point

>>> s1 = '\u0021' >>> s1 '!' >>> s2 = '\u0409' >>> s2 'Љ' >>> s1 < s2 True >>> >>> s1 = '\u0021' >>> s1 '!' >>> s2 = '\u0409' >>> s2 'Љ' >>> s1 < s2 True >>> Introduction to Computing Using Python String comparison, revisited Unicode code points, being integers, give a natural ordering to all the characters representable in Unicode Unicode was designed so that, for any pair of characters from the same alphabet, the one that is earlier in the alphabet will have a smaller Unicode code point.

Introduction to Computing Using Python Unicode Transformation Format (UTF) A Unicode string is a sequence of code points that are numbers from 0 to 0x10FFFF. Unlike ASCII codes, Unicode code points are not what is stored in memory; the rule for translating a Unicode character or code point into a sequence of bytes is called an encoding. There are several Unicode encodings: UTF-8, UTF-16, and UTF-32. UTF stands for Unicode Transformation Format. UTF-8 has become the preferred encoding for and web pages The default encoding when you write Python 3 programs is UTF-8. In UTF-8, every ASCII character has an encoding that is exactly the 8-bit ASCII encoding.

>>> content b'This is a text document\nposted on the\nWWW.\n' >>> type(content) >>> >>> content b'This is a text document\nposted on the\nWWW.\n' >>> type(content) >>> >>> content b'This is a text document\nposted on the\nWWW.\n' >>> type(content) >>> s = content.decode('utf-8') >>> type(s) >>> s 'This is a text document\nposted on the\nWWW.\n' >>> >>> content b'This is a text document\nposted on the\nWWW.\n' >>> type(content) >>> s = content.decode('utf-8') >>> type(s) >>> s 'This is a text document\nposted on the\nWWW.\n' >>> >>> content b'This is a text document\nposted on the\nWWW.\n' >>> type(content) >>> s = content.decode('utf-8') >>> type(s) >>> s 'This is a text document\nposted on the\nWWW.\n' >>> s = content.decode() >>> s 'This is a text document\nposted on the\nWWW.\n' >>> >>> content b'This is a text document\nposted on the\nWWW.\n' >>> type(content) >>> s = content.decode('utf-8') >>> type(s) >>> s 'This is a text document\nposted on the\nWWW.\n' >>> s = content.decode() >>> s 'This is a text document\nposted on the\nWWW.\n' >>> Introduction to Computing Using Python Assigning an encoding to “raw bytes” When a file is downloaded from the web, it does not have an encoding the file could be a picture or an executable program, i.e. not a text file the downloaded file content is a sequence of bytes, i.e. of type bytes The bytes method decode() takes an encoding description as input and returns a string that is obtained by applying the encoding to the sequence of bytes the default is UTF-8 The bytes method decode() takes an encoding description as input and returns a string that is obtained by applying the encoding to the sequence of bytes

Introduction to Computing Using Python Randomness Some apps need numbers generated “at random” (i.e., from some probability distribution): scientific computing financial simulations cryptography computer games Truly random numbers are hard to generate Most often, a pseudorandom number generator is used numbers only appear to be random they are really generated using a deterministic process The Python standard library module random provides a pseudo random number generator as well useful sampling functions

>>> import random >>> random.randrange(1, 7) 2 >>> >>> import random >>> random.randrange(1, 7) 2 >>> >>> import random >>> random.randrange(1, 7) 2 >>> random.randrange(1, 7) 1 >>> >>> import random >>> random.randrange(1, 7) 2 >>> random.randrange(1, 7) 1 >>> >>> import random >>> random.randrange(1, 7) 2 >>> random.randrange(1, 7) 1 >>> random.randrange(1, 7) 4 >>> >>> import random >>> random.randrange(1, 7) 2 >>> random.randrange(1, 7) 1 >>> random.randrange(1, 7) 4 >>> >>> import random >>> random.randrange(1, 7) 2 >>> random.randrange(1, 7) 1 >>> random.randrange(1, 7) 4 >>> random.randrange(1, 7) 2 >>> >>> import random >>> random.randrange(1, 7) 2 >>> random.randrange(1, 7) 1 >>> random.randrange(1, 7) 4 >>> random.randrange(1, 7) 2 >>> >>> import random >>> random.randrange(1, 7) 2 >>> random.randrange(1, 7) 1 >>> random.randrange(1, 7) 4 >>> random.randrange(1, 7) 2 >>> random.uniform(0, 1) >>> random.uniform(0, 1) >>> random.uniform(0, 1) >>> >>> import random >>> random.randrange(1, 7) 2 >>> random.randrange(1, 7) 1 >>> random.randrange(1, 7) 4 >>> random.randrange(1, 7) 2 >>> random.uniform(0, 1) >>> random.uniform(0, 1) >>> random.uniform(0, 1) >>> Introduction to Computing Using Python Standard Library module random Function randrange() returns a “random” integer number from a given range range is from 1 up to (but not including) 7 Function uniform() returns a “random” float number from a given range Example usage: simulate the throws of a die

>>> names = ['Ann', 'Bob', 'Cal', 'Dee', 'Eve', 'Flo', 'Hal', 'Ike'] >>> import random >>> random.shuffle(names) >>> names ['Hal', 'Dee', 'Bob', 'Ike', 'Cal', 'Eve', 'Flo', 'Ann'] >>> >>> names = ['Ann', 'Bob', 'Cal', 'Dee', 'Eve', 'Flo', 'Hal', 'Ike'] >>> import random >>> random.shuffle(names) >>> names ['Hal', 'Dee', 'Bob', 'Ike', 'Cal', 'Eve', 'Flo', 'Ann'] >>> >>> names = ['Ann', 'Bob', 'Cal', 'Dee', 'Eve', 'Flo', 'Hal', 'Ike'] >>> import random >>> random.shuffle(names) >>> names ['Hal', 'Dee', 'Bob', 'Ike', 'Cal', 'Eve', 'Flo', 'Ann'] >>> random.choice(names) 'Bob' >>> random.choice(names) 'Ann' >>> random.choice(names) 'Cal' >>> random.choice(names) 'Cal' >>> >>> names = ['Ann', 'Bob', 'Cal', 'Dee', 'Eve', 'Flo', 'Hal', 'Ike'] >>> import random >>> random.shuffle(names) >>> names ['Hal', 'Dee', 'Bob', 'Ike', 'Cal', 'Eve', 'Flo', 'Ann'] >>> random.choice(names) 'Bob' >>> random.choice(names) 'Ann' >>> random.choice(names) 'Cal' >>> random.choice(names) 'Cal' >>> >>> names = ['Ann', 'Bob', 'Cal', 'Dee', 'Eve', 'Flo', 'Hal', 'Ike'] >>> import random >>> random.shuffle(names) >>> names ['Hal', 'Dee', 'Bob', 'Ike', 'Cal', 'Eve', 'Flo', 'Ann'] >>> random.choice(names) 'Bob' >>> random.choice(names) 'Ann' >>> random.choice(names) 'Cal' >>> random.choice(names) 'Cal' >>> random.sample(names, 3) ['Ike', 'Hal', 'Bob'] >>> random.sample(names, 3) ['Flo', 'Bob', 'Ike'] >>> random.sample(names, 3) ['Ike', 'Ann', 'Hal'] >>> >>> names = ['Ann', 'Bob', 'Cal', 'Dee', 'Eve', 'Flo', 'Hal', 'Ike'] >>> import random >>> random.shuffle(names) >>> names ['Hal', 'Dee', 'Bob', 'Ike', 'Cal', 'Eve', 'Flo', 'Ann'] >>> random.choice(names) 'Bob' >>> random.choice(names) 'Ann' >>> random.choice(names) 'Cal' >>> random.choice(names) 'Cal' >>> random.sample(names, 3) ['Ike', 'Hal', 'Bob'] >>> random.sample(names, 3) ['Flo', 'Bob', 'Ike'] >>> random.sample(names, 3) ['Ike', 'Ann', 'Hal'] >>> Introduction to Computing Using Python Standard Library module random Defined in module random are functions shuffle(), choice(), sample(), …

>>> game(2, 3) Enter next position (format: x y): 0 2 No bomb at position 0 2 Enter next position (format: x y): 1 1 No bomb at position 1 1 Enter next position (format: x y): 0 1 You found the bomb! >>> game(2, 3) Enter next position (format: x y): 0 2 No bomb at position 0 2 Enter next position (format: x y): 1 1 No bomb at position 1 1 Enter next position (format: x y): 0 1 You found the bomb! import random def game(rows, cols): 'a simple bomb finding game' # generate a list of size rows*cols that contains # empty strings except for 1 'B' at some random index table = (rows*cols-1)*[''] + ['B'] random.shuffle(table) while True: pos = input('Enter next position (format: x y): ') position = pos.split() # position (x, y) corresponds to index x*cols + y of table if table[int(position[0])*cols + int(position[1])] == 'B': print('You found the bomb!') break else: print('No bomb at position', pos) import random def game(rows, cols): 'a simple bomb finding game' # generate a list of size rows*cols that contains # empty strings except for 1 'B' at some random index table = (rows*cols-1)*[''] + ['B'] random.shuffle(table) while True: pos = input('Enter next position (format: x y): ') position = pos.split() # position (x, y) corresponds to index x*cols + y of table if table[int(position[0])*cols + int(position[1])] == 'B': print('You found the bomb!') break else: print('No bomb at position', pos) Introduction to Computing Using Python Exercise Develop function game() that: takes integers r and c as input, generates a field of r rows and c columns with a bomb at a randomly chosen row and column, and then asks users to find the bomb