Author Archives: graceliana@gmail.com

List: Algorithm – Hangman Intro

Functions revisited
1. A function is defined with a name and a set of parentheses followed by a colon
2. A def is a function
3. It also has a key word: def at the left side, no indentation
4. It should be defined right after any imports
5. If the function needs a value from another function, it should be inside the
parentheses. This is called the argument
6. If there is more than one argument, it is called an argument list
7. If there are no arguments, it is called an empty argument list

hangman.py

Hangman Game

HANGMANPICS = ['''

  +---+
  |   |
      |
      |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']

words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()

def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]

print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False


Classwork:
A. Write a short program, YI_printSpecial.py to display the shape on the screen using ‘ ‘ ‘:

   ___
 /     \
|       |
 \ ___ /
 

B. Write a short program, YI_wordList1.py as follows:
1) Use the words list with
2) the split() function and
3) print all the elements of this list by using a “while” or “for” loop


Homework:
Write a short program, YI_wordList2.py with the following specifications:
1) Must contain a list of words
2) Use the split() function
3) Have a random integer from 0 to 9 to pick a word.
4) Display 3 random words by using a “while” or “for” loop.

List: Slicing and Indexing with Connect 4

In the program hangman.py we learned how to slice a string and indexing in the previous assignments, pig latin and swapping letters.

The Connect 4 program can be written using strings.
Here is a little help:

# Using strings:
connect_board = '''|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|'''

# what do the indices look like?

# |  1  |  3  |  5  |  7  |  9  | 11  | 
# | 15  | 17  | 19  | 21  | 23  | 25  | 
# | 29  | 31  | 33  | 35  | 37  | 39  | 
# | 43  | 45  | 47  | 49  | 51  | 53  | 
# | 57  | 59  | 61  | 63  | 65  | 67  | 
# |  1  |  2  |  3  |  4  |  5  |  6  | 
In the last row you have the column numbers.


print('Empty board: ')
print(connect_board)
print( ' 1 2 3 4 5 6 ')
print('\nThe length of the string is ',len(connect_board))


print('')
yesNo = 'y'
while yesNo == 'y':
    column = int(input("Enter the column number "))
    offset = 1
    if column == 2:
        offset = 3
    elif column == 3:
        offset = 5
    elif column == 4:
        offset = 7
    elif column == 5:
        offset = 9
    elif column == 6:
        offset = 11
    empty = True
    position = offset + (14 * 4)
    while empty:
        if connect_board[position] == '_':
            connect_board = connect_board[:position] + 'A' + connect_board[position + 1:]
            print(connect_board)
            print( ' 1 2 3 4 5 6 ')
            empty = False
        else:
            position -= 14

    yesNo = input('More? ')

A test run could look like this:

Empty board: 
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
 1 2 3 4 5 6 


Enter the column number 1
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
 1 2 3 4 5 6 
More? y
Enter the column number 1
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|_|_|_|
 1 2 3 4 5 6 
More? y
Enter the column number 4
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|A|_|_|
 1 2 3 4 5 6 
More? y
Enter the column number 6
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|A|_|A|
 1 2 3 4 5 6 
More? y
Enter the column number 5
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|A|A|A|
 1 2 3 4 5 6 
More? y
Enter the column number 2
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|A|_|A|A|A|
 1 2 3 4 5 6 
More? y
Enter the column number 1
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|_|_|_|
|A|A|_|A|A|A|
 1 2 3 4 5 6 
More? y
Enter the column number 3
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|_|_|_|
|A|A|A|A|A|A|
 1 2 3 4 5 6 
More? 

Homework:
Write the pseudocode for the “Connect 4” program. Check edmodo.com for a little help on the pseudocode.

List: memory cards

Classwork: Homework discussion
The assignment below is designed to help you implement the memory cards program.
The idea is that letters a through h are associated with rectangles rect_a through rect_h. When a player chooses letter a, he or she is choosing rect_a. Think of this: when the user click on a memory card all you know is the location of the point and then you use the point to figure out which rectangle contains that point.
A rectangle in this assignment is associated with a file name just like in the memory cards a rectangle is associated with an image ( an image name ).
If you look at rect_a and rect_e, both are associated with the same file name. So picking a rectangle allows you to check whether the names are equal. But how do you work this out when you shuffle them? That is the part you have to think about.

rect_a = 'a'
rect_b = 'b'
rect_c = 'c'
rect_d = 'd'
rect_e = 'e'
rect_f = 'f'
rect_g = 'g'
rect_h = 'h'

original_images = ['trees.bmp','sky.bmp','water.bmp','lilypads.bmp','trees.bmp','sky.bmp','water.bmp','lilypads.bmp']
    
rectangles = [rect_a,rect_b,rect_c,rect_d,rect_e,rect_f,rect_g,rect_h]


## Write a program in python, twoMatchingFiles_YI.py to prompt the user for two strings from 'a' through 'h'(in the alphabet). Use the variables shown above.
## 1. Check if the user guesses two matching bmp file names. Use a for loop to accomplished this.
## 2. Loop until the user found a match.
## 3. Prompt the user to quit? or play again?
## 4. If play again is selected, randomly scramble the bmp file names before the program continues.
## 5. If you have already written your program for the matching cards, copy your code snippet
##    for this part of the program. 

Algorithm: Agnes Grades

Assignment:

Agnes Gru keeps track of her grades with the help of a python program, YI_AgnesGrades.py. (YI in the program name represents your initials)

agnesgru
This is her schedule:

twoLists = [['biology','chemistry','physics','horticulture', 'english','math','phys ed','spanish'],['period 1','period 2','period 3', 'period 4','period 5','period 6','period 7', 'period 8']]


##        biology        period 1
##      chemistry        period 2
##        physics        period 3
##   horticulture        period 4
##        english        period 5
##           math        period 6
##        phys ed        period 7
##        spanish        period 8

She has Test grades, Homework grades and Classwork grades for all of her classes. These categories have different weights. Homework and Classwork represent each 30% of her grade. Her test category represents 40% of her marking period grade. Write YI_AgnesGrades.py program for Agnes using functions and what your learned from twoLists.
You program should

  1. Prompt Agnes for her grades. (This function should be activated after the program is successfully completed)
  2. Calculate each category average.
  3. Calculate her final grade for the marking period for each period.
  4. End the program by displaying each of her categories percentages and her marking period grade.

Make sure you use full sentences so Agnes can easily understand the results.

Use the following data with the purpose of developing your program and assessment:
Suggestion code:

# Program description
# author's name
# python version

##################
# Use these data
##################


#Period 1

#    15 homework grades
hwk1 = [86 ,76 ,79 ,72 ,78 ,77 ,90 ,86 ,79 ,71 ,89 ,79 ,98 ,87 ,96 ]
#    20 classwork grades
clwk1 = [71 ,86 ,76 ,86 ,88 ,79 ,85 ,98 ,75 ,87 ,76 ,99 ,75 ,85 ,74 ,71 ,77 ,80 ,85 ,76 ]
#    5 test grades
tst1 = [94 ,84 ,92 ,80 ,86 ]

#Period 2

#    15 homework grades
hwk2 = [90 ,97 ,74 ,80 ,93 ,75 ,84 ,94 ,94 ,86 ,79 ,88 ,100 ,80 ,71]
#    20 classwork grades
clwk2 = [84 ,92 ,93 ,83 ,86 ,82 ,84 ,98 ,76 ,80 ,74 ,71 ,95 ,99 ,73 ,78 ,70 ,80 ,73 ,72 ]
#    5 test grades
tst2 = [95 ,83 ,85 ,96 ,86 ]

#Period 3

#    15 homework grades
hwk3 = [88 ,74 ,88 ,100 ,82 ,77 ,85 ,90 ,98 ,89 ,99 ,96 ,81 ,75 ,85 ]
#    20 classwork grades
clwk3 = [83 ,79 ,94 ,71 ,92 ,90 ,97 ,96 ,77 ,89 ,100 ,80 ,95 ,85 ,78 ,73 ,95 ,75 ,92 ,70 ]
#    5 test grades
tst3 = [83 ,92 ,88 ,85 ,99 ]

#Period 4

#    15 homework grades
hwk4 = [82 ,76 ,85 ,81 ,80 ,73 ,73 ,100 ,96 ,97 ,74 ,78 ,91 ,90 ,82 ]
#    20 classwork grades
clwk4 = [97 ,98 ,71 ,90 ,79 ,90 ,72 ,84 ,73 ,83 ,87 ,91 ,81 ,74 ,76 ,91 ,82 ,82 ,87 ,75 ]
#    5 test grades
tst4 = [96 ,87 ,82 ,82 ,94 ]

#Period 5

#    15 homework grades
hwk5 = [77 ,95 ,79 ,75 ,97 ,90 ,76 ,94 ,93 ,84 ,89 ,95 ,74 ,91 ,97 ]
#    20 classwork grades
clwk5 = [96 ,91 ,91 ,86 ,92 ,76 ,72 ,70 ,87 ,84 ,87 ,87 ,76 ,83 ,72 ,99 ,82 ,76 ,75 ,79 ]
#    5 test grades
tst5 = [81 ,84 ,100 ,84 ,81 ]

#Period 6

#    15 homework grades
hwk6 = [94 ,91 ,71 ,82 ,73 ,78 ,84 ,82 ,75 ,83 ,93 ,98 ,86 ,100 ,76 ]
#    20 classwork grades
clwk6 = [81 ,86 ,95 ,92 ,83 ,80 ,97 ,84 ,96 ,90 ,97 ,82 ,79 ,77 ,74 ,94 ,78 ,85 ,80 ,74 ]
#    5 test grades
tst6 = [87 ,92 ,85 ,96 ,89 ]

#Period 7

#    15 homework grades
hwk7 = [88 ,83 ,97 ,82 ,78 ,89 ,99 ,74 ,71 ,86 ,81 ,72 ,91 ,87 ,95 ]
#    20 classwork grades
clwk7 = [97 ,83 ,99 ,100 ,97 ,88 ,92 ,73 ,88 ,82 ,96 ,76 ,95 ,75 ,93 ,95 ,93 ,72 ,93 ,95 ]
#    5 test grades
tst7 = [92 ,94 ,95 ,81 ,87 ]

#Period 8

#    15 homework grades
hwk8 = [100 ,88 ,92 ,74 ,82 ,88 ,75 ,80 ,93 ,82 ,85 ,85 ,97 ,94 ,78 ]
#    20 classwork grades
clwk8 = [97 ,85 ,90 ,73 ,73 ,99 ,96 ,100 ,99 ,77 ,99 ,88 ,78 ,83 ,96 ,84 ,89 ,93 ,99 ,90 ]
#    5 test grades
tst8 = [90 ,88 ,91 ,94 ,89 ]

##################
# functions
##################

def homework(hwk):
    ...
    return avg
        

def classwork(clwk):
    ...
    return avg

def test(tst):
    ...
    return avg


##################
# main
##################
...
while yesNo =="y":
    ...
    ...
    hwkAvg = round(homework(hwk))
    clswkAvg = round(classwork(clwk))
    tstAvg = round(test(tst))
    print('Averages are ',hwkAvg,'for Homework', clswkAvg, 'for Classwork',tstAvg, 'for Tests')
    ....
    print("The final quarter grade for period", periodx, "is", finalGrade)
    ...


NOTE: the three dots represent missing code that you need to fill in

Algorithm: Calorie and Fat Calculator

screen-shot-2016-11-16-at-10-32-19-pm

Write a python program, YI_FoodChart.py to provide calories and fat content in a selected number of foods.
– Choose 4 different categories of foods from the link attached to the image or any other resource you might want to use.
– Write a function for each of the categories with at least 5 foods choices.
– Display a menu and prompt the user for choices.
– Once the user is finished selecting, display the number of calories and the fat content.

Example:

1. Meats
2. Grains
3. Vegetables
4. Fruit

Choose a category: 2

1. Rice, brown long-grain  Fat: 1.8 grams Calories: 216
2. Pasta, whole wheat      Fat: 1 gram    Calories: 214
3. Pasta, corn             Fat: 1.5 grams Calories: 210
4. Pasta, Quinoa           Fat: 0 grams   Calories: 200
5. Pasta, Soba (buckwheat) Fat: 1.5 grams Calories: 190
Choose the food: 4

Do you want to continue? y/n

if the answer is not:
   The total gram of fat is ... and the calories are ...
   Would you like to start again? y/n
else
    
1. Meats
2. Grains
3. Vegetables
4. Fruit

Choose a category:


NOTES:
– Include friendly and clear messages to the user.
– Include an introduction and goodbye or exit message.

Algorithm: Game – connect four

Classwork/Homework:
(Game: connect four) Connect four is a two-player board game in which the players alternately drop colored disks into a seven-column, six-row vertically suspended grid, as shown below.

connect4

The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before your opponent can do likewise. The program prompts two players to drop a red or yellow disk alternately. In the preceding figure, the red disk is shown in a dark color and the yellow in a light color. Whenever a disk is dropped, the program redisplays the board on the console and determines the status of the game (win, draw, or continue). Here is a sample run:

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
———————————————

Drop a red disk at column (0–6): 0
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | | | | |
———————————————

Drop a yellow disk at column (0–6): 4

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | |Y| | |
.
.
.
.

Drop a yellow disk at column (0–6): 6 

| | | | | | | |
| | | | | | | |
| | | | |Y| | |
| | | |Y|Y|Y|R|
| | |Y|R|R|Y|Y|
|R|Y|R|Y|R|R|R|
———————————————
The yellow player won
Do you want to play again?

Write the two-player program, Connect4_YI.py. Display at every move the board as shown in the example above. Include a prompt to continue playing.

Your program should include:
1. Good documentation
2. An introduction message
3. Functions
4. Main
5. An end of game message
6. Input/output

What is good documentation?
Answer:

  1. Header with author’s name, assignment description, date and python version.
  2. Comments in each function. A short sentence will be sufficient.
  3. Comments for code snippets written for specific handling. An example might be checking if there are 3 in a row, or 4 in a row.
  4. Comments to indicate unusual or rare situations that don’t follow a pattern or repetition.

Advanced: Variable scopes



Python Variable scopes



Fix the problem:

#####################################################################
#  YI_MoreOnScopes3.py
#  Mrs. Elia
#  12/18/14
#  variables outside a definition and in other definitions
#
#####################################################################
#  Definitions
#
#####################################################################

def increase():
    num += 150

def decrease():
    num -= 50

## main
num = 100
print(num)
increase()
print(num)
decrease()
print(num)


## desired output:
## 100
## 250
## 200

Hint:

num = 100
print(num)
...increase(...)
print(num)
...decrease(...)
print(num)

Fix this problem

#####################################################################
#  YI_MoreOnScopes4.py
#  Mrs. Elia
#  12/18/14
#  variables outside a definition and in other definitions
#
#####################################################################
#  Definitions
#
#####################################################################

def two_terms():
    term1 = seed1 + seed2
    term2 = seed2 + term1
    return term1
    return term2


## main

seed1 = 3
seed2 = 5
two_terms()
print(...)

## desired output:
## 8 13

Hint:

## main

seed1 = 3
seed2 = 5
...two_terms(...,...)
print(...,...)

The output should be:
8 13

Algorithm: Tic-Tac-Toe to Battleship

Battleship

The next assignment is to write a python program YI_battleship1.py using the concepts and algorithms learned in Tic-Tac-Toe. In this version of the program you will only limit the board to be 3 x 3 and only 2 ships: one ship has 3 contiguous places and the other ship has 2 contiguous places. The ships could be placed horizontally or vertically. The purpose of this 1st version of the game is for the computer to guess the player’s ships positions. Your program’s algorithm will allow the player to enter the locations for the 2 ships( 2 and 3 places in length).

Classwork:
With a partner, play on paper our version of battleship but for two players.
1. Make sure you follow the rules of the game.
2. Play the game several times with the ships in different locations.
3. Pay attention to the strategy you use to find the ships and to sink them.
4. Categorize the strategies by the specific locations of the ships. (edmodo.com)
5. Write a short paragraph describing the strategy you use. Make sure your description is categorized by the different locations of the ships.(edmodo.com)

NOTE: You can use random to find a ship but once you have a hit, you should not select the next location using random. Develop an intelligent algorithm.

Homework:
Submit your answers to the following posts (edmodo.com)
1. What python feature would you use to hold the information about the ships locations? (e.g. lists, a list of lists, a dictionary, variables or something else)
2. Describe how you would access that information based on your choice in the previous question.
3. Given that a 3-place ship is located at the upper left corner of the board, write the pseudocode to sink it.

Preparing for Battleship

Preparing for the Battleship program

Play Battleship in a 3 by 3 board and only two ships: two and three squares long with a partner:
Here is an example:
Screen Shot 2015-01-13 at 8.34.50 AM

  • Can you group the locations of the ships in categories?
    The ships could be:

    • Vertical or Horizontal
    • In a corner
    • By the edges
    • In the middle

If you found a ship at a location, what would be your next move based on the grouping mentioned above?

With a partner play multiple times in a 3 x 3 board. Then play with this hit:

Screen Shot 2015-01-13 at 8.40.12 AM

Suggested labeling convention: rows by columns

Screen Shot 2015-02-02 at 9.29.56 AM

A code snippet to help you print each location:

>>> listoflists=[['A','B','C'],['D','E','F'],['G','H','I']]
>>> for i in range(len(listoflists)):
    for j in range(len(listoflists[0])):
        print(listoflists[i][j],end=' ')
    print()

    
A B C 
D E F 
G H I 
>>> 

In pseudocode, write the next possible places that you might choose for the Hit above.

Homework:
Write the pseudocode to choose the next move when finding a hit in each of the four corners.
Screen Shot 2015-01-13 at 9.12.33 AM

Algorithm: Battleship Day 4

Continuing to prepare for the Battleship program

Classwork:

1. Write the pseudocode to handle checking if there is a ship on one of the edges. What steps would your program follow?

Suggested Classwork:

2. Write a program, Edges4_YI.py to handle the following scenario:

– a hit is found on one of the edges locations on the 3 x 3 board and based on the user’s response write the code to find the ship and sink it.

The idea at every scenario is to find a pattern so you can minimize the code and reuse it.

– Use a list of three lists with 3 items each.
– Randomly select the edges where the program will place the ship.

Screen Shot 2015-02-02 at 7.32.57 AMScreen Shot 2015-02-02 at 8.06.20 AM

Reminder:

Requirements for an A:
1. Don’t forget the introduction with the rules of the game. Let the player know that the ships can only be placed horizontally or vertically.
2. The program has to be turned in on time.
3. The program must have the pygame component.
4. The program has to display at least one board.
5. The program has to handle two ships: 1 of two places and 1 of three places.
6. The program uses a smart algorithm after it finds the first occupied place.
7. The program’s quality of design
8. The program has to run until the game is over.

What will cause a drop in the grade?
The program is not able to tell if the ships overlap.
The program is not able to recognize invalid input.(Prompt the user for valid input)
The program is not able to detect duplicate entries. (Prompt the user for valid input)
The program has no header, no documentation and no output.
The program is over due.

Algorithm: Prepare for the Battleship

Continuing to prepare for the Battleship program

Classwork:

1. On a piece of paper decide in which edge you will place a 2 or 3-square ship.

2. Write a program, YI_4Edges.py to prompt the user for one of the edges locations on the 3 x 3 board and based on the user’s response write the code to find the ship and sink it.
– Use a list of three lists with 3 items each.
– Randomly select the edges where the program will place the ship.

Screen Shot 2015-02-02 at 7.32.57 AM Screen Shot 2015-02-02 at 8.06.20 AM

Algorithm: Battleship Day 1

Preparing for the Battleship program

Play the game agains the computer here:
(You need a browser that supports the game, Firefox)

With a friend:

Play Battleship with a purpose:

Can you group the locations of the ships in categories?
The ships could be:

  • Vertical or Horizontal
  • In a corner
  • By the edges
  • In the middle

If you found a ship at a location, what would be your next move based on the grouping mentioned above?

If you want to include images, look at the next chapter from Invent with Python

Algorithm: Preparing for the Battleship program Day 3

Preparing for the Battleship program

Classwork:

You can start working on the Battleship pygame program or you can choose to write a few programs to handle individual scenarios. Gradually, you will have the final version of the program.

Battleship development by parts:
Write a program, Corners4_YI.py to handle the following scenario:

– a hit is found on one of t the corners on the 3 x 3 board and based on the user’s response write the code to find the ship and sink it.

The idea at every scenario is to find a pattern so you can minimize the code and reuse it.

Use a list of three lists with 3 items each.
Randomly select the corner where the program will place the ship.

Screen Shot 2015-01-13 at 9.12.33 AM

Application’s Logistics:
Your program should only maintain as a minimum two boards:

1. The computer’s calls of the player’s ships locations.
2. The player’s guesses as either M(issed) or H(it).

Minimum requirements:
Display one board using pygame: either a or b
a. A board with the computer’s guesses with blue if it is a Miss or yellow and a portion of a ship if it is a Hit.
b. A board with the player’s guesses with blue if it is a Miss or yellow and a portion of a ship if it is a hit.

Some suggestions:

>>> listoflists=[['A','B','C'],['D','E','F'],['G','H','I']]
>>> for i in range(len(listoflists)):
        for j in range(len(listoflists[0])):
            print(listoflists[i][j],end=' ')
        print()

    
A B C 
D E F 
G H I 
>>> 

Algorithm: Wheel of Fortune – Description and Design

1. Have the variable secretWord changed to secretPhrase and have a value assigned to it.
2. Prompt the user for a letter and display it in the right positions if it is in the secretPhrase. Otherwise, send a message to the player “incorrect” and keep track of how many times the player guesses the wrong letters.
3. Terminate the game after 5 tries. Display “game over” if it fails. Otherwise, displays “You are a winner!!” and add message with the prize(s)

Write YI_WheelOfFortune.py using what you learned from Hangman.py

1. Have the variable secretWord changed to secretPhrase and have a value assigned to it.
2. Prompt the user for a letter and display it in the right positions if it is in the secretPhrase. Otherwise, send a message to the player “incorrect” and keep track of how many times the player guesses the wrong letters.
3. Terminate the game after 5 tries. Display “game over” if it fails. Otherwise, displays “You are a winner!!” and add message with the prize(s)

Screen Shot 2014-11-16 at 5.52.28 PMScreen Shot 2014-11-16 at 5.53.09 PM

 

Designing the game:

  • Start by thinking to implement the secret phrase .
  • Make it similar to the secret word from the hangman.py program
  • The secret phrase has a phrase instead of a word. You have to think how you are going to handle the spaces. A suggestion from a student, Anna Schmult: replace a space with a “dash”. Shihan YU has a few good ideas about it. You can ask him also how he is handling this component.
  • Have a definition to randomly select a phrase
  • The definition should look very similar to getRandomWord(wordList) from hangaman.py
  • Write a short program to test your definition, and you handle the spaces and how you select randomly the phrase. Name this program YI_WheelOfFortune1.py
  • Next, work on the displayBoard() definition.
  • Don’t worry about the HANGMANPICS. You do not need it.
  • You can use the code for the missedLetters and the slicing to determine where the correct letter goes
  • Test your code works by writing a program YI_WheelOfFortune2.py. You can supply the list of phrases in the definition itself.
  • If you feel ambitious, you can add the code to the YI_WheelOfFortune1.py and return the secretPhrase as an argument to the displayBoard() definition.

 
 
THIS IS A GREAT PROJECT TO DISCUSS WITH YOUR CLASSMATES AND FROM OTHER PYTHON CLASSES!!! “DISCUSS” DOESN’T MEAN COPY THE CODE LINE BY LINE. IT MEANS UNDERSTAND THE STRATEGY AND APPLY IT TO YOUR OWN PROGRAM.

Algorithm: The Wheel of Fortune hangman n the game


Programming Project: The Wheel of Fortune
Write YI_WheelOfFortune.py using what you learned from hangman.py

Due date: November 25th, 2015

Screen Shot 2015-11-20 at 7.46.00 AM —> Screen Shot 2014-11-16 at 5.52.28 PMScreen Shot 2014-11-16 at 5.53.09 PM

For the last few days We have worked on understanding and assimilating Al Sweigart’s hangman.py program by taking the program apart and tracing it with different data to make sure we tested every line of code.

Now we can use the skills we learned to write a similar program to simulate the Wheel of Fortune. You can use the displayboard and getguess functions. You can collaborate with a partner but you should have your own program. No two programs should be alike!

The original game is multiplayer but you will implement it for only one player. Even though the behavior of the game should be reflected in your simulation, there are changes that have to be made to turn it into one player and still be a fun game. You might want to apply a penalty when the “lose a turn” comes up. This implementation of the Wheel of Fortune should handle only a word.

Somethings to keep in mind
Components that can help you through the process:

  1. A list of items on the wheel
  2. Random number for the spin simulation
  3. The “secret word”
  4. The “missed letters”
  5. The “correct letter”
  6. A “place holder” for the prizes

THE GAME

  1. Spin of the wheel: { gain or loss }
  2. If there is a gain, the player can guess a letter: { correct -> keeps the prize, incorrect -> loses the prize }
  3. The player can solve the puzzle before all the letters have been guessed.
  4. The player can buy a vowel if there is money in the “place holder”.
  5. The player gets to keep the prizes if the puzzle is solved.

NOTE: the program should allow the user to play the game after the puzzle was solved.

Algorithm: Hangman Game using what you learned


Hangman Game
More on lists:

What is the output from the next code snippet?

>>> wordIndex = 2
>>> print(wordIndex)
2
>>> print(['biology','chemistry','physics','algebra'][wordIndex])
physics
>>> 

Displaying the Board to the Player

def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
    print(HANGMANPICS[len(missedLetters)])
    print()

    print('Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
    print()

    blanks = '_' * len(secretWord)

    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

    for letter in blanks: # show the secret word with spaces in between each letter
        print(letter, end=' ')
    print()

Open a new window and create a python program, YI_displayBoard.py and copy the following code:

secretWord = 'apple'
blanks = '_' * len(secretWord)
correctLetters = 'l'
blanks

for i in range(len(secretWord)): # replace blanks with correctly guessed letters
    if secretWord[i] in correctLetters:
        blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

for letter in blanks: # show the secret word with spaces in between each letter
    print(letter, end=' ')
print()

Change the correctLetters variable and play with the program until you figure out how it works.
There is a post in edmodo.com for you to submit the file and to explain how the program works.


Homework:
Write YI_WheelOfFortune.py using what you learned from Hangman.py

1. Have the variable secretWord changed to secretPhrase and have a value assigned to it.
2. Prompt the user for a letter and display it in the right positions if it is in the secretPhrase. Otherwise, send a message to the player “incorrect” and keep track of how many times the player guesses the wrong letters.
3. Terminate the game after 5 tries. Display “game over” if it fails. Otherwise, displays “You are a winner!!” and add message with the prize(s)

Dictionaries

Classwork:

Two ways to create a dictionary in python:
1.

grocery1 = {'lettuce': 1.99, 'tomato': 0.49, 'onion': 0.35, 'olives': 0.99}

2.

grocery2 = {}
grocery2['lettuce'] = 1.99
grocery2['tomato'] = 0.49
grocery2['onion'] = 0.35
grocery2['olives'] = 0.99
grocery2
{'olives': 0.99, 'tomato': 0.49, 'onion': 0.35, 'lettuce': 1.99}

Two ways to insert a new key-value pair to the dictionary:
1.

grocery1['lemon'] = 0.78
grocery1
{'olives': 0.99, 'lemon': 0.78, 'tomato': 0.49, 'onion': 0.35, 'lettuce': 1.99}

2.

grocery1.update({'potato':1.10})
grocery1
{'lemon': 0.78, 'onion': 0.35, 'potato': 1.1, 'olives': 0.99, 'tomato': 0.49, 'lettuce': 1.99}

Two ways to create a list of the keys of the dictionary:
1.

keys = grocery1.keys()
keys
dict_keys(['lemon', 'onion', 'potato', 'olives', 'tomato', 'lettuce'])
for key in keys:
print(grocery1[key], end = '-')
0.78-0.35-1.1-0.99-0.49-1.99-

print(keys)
dict_keys(['onion', 'tomato', 'olives', 'lettuce'])
for key in keys:
print(key, end = ' ')
onion tomato olives lettuce

2.

keys_list = list(grocery1.keys())
keys_list
['lemon', 'onion', 'potato', 'olives', 'tomato', 'lettuce']
 

Two ways to create a list of values:
1.

values_list = []
for key in keys:
    values_list += [grocery1[key]]

values_list
[0.78, 0.35, 1.1, 0.99, 0.49, 1.99]
 

2.

val_list = grocery1.values()
val_list
dict_values([0.78, 0.35, 1.1, 0.99, 0.49, 1.99])
 

More to know:

x = 'lemon' in grocery
x
True

y = 'carrot' in grocery
y
False

How to delete a key-value entry pair from a dictionary:

grocery1 = {'lettuce': 1.99, 'tomato': 0.49, 'onion': 0.35, 'olives': 0.99}
del grocery1['lettuce']
grocery1
{'onion': 0.35, 'tomato': 0.49, 'olives': 0.99}

In edmodo.com
Homework:
Answer the following questions in edmodo.com

1. Do lists allow duplicate elements? what about dictionaries?

adict = {'a':1,'b':2,'a':4}
adict
{'a': 4, 'b': 2}

2. What are two ways to insert key–> value pairs into a dictionary.
3. Can different ‘types’ of keys be used in the same dictionary?
4. What happens when you try entering a value for a key that is already in the dictionary?
5. Create a scenario in which you would use a dictionary (without using the grocery example from these slides), and explain why you’d use a dictionary rather than a list.

Gota, you were right. Here is another way to add a key-value pair to a dictionary from stackoverflow.com

x = {1:2}
print x
{1: 2}

x.update({3:4})
print x
{1: 2, 3: 4}

Dictionaries: One more look

Dictionaries in python

Interesting code found in some python Scrabble programs:
scrabble

word = input("Enter a four letter word ")
word = word.upper()
letterNum = {'A':1,'E':1,'D':2,'R':2,'B':3,'M':3,'V':4,'Y':4,'J':8,'X':8}

What does the following line print?

print(letterNum['A'])

How was it used in the scrabble program?
One possible answer:

value = 0
for i in word:
    value += letterNum[i]

print(value)

Another possible answer:

letterValue = [0,0,0,0]
for i in range(4):
    letterValue[i] = letterNum[word[i]]

print(letterValue)

Classwork:
Work in python’s shell and copy and paste your work on edmodo.com’s post: Dictionary – Clwk 1/8 – Basic Concepts

Create a dictionary: ‘hello’ is the key and ‘hola’ is the value

spanishDictionary = {'hello':'hola','goodbye':'adios','one':'uno','two':'dos'}

Access a value with the key

word = input("what word would like to translate to spanish? ")
palabra = spanishDictionary[word]

Add a new key and value:

spanishDictionary.update({'blue':'azul'})
print(len(spanishDictionary))

Delete a key and the value:

del(spanishDictionary['blue'])

Replace the value of a key:

spanishDictionary['goodbye'] = 'chau'

Remove all items:

spanishDictionary.clear()

You can have a different type of value:

numbers = {'one':1,'two':2,'three':3,'four':4,'five':5}


print( numbers['two'] * numbers['three'])

You can have a different type of key and a different type of value:

numbers = {90:0,91:1,92:2,93:3}

print(numbers[92] * numbers[93])

Homework:
Add ten more words to the dictionary. Write a sentence in English and then translate it to Spanish or the language you chose. Add this new code to the original post.

Dictionaries: Students Grades

Classwork:
Write a python program, StudentGrades_YI.py. The program has three dictionaries:
test1 = {‘bob’:88, ‘lisa’:100,…}
test2 = {‘bob’:85, ‘lisa’:95,…}
test3 = {‘bob’:80, ‘lisa’:98,…}

1. Add 5 more students (using the update method) and their grades in the dictionaries.
2. Create a dictionary with the students’ averages from test 1, 2 and 3.
3. Find the student with the highest average.
4. Print all the students names and averages.

Dictionaries: Mad Libs

Classwork: having fun with lists.

Screen Shot 2015-11-02 at 2.13.55 PM

Screen Shot 2015-11-02 at 2.14.33 PM

DIY Mad libs: Write your own mad lib program, YI_MadLibs.py using lists. You might want to have a theme.
Recipe:
1. Create 9 lists for adjectives, adverbs, nouns or plural nouns, verbs, exclamations, numbers, colors, and names. You can prompt the user for name to fill your list of names but all the other lists should already contained the items.

  1. Generate 9 random digits one for each of the lists. The range will depend on the number of items each list has.
  2. Create a sentence with the choice of each list. Make sure you put them in the right order!
  3. Prompt the user whether he or she wants to play again.

NOTE:
Adjectives: describes something (green, squishy, cute)
Adverbs: describes an action (quickly, carefully, silently)
Nouns: person, place or thing (car, house, child)
Plural noun: people, places or things (cars, houses, children)
Verbs: an action (run, jump, swim)
Exclamations: wow!, oh!, yuck!

Something to keep in mind:
Find the words for your lists in such a way that fit “nicely” into your theme sentence.

You can play with this site to get an idea:
Screen Shot 2015-11-02 at 2.07.39 PM

Dictionaries: MySpanishDictionary_YI.py

Dictionaries
Screen Shot 2016-01-06 at 1.34.15 AM

dictionary methods

Assignment:
Write a python program, YI_MySpanishDictionary.py using functions and dictionaries.

    Note: You can use a different language. Name your program according to the language you are using.

  • Hardcode a dictionary’s english word (key) and its spanish translation (value) for several english words (entries in the dictionary)
  • Display a menu for the user to choose:
    1. Translate an english word
    2. Display all english words in the dictionary
    3. Add new english/spanish entries
    4. Delete english/spanish entries.

  • Include an introduction
  • Exit the program properly
  • Do not forget to keep your code well documented
  • Pasting your code on the post is a requirement
  • Attaching your file is also a requirement