PyClass

Today

Example #1: The number guessing game:

Write a program that asks you to guess a number.

Setup

# This is a guess the number game.
import random

guessesTaken = 0

print('Hello! What is your name?')
myName = input()

number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
    

The main body of the game:

while guessesTaken < 6:
    print('Take a guess.')
    guess = input()
    guess = int(guess)

    guessesTaken = guessesTaken + 1

    if guess < number:
        print('Your guess is too low.')

    if guess > number:
        print('Your guess is too high.')

    if guess == number:
        break
    

Score / results:

if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + myName + '! You guessed my number in ' + \
    guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)

Gambling with the guessing game

Play the number guessing game, let the computer know beforehand how many chances to give you. Suppose you decide you can guess the number in 3 chances. If you do, you get (20 - 3) dollars. If you lose, you lose (20 - 3) dollars. How many chances should you ask for?

Example #2: The plaintext attack

http://en.wikipedia.org/wiki/Chosen-plaintext_attack

Basic gist: A chosen-plaintext attack (CPA) is an attack model for cryptanalysis which presumes that the attacker has the capability to choose arbitrary plaintexts to be encrypted and obtain the corresponding ciphertexts. The goal of the attack is to gain some further information which reduces the security of the encryption scheme. In the worst case, a chosen-plaintext attack could reveal the scheme's secret key.

Cracking encryption using the plaintext attack

Given:

Decrypt all sentences.

Encrypted lines (saved in a text file):

 
uryyb gurer
gur dhvpx oebja sbk whzcf bire gur ynml qbt
sbhe fpber naq frira lrnef ntb
rirelguvat va vgf evtug cynpr
    

Setup + read file

 
import string
import sys

_lines = open("test.txt", "r").readlines()
lines = [x.rstrip() for x in _lines]
    

Find the encrypted version of our line:

our_unencrypted_line = "the quick brown fox jumps over the lazy dog"
our_line = ""

for line in lines:
    for a in string.lowercase:
        if a not in line: break
    else:
        our_line = line
    

Decrypt all lines:

translation = {}

for encrypted, unencrypted in zip(our_line, our_unencrypted_line):
    translation[encrypted] = unencrypted

for line in lines:
    for a in line:
        sys.stdout.write(translation[a])
        print

Problem 3: The Animal Game

See a demo online: http://animalgame.com

[Code will be written in class]