Download presentation
Presentation is loading. Please wait.
1
Week 10 - Wednesday CS 113
2
Last time What did we talk about last time? Traveling salesman problem
Other hard problems NP-completeness P vs. NP
3
Questions?
4
Project 3
5
Turing Machines
6
Turing machine A Turing machine is a model of computation
It consists of a head, an infinitely long tape, a set of possible states, and an alphabet of characters that can be written on the tape A finite list of rules says what it should write and whether it should move left or right given the current symbol and state A 1
7
Turing machine example
3 state, 2 symbol “busy beaver” Turing machine: Starting state A Tape Symbol State A State B State C Write Move Next 1 R B C L HALT A
8
Computational power Computational power means the ability to solve a problem The ability to run an algorithm Speed is not related to computational power Turing machines have as much computational power as any known computer Any algorithm that can be run on any computer can be run on a Turing machine
9
Do you own a Turing machine?
A desktop or laptop computer can simulate the action of a Turing machine Anything that can simulate a Turing machine has the same computational power as a Turing machine Of course, the concept of a Turing machine requires infinite tape There are some things that a "true" Turing machine could compute that would cause your computer to run out of memory
10
Are you a Turing machine?
If a Turing machine is the most powerful tool for computation there is, then you can't be more powerful than a Turing machine Does your brain simply change from one state to another according to a series of fixed rules? Some neurologists think that we're closer to that than we'd like to admit Perhaps our ability to break rules makes us strong Maybe it doesn't matter…
11
Halting Problem
12
Trouble! There are some computational problems that you cannot design an algorithm for No computer can ever solve the general problem (though sometimes you can solve instances of the problem) Examples It's impossible to write a Python program that can tell if any Python program will run to completion
13
Halting problem Given a Turing machine and input x, does it reach the halt state? This problem is undecidable That means that there is no algorithm that can be to determine if any Turing machine will go into an infinite loop Consequently, there is no algorithm that can take any program and check to see if it goes into an infinite loop
14
Turntables Douglas Hofstadter uses the metaphor of turntables
Imagine that evil people design records that will shake turntables apart when they're played Maybe turntable A can play record A and turntable B can play record B However, if turntable A plays record B, it will shatter
15
Stuff you have to buy for this proof
Turing machines can perform all possible computations It's possible to encode the way a Turing machine works such that another Turing machine can read it It's easy to make a slight change to a Turing machine so that it gives back the opposite answer (or goes into an infinite loop)
16
Proof by contradiction
H m x YES NO You've got a Turing machine M with encoding m You want to see if M will halt on input x Assume there is a machine H that can take encoding m and input x H(m,x) is YES if it halts H(m,x) is NO if it loops forever We create (evil) machine E that takes description m and runs H(m,m) If H(m,m) is YES, E loops forever If H(m,m) is NO, E returns YES H YES NO E m Loop forever
17
A mind-bending proof Let's say that e is the description of E
What happens if you feed description e into E? E(e) says what E will do with itself as input If it returns YES, that means that E on input e loops forever But it can't, because it just returned YES If it loops forever, then E on input e would return YES But it can't, because it's looping forever! Our assumption that machine H exists must be wrong
18
Post correspondence problem
Given two finite lists of words A and B, can you pick k words (repetitions allowed) from A and k words (repetitions allowed) from B so that the words from A concatenated are exactly the same string as the words from B concatenated Example: Solution: aa + bb + bb = aabbbb = a + a + bbbb The Post correspondence problem (PCP) is undecidable (there is no algorithm that can solve all instances of it) A B aa bbbb aba a bb abba
19
Python Review
20
Variables In Python, the first time we assign a value to a name it creates a variable The = sign is the assignment operator Think of it as an arrow that points left, storing whatever is on the right into the variable We can use whatever is stored in a variable like it's a value person = "Walter White" print(person)
21
Conversion to an integer
Sometimes you need to convert a string value to an integer, especially if you read it from a file Use the int() function In other cases, you want to convert a string to a floating point value (a decimal) Then, use the float() function word = "125" number = int(word) # number is now 125 text = "6.125" value = float(text) # value is now 6.125
22
Visual Python Be familiar with the following shapes for the exam Box:
Sphere: The pos attribute gives the location of the center of each All shapes also have a color attribute box(pos=vector(x,y,z),size=vector(l,h,w)) sphere(pos=vector(x,y,z),radius=r)
23
while loops The while loop runs as long as a condition is true
In this case, when countdown becomes 0, the loop stops (since 0 is not less than 0) Note that while loops use the same relational operators as if statements countdown = 10 while countdown > 0: print(countdown) countdown = countdown – 1 print("Blast-off!")
24
for loops If you want to do something, say, 10 times in Python, you can use a for loop But you need to call the range() method to generate a list of numbers for you In this case, the loop will run 10 times, and the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 will print out for i in range(10): print(i)
25
if statements In Python, the primary way to make a choice is with an if statement Whatever code is under the if and tabbed in will only be executed if the condition is true Optionally, an else section can be added if you want to do something if the condition is false Conditions often use the following relational operators to make a comparison: ==, !=, <, <=, >, >= if phrase == "open sesame": print("Welcome, Ali Baba!") else: print("Access denied!")
26
Else It is often the case that we want to do one thing if a certain condition is met and something else if it is not Example: If it's raining: I'll bring an umbrella Otherwise: I'll eat lunch in the park Python uses the keyword else to mark code that will be executed if the condition was false
27
Things to watch out for The condition of an if must be followed by a colon (:) Never use = in a condition (always use ==) It's easy to be off by one (x < 5 is not the same as x <= 5) An else also has a colon after it An else never has a condition It marks what gets done when the if's condition is false Using an else is not required But you can't have an else without and if
28
Operations on Booleans
The condition of an if or a while is a Boolean value Booleans are either True or False To make complex decisions, we may need to combine multiple Boolean values together You might be familiar with these operations if you have taken a course in logic
29
The not operator The not operator
Changes a True into a False or a False into a True x not(x) True False
30
The and operator The and operator
It gives back True only if both things being combined are True If I can swim AND the pool is not filled with acid, then I will survive x y x and y True False
31
The or operator The or operator
It gives back True if either or both things being combined are True If I get punched in the face OR kicked in the stomach, then I will be in pain x y x or y True False
32
Example of and The following code will check if a number x has a single digit The same effect could be achieved with an if statement inside of an if statement, but this form is cleaner if x >= 0 and x < 10: print("Your number has a single digit!")
33
Multiple options Sometimes you want to make a choice between more than two things Essentially, you want a long list of mutually exclusive options This can be done by nesting another if inside of an else And then an if inside of its else … But if you have a long list of options, your level of indentation gets crazy
34
elif Python has a special keyword elif that combines else and if
Start with an if for the first condition, use an elif for each condition in between, and almost always finish with a final else if condition1: statement1 elif condition2: statement2 elif condition3: statement3 elif condition4: statement4 else: statement5
35
Functions
36
Idea of a function Functions allow you to package up some code to run over and over Functions usually take some input (like numbers or text) so that they can be customized Functions often give back an answer (like the square root of a number) Also called methods in some other languages The customizable purple blocks played the role of functions in Scratch
37
Advantages of functions
More modular programming Break a program into separate tasks Each task could be assigned to a different programmer Code reusability Use code over and over Even from other programs Less code duplication Improved readability Each function can do a few, clear tasks
38
Defining a function Name of 1st argument Function name
def name( arg1, … , argn ): statement1 statement2 … statementm Required syntax Name of last argument Code done by function
39
Simple function example
Given two numbers, find the smaller: def smaller(a, b): if a < b: return a else : return b
40
Value returning functions
It is possible to divide functions into two types: Functions that return values Functions that don't return values Functions that do return values give an answer: It's as if the function is replaced by whatever answer is returned x = 3 y = 4 small = smaller(x, y) #small contains 3
41
Functions that don't return values
A function doesn't have to return an answer: This function only prints things to the screen A function that doesn't return anything does some task but doesn't give back an answer def callForHelp(times): for i in range(times): print("Help!")
42
return statements Like most code in Python, the code inside of a function executes line by line Of course, you are allowed to put if statements and loops inside methods You can also put in return statements A function will stop executing and jump back to wherever it was called from when it hits a return The return statement is where you put the value that will be given back to the caller
43
Calling functions Defining a function is only half the game
You have to call functions to use them Calling a function means giving it the parameters (or arguments) it needs and then waiting for its answer By now, you have done many function calls print() sin() You can call your own functions the same way
44
Calling functions callForHelp(3) #calls for help 3 times
You type the name of the function and then its arguments in parentheses If it's a value returning function, you can store the answer it gives back The arguments you give can be values or variables You have to give the function the right number of arguments or the program will have an error callForHelp(3) #calls for help 3 times result = smaller(9, 2)
45
Key syntax Every function starts with def
Then comes the name of the function Followed by the names of the arguments in parentheses Followed by a colon (:) Like loops and if statements, the code inside a function is indented one level Call the function in other code by typing the name and the correct number of arguments in parentheses
46
Lists in Python
47
Strings Strings hold text
They are lists of characters (letters, digits, punctuation, etc.) A string literal in Python is text with either single or double quotes around it It doesn't matter which you use, but you can't mix them in one string line = "Stop, collaborate, and listen!" countdown = 'Launching in 5, 4, 3, 2, 1... Blast off!'
48
String operations You can use + to concatenate two strings together (to get a third string that is both of them stuck together) You can use * to get repetitions of a string place = "boon" + "docks" print(place) #prints boondocks comment = "yeah " * 3 print(comment) #prints yeah yeah yeah
49
String operations continued
You can use the len() function to get the length of a string You can use square brackets to get a particular character in the string Indexes start at 0 The first character in a string is at 0, the last is at its length - 1 author = "Thomas Pynchon" print( len(author) ) #prints 14 movie = "Dr. Strangelove" print(movie[4]) #prints S
50
Slices If you want to get more than one character from a string, you can use the slice notation Two numbers with a colon (:) in between The first number is the starting point, the second number is the location after the ending point If you subtract the first from the last, you'll get the length of the result adjective = "dysfunctional" noun = adjective[3:6] #noun contains "fun"
51
Lists You can think of a string as a list of characters
Python provides a way to make lists of other things too To make a list, you can put a collection of objects inside square brackets They can even be different types days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] stuff = ["Danger!", 3, True, 1.7]
52
Accessing an element As with strings, use square brackets and a number to access an element in the list Like strings, elements are numbered from 0 to the length – 1 You can use the len() function to get the length of a list days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] bleh = days[0] #contains "Monday" count = len(days) #contains 7
53
Changing elements in a list
You can also change the elements in a list using the square bracket notation This is one of the bigger differences between strings and general lists You cannot change the characters in a string You have to make a new string birds = ["Duck", "Duck", "Duck"] birds[2] = "Goose" print(birds) #prints ['Duck', 'Duck', 'Goose']
54
Slices on lists Just like strings, you can use the slice notation to get a copy of part of a list There are shortcuts too Python assumes 0 if you leave off the first number It assumes the length if you leave off the last number days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] weekend = days[5:7] print(weekend) #prints ['Saturday', 'Sunday'] weekdays = days[:5] #Monday through Friday
55
For loops and lists A for loop can be used to iterate over all the elements in a list Since a string is a special kind of list, you can iterate over the characters in them too days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] for day in days: print( day ) #prints each day on a line word = "HEY" for letter in word: print( letter ) #H E Y on separate lines
56
split() method Sometimes you get a string that contains a lot of words
You'd like to split the string up into a list of those individual words so that you can deal with each Calling the split(" ") method returns just such a list, breaking apart the string wherever there is a space character (" ") sentence = "I seem to be having tremendous difficulty with my lifestyle." words = sentence.split(" ") print(words[5]) #prints tremendous print( len(words) ) #prints 10
57
Files
58
Files A file is simply a sequence of bytes
Or characters, if you want of think of it that way All files are binary files, in the sense that the data is ultimately 1s and 0s Some files are also text files A text file can be read by a human, not just a computer If you can open the file with Notepad and read something meaningful, it's a text file Python (.py) files are a good example of text files Word (.doc or .docx) files are not text files, since they are formatted in a way that only the Word program can read
59
Reading text files Python makes it easy to read text files
Unfortunately, GlowScript.org uses a more complicated command The first step is to open the file If you put this at the top of your program, there will be a Choose File button that will let you pick a file on your computer Inside the variable you store into (file, in this case) is a field called text, which will contain the contents of the file you pick, as a string file = read_local_file(scene.title_anchor, wait)
60
Printing a file to the screen
To print a file to the screen, we open it and loop through everything in it We want to divide file (a giant string) into a list of lines, using the split() method Between every line in the file is a special character "\n", which means end of line file = read_local_file(scene.title_anchor, wait) lines = file.text.split("\n") for line in lines: print( line )
61
Adding up the numbers in a file
What if a file contains a bunch of numbers, with each one on a separate line? We could add them up and print out the sum file = read_local_file(scene.title_anchor, wait) lines = file.text.split("\n") sum = 0 for line in lines: sum = sum + int(line) #convert line to int print("Sum: " + sum)
62
Quiz
63
Upcoming
64
Next time… Finish review for Exam 2 Lab 10
65
Reminders Work on Project 4 Work on Design Document for Final Project
Due Friday! Exam 2 is next Monday We'll finish the review on Friday
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.