Showing posts with label Program. Show all posts
Showing posts with label Program. Show all posts

Sunday, November 3, 2013

Do the Point and Rectangle ever Overlap?

Problem :
Convert the following specification into code. Do the point and rectangle ever overlap?
A point starts at [10, 20]. It repeatedly changes position by [3, 0.7] — e.g., under button or timer control. Meanwhile, a rectangle stays in place. Its corners are at [50, 50] (upper left), [180, 50] (upper right), [180, 140] (lower right), and [50, 140] (lower left).
To check for overlap, i.e., collision, just run your code and check visually. You do not need to implement a point-rectangle collision test. However, we encourage you to think about how you would implement such a test.




CODE :

import simplegui

# initialize state
width = 200
height = 200
position = [10, 20]
radius = 2
velocity = [3,0.7]

# event handlers
def keydown(key):
    if key == simplegui.KEY_MAP['down']:
        position[1] = position[1] - velocity[1]
        position[0] = position[0] - velocity[0]
 

    elif key == simplegui.KEY_MAP['up']:
        position[1] = position[1] + velocity[1]
        position[0] = position[0] + velocity[0]
  
   
def draw(canvas):
    canvas.draw_circle(position, radius, 2, "red", "red")
    canvas.draw_line((50, 50), (50, 140), 2, "White")
    canvas.draw_line((50, 140), (180, 140), 2, "White")
    canvas.draw_line((180, 50), (50, 50), 2, "White")
    canvas.draw_line((180, 140), (180, 50), 2, "White")

# create frame
frame = simplegui.create_frame("Key Handling", width, height)

# register event handlers
frame.set_keydown_handler(keydown)
frame.set_draw_handler(draw)

# start frame
frame.start()



# http://www.codeskulptor.org/#user22_YXZnJWQnbLfSi81.py

Output :


  

Saturday, November 2, 2013

Play with Strings !

STRINGS

LOVE IT !! Besides numbers, Python can also manipulate strings, which can be expressed in several ways.


#! python works with strings
# Used 1 to 24 in printing to see the results in console.

# Strings can be concatenated (glued together) with the + operator, and repeated with *: 

word = 'Help' + 'A'
print 1,word

print 2,'<' + word*5 + '>'

# Two string literals next to each other are automatically concatenated; 
# the first line above could also have been written "word = 'Help' 'A'"; 
# this only works with two literals, not with arbitrary string expressions: 

st='str' 'ing'             #  <-  This is ok
print 3, st
st='str'.strip() + 'ing'   #  <-  This is ok
print 4, st

# Strings can be subscripted (indexed); like in C, the first character of a string 
# has subscript (index) 0. There is no separate character type; a character is 
# simply a string of size one. Like in Icon, substrings can be specified with 
# the slice notation: two indices separated by a colon. 

print 5, word[4]

print 6, word[0:2]

print 7, word[2:4]

# Slice indices have useful defaults; an omitted first index defaults to zero, 
# an omitted second index defaults to the size of the string being sliced. 

print 8, word[:2]    # The first two characters
print 9, word[2:]    # All but the first two characters

# Python strings cannot be changed. Assigning to an indexed position in the string results in an error: 
# However, creating a new string with the combined content is easy and efficient: 

print 10, 'x' + word[1:]

print 11, 'Splat' + word[4]

# Here's a useful invariant of slice operations: s[:i] + s[i:] equals s. 

print 12, word[:2] + word[2:]

print 13, word[:3] + word[3:]


# Degenerate slice indices are handled gracefully: an index that is too large is replaced 
# by the string size, an upper bound smaller than the lower bound returns an empty string. 

print 14, word[1:100]

print 15, word[10:]

print 16, word[2:1]


# Indices may be negative numbers, to start counting from the right. For example: 


print 17, word[-1]     # The last character

print 18, word[-2]     # The last-but-one character

print 19, word[-2:]    # The last two characters

print 20, word[:-2]    # All but the last two characters


# But note that -0 is really the same as 0, so it does not count from the right! 

print 21, word[-0]     # (since -0 equals 0)

# Out-of-range negative slice indices are truncated, but don't try this for single-element (non-slice) indices: 

print 22, word[-100:]

# print word[-10]    # error

#The best way to remember how slices work is to think of the indices as pointing between characters, 
#with the left edge of the first character numbered 0. Then the right edge of the last character 
#of a string of n characters has index n, for example: 

# +---+---+---+---+---+ 
# | H | e | l | p | A |
# +---+---+---+---+---+ 
# 0   1   2   3   4   5 
#-5  -4  -3  -2  -1


s = 'supercalifragilisticexpialidocious'
print 23, s
print 24, 'length of above string is : ', len(s)

http://www.codeskulptor.org/#user22_0UcuKWvNvVDJS7H.py

Output :


1 HelpA
2 <HelpAHelpAHelpAHelpAHelpA>
3 string
4 string
5 A
6 He
7 lp
8 He
9 lpA
10 xelpA
11 SplatA
12 HelpA
13 HelpA
14 elpA
15 
16 
17 A
18 p
19 pA
20 Hel
21 H
22 HelpA
23 supercalifragilisticexpialidocious
24 length of above string is :  34

Thursday, October 31, 2013

The Collatz conjecture or the 3n + 1 conjecture

Given any initial natural number, consider the sequence of numbers generated by repeatedly following the rule:


  • divide by two if the number is even or
  • multiply by 3 and add 1 if the number is odd.

The Collatz conjecture states that this sequence always terminates at 1. For example, the sequence generated by 23 is:

23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1

Write a Python program that takes a global variable n and print out the sequence of numbers generated by this rule. Run this program for n = 217. What is the largest number in the sequence generated by this starting value?

To test your code, starting at n = 23 generates a sequence with a maximum value of 160.

Note: The Collatz conjecture is a conjecture in mathematics named after Lothar Collatz, who first proposed it in 1937. The conjecture is also known as the 3n + 1 conjecture. For more detail : http://en.wikipedia.org/wiki/Collatz_conjecture


n=int(raw_input("Enter the beginning number: "))
i=0
print n
while n > 1:
 if n%2 == 0: # if n is even
  n = n/2
  print n
 else:
  n = 3*n+1
  print n
 i += 1;

http://www.codeskulptor.org/#user22_Afr8cR8fTfGHWtJ.py

Sunday, October 27, 2013

My First Automobile in Python

#Turn the following description into a CodeSkulptor program, and run it.

#Create a 300-by-300 canvas.
#Draw two circles with radius 20 and white lines of width 10. One is centered at (90,200) and one at (210,200).
#Draw a red line of width 40 from (50,180) to (250,180).
#Draw two red lines of width 5 from (55,170) to (90,120) and from (90,120) to (130,120).
#Draw a red line of width 140 from (180,108) to (180,160).
#The resulting picture is a simple diagram of what?


import simplegui

# define draw handler
def draw(canvas):
 #Draw two circles with radius 20 and white lines of width 10. One is centered at (90,200) and one at (210,200).
    canvas.draw_circle([90, 200], 20, 10, "White")
    canvas.draw_circle([210, 200], 20, 10, "White")

 #Draw a red line of width 40 from (50,180) to (250,180). 
    canvas.draw_line((50, 180), (250, 180), 10, "Red")

 #Draw two red lines of width 5 from (55,170) to (90,120) and from (90,120) to (130,120).
    canvas.draw_line((55, 170), (90, 120), 5, "Red")
    canvas.draw_line((90, 120), (130, 120), 5, "Red")

 #Draw a red line of width 140 from (180,108) to (180,160).
    canvas.draw_line((180, 108), (180, 160), 140, "Red")

# create frame
frame = simplegui.create_frame("My First Automobile", 300, 300)

# register draw handler    
frame.set_draw_handler(draw)

# start frame
frame.start()

http://www.codeskulptor.org/#user21_WXAhADbLxljqk7c.py

 Output :

Calculate the Occurance of a Character in a given String!

# Calculate the number of 1 and L in the string given


s="1lll1l1l1l1ll1l111ll1l1ll1l1ll1ll111ll1ll1ll1l1ll1ll1ll1ll1lll1l1l1l1l1l1l1l1l1l1l1l1ll1lll1l111ll1l1l1l1l1l1"

print "Length of String given is : ", len(s)
x,y=0,0
for n in range (0,len(s)):

    if s[n]=='l':
        x=x+1
    else:
        y=y+1
print "Number of times L appeared in the given string is : ", x
print "Number of times 1 appear in the given string is : ", y

http://www.codeskulptor.org/#user21_ViL6RA4QrSkUWtF.py

==============
Console Output :


Length of String given is :  109
Number of times L appeared in the given string is :  61
Number of times 1 appear in the given string is :  48

#Another way to do this is by a simple command :
import simplegui
string="1lll1l1l1l1ll1l111ll1l1ll1l1ll1ll111ll1ll1ll1l1ll1ll1ll1ll1lll1l1l1l1l1l1l1l1l1l1l1l1ll1lll1l111ll1l1l1l1l1l1"
x= string.count("l")
y= string.count("1")

print "Length of String given is : ", len(string)
print "Number of times L appeared in the given string is : ", x

print "Number of times 1 appear in the given string is : ", y

http://www.codeskulptor.org/#user21_nK7oJgwPOe1IJUR.py

==============
Console Output Remains the same :

Length of String given is :  109
Number of times L appeared in the given string is :  61
Number of times 1 appear in the given string is :  48

Friday, October 25, 2013

Comparison of Two Number by taking input from User!


# Compare two number by taking input from User 

# Program explains How to take input from user and usage of 'if'operator


x = int(raw_input("Enter First number: "))

y = int(raw_input("Enter Second number: "))


if x > y:

     print 'First number is greater then second'

elif x < y :

      print 'Second number is greater then first'

else:

      print 'Both the Numbers are equal'

http://www.codeskulptor.org/#user21_bb6vkgWmQuyNwka.py

Fibonacci series


# Fibonacci series:
# the sum of two elements defines the next
b, c = 0, 1
while c < 200:
       print c,
       b, c = c, b+c

Console Output :
1 1 2 3 5 8 13 21 34 55 89 144

Mini-Project 2 : “Guess the number” Game

Mini-project description — “Guess the number” game

One of the simplest two-player games is “Guess the number”. The first player thinks of a secret number in some known range while the second player attempts to guess the number. After each guess, the first player answers either “Higher”, “Lower” or “Correct!” depending on whether the secret number is higher, lower or equal to the guess. In this project, you will build a simple interactive program in Python where the computer will take the role of the first player while you play as the second player.
You will interact with your program using an input field and several buttons. For this project, we will ignore the canvas and print the computer's responses in the console. Building an initial version of your project that prints information in the console is a development strategy that you should use in later projects as well. Focusing on getting the logic of the program correct before trying to make it display the information in some “nice” way on the canvas usually saves lots of time since debugging logic errors in graphical output can be tricky.

suggested development strategy for the basic version of “Guess the number” is:
  1. Decide on a set of global variables that contain the state of the game. For example, one obvious choice is the secret number that has been generated by the program. You will need other global variables, especially to accommodate later extensions to the basic game.
  2. Figure out how to generate a random secret number in a given range, low to high. When discussing ranges, we will follow the standard Python convention of including the low end of the range and excluding the high end of the range, which can be expressed mathematically as [low, high). So, [0, 3) means all of the numbers starting at 0 up to, but not including 3. In other words 0, 1, and 2. We suggest using the range [0, 100) in your first implementation. Hint: look at the functions in the random module to figure out how to easily select such a random number. We suggest testing this in a separate CodeSkulptor tab before adding code to your project.
  3. Figure out how to create an input text box using the simplegui module. You will use this input to get the guess from the user. For all variants of the game, this input field should always be active (in other words, a game should always be in progress). Again, test in a separate CodeSkulptor tab before adding code to your project. Again, we suggest testing separate CodeSkulptor tab before adding code to your project.
  4. Write the event handler input_guess(guess) that takes the input guess, compares it to the secret number and prints out the appropriate response. Remember that guess is a string so you will need to convert it into a number before testing it against the secret number. Hint: We have showed you how to convert strings to numbers in the lectures.
  5. Test your code by playing multiple games of “Guess the number” with a fixed range. At this point, you will need to re-run your program between each game (using the CodeSkulptor “Run” button).
  6. Fill in your new_game() function so the generation of the secret number is now done inside this function. That is, calling new_game() should compute a random secret number and assign it to a global variable. You can now call the function new_game() in the body of your code right before you start your frame.
From this minimal working version of “Guess the number”, the rest of this project consists of adding extra functionality to your project. There are two improvements that you will need to make to get full credit:
  1. Using function(s) in the simplegui module, add buttons to restart the game so that you don't need to repeatedly click “Run” in CodeSkulptor to play multiple games. You should add two buttons: “Range: 0 - 100” and “Range: 0 - 1000” that allow the player to choose different ranges for the secret number. Using either of these buttons should restart the game and print out an appropriate message. They should work at any time during the game. In our implementation, the event handler for each button set the desired range for the secret number (as a global variable) and then called new_game to reset the secret number in the desired range.
    As you play “Guess the number”, you might notice that a good strategy is to maintain an interval that consists of the highest guess that is “Lower” than the secret number and the lowest guess that is “Higher” than the secret number. A good choice for the next guess is the number that is the average of these two numbers. The answer for this new guess then allows you to figure a new interval that contains the secret number and that is half as large. For example, if the secret number is in the range [0, 100), it is a good idea to guess 50. If the answer is "Higher", the secret number must be in the range [51, 100). It is then a good idea to guess 75 and so on. This technique of successively narrowing the range corresponds to a well-known computer algorithm known as binary search.
  2. Your final addition to “Guess the number” will be to restrict the player to a limited number of guesses. After each guess, your program should include in its output the number of remaining guesses. Once the player has used up those guesses, they lose, the game prints out an appropriate message, and a new game immediately starts.
    Since the strategy above for playing “Guess the number” approximately halves the range of possible secret numbers after each guess, any secret number in the range [low, high) can always be found in at most n guesses where n is the smallest integer such that 2 ** n >= high - low + 1. For the range [0, 100)n is seven. For the range [0, 1000)n is ten. In our implementation, the function new_game() set the number of allowed guess to seven when the range is [0, 100) or to ten when the range is [0, 1000). For more of a challenge, you may compute n fromlow and high using the functions math.log and math.ceil in the math module.
When your program starts, the game should immediately begin in range [0, 100). When the game ends (because the player either wins or runs out of guesses), a new game with the same range as the last one should immediately begin by calling new_game(). Whenever the player clicks one of the range buttons, the current game should stop and a new game with the selected range should begin.

Grading rubric — 11 pts total (scaled to 100 pts)

Your peers will assess your mini-project according to the rubric given below. To guide you in determining whether your project satisfies each item in the rubric, please consult the video that demonstrates our implementation of “Guess the number”. Small deviations from the textual output of our implementation are fine. You should avoid potentially confusing deviations (such as printing “Too high” or “Too low” instead of “Lower” and “Higher”). Whether moderate deviations satisfy an item of the grading rubric is at your peers' discretion during their assessment.
Here is a break down of the scoring:
  • 1 pt — The game starts immediately when the “Run” button in CodeSkulptor is pressed.
  • 1 pt — A game is always in progress. Finishing one game immediately starts another in the same range.
  • 1 pt — The game reads guess from the input field and correctly prints it out.
  • 3 pts — The game correctly plays “Guess the number” with the range [0, 100) and prints understandable output messages to the console. Play three complete games: 1 pt for each correct game.
  • 2 pts — The game includes two buttons that allow the user to select the range [0, 100) or the range [0, 1000) for the secret number. These buttons correctly change the range and print an appropriate message. (1 pt per button.)
  • 2 pts — The game restricts the player to a finite number of guesses and correctly terminates the game when these guesses are exhausted. Award 1 pt if the number of remaining guesses is printed, but the game does not terminate correctly.
  • 1 pt — The game varies the number of allowed guesses based on the range of the secret number — seven guesses for range [0, 100), ten guesses for range [0, 1000).
To help aid you in gauging what a full credit project might look like, the video lecture on the “Guess the number” project includes a demonstration of our implementation of this project. You do not need to validate that the input number is in the correct range. (For this game, that responsibility should fall on the player.)
=================================================================================

Code :
# Mini Project "Guess the number" 
import random
import math
import simplegui

# initialize global variables used in your code
limit = 100
secret_number = random.randrange(0, 100)
max_guess =math.ceil(math.log(limit+1,2))

# define event handlers for control panel
    
def range100():
    global secret_number, max_guess, limit
    secret_number = random.randrange(0, 100)  
    max_guess = math.ceil(math.log(limit+1,2))
    print "Let's try a new secret number, ranging from 0 to 100!"
    print "You have", int(max_guess),"guesses remaining.\n"
    # button that changes range to range [0,100) and restarts

def range1000():
    global secret_number, max_guess, limit
    secret_number = random.randrange(0, 1000)
    limit=1000
    max_guess = math.ceil(math.log(limit+1,2))
    print "Let's try a new secret number, ranging from 0 to 1000!"
    print "You have", int(max_guess),"guesses remaining.\n"
    # button that changes range to range [0,1000) and restarts

def get_input(guess):
    # main game logic goes here
    global max_guess, limit,secret_number
    max_guess -= 1 
    if int(max_guess) > 0 :
        if int(guess) == secret_number and limit==100:
            print guess, "is correct. You won congratulation! \n "
            max_guess = math.ceil(math.log(limit+1,2))
            secret_number = random.randint(0,limit)
            range100()
     
        elif int(guess) == secret_number and limit==1000:
            print guess, "is correct. You won congratulation! \n"
            max_guess = math.ceil(math.log(limit+1,2))
            secret_number = random.randint(0,limit)
            range1000()
    
        elif int(guess) > secret_number:
            print "Guess is " + guess + ". Try Lower."
            print "You have", int(max_guess),"guesses remaining."
        else:
            print "Guess is " + guess +". Try Higher."
            print "You have", int(max_guess),"guesses remaining."
    
    else:
        
        if int(guess) == secret_number :
            if limit==100:
                print guess, "is correct. You won congratulation! \n "
                max_guess = math.ceil(math.log(limit+1,2))
                secret_number = random.randint(0,limit)
                range100()
     
            else:
                print guess, "is correct. You won congratulation! \n"
                max_guess = math.ceil(math.log(limit+1,2))
                secret_number = random.randint(0,limit)
                range1000()
           
        else:
            if limit==1000:
                print "You Lose. The Secret Number was ", secret_number, " \n"
                max_guess = math.ceil(math.log(limit+1,2))
                secret_number = random.randint(0,limit)
                range1000()
            
            else :
                print "You Lose. The Secret Number was ", secret_number," \n"
                max_guess = math.ceil(math.log(limit+1,2))
                secret_number = random.randint(0,limit)
                range100()
    
# create frame
frame = simplegui.create_frame("Guess The Number", 200, 200)

# register event handlers for control elements
game_100 = frame.add_button("Range: 0 - 100", range100)
game_1000 = frame.add_button("Range: 0 - 1000", range1000)
inpt = frame.add_input("Enter guess", get_input, 100)

# start frame
frame.start()

Mini-Project 1 : Rock-paper-scissors-lizard-Spock

Mini-project description — Rock-paper-scissors-lizard-Spock

Rock-paper-scissors is a hand game that is played by two people. The players count to three in unison and simultaneously &ldqup;throw” one of three hand signals that correspond to rock, paper or scissors. The winner is determined by the rules:
  • Rock smashes scissors
  • Scissors cuts paper
  • Paper covers rock
Rock-paper-scissors is a surprisingly popular game that many people play seriously (see the Wikipedia article for details). Due to the fact that a tie happens around 1/3 of the time, several variants of Rock-Paper-Scissors exist that include more choices to make ties more unlikely.
Rock-paper-scissors-lizard-Spock (RPSLS) is a variant of Rock-paper-scissors that allows five choices. Each choice wins against two other choices, loses against two other choices and ties against itself. Much of RPSLS's popularity is that it has been featured in 3 episodes of the TV series "The Big Bang Theory". The Wikipedia entry for RPSLS gives the complete description of the details of the game.
In our first mini-project, we will build a Python function rpsls(name) that takes as input the string name, which is one of "rock""paper","scissors""lizard", or "Spock". The function then simulates playing a round of Rock-paper-scissors-lizard-Spock by generating its own random choice from these alternatives and then determining the winner using a simple rule that we will next describe.
While Rock-paper-scissor-lizard-Spock has a set of ten rules that logically determine who wins a round of RPSLS, coding up these rules would require a large number (5x5=25) of if/elif/else clauses in your mini-project code. A simpler method for determining the winner is to assign each of the five choices a number:
  • 0 — rock
  • 1 — Spock
  • 2 — paper
  • 3 — lizard
  • 4 — scissors
In this expanded list, each choice wins against the preceding two choices and loses against the following two choices. In all of the mini-projects for this class, I will provide a walk through of the steps involved in building your project to aid its development. A template for your mini-project is available here. Please work from this template.

Mini-project development process

  1. Build a helper function name_to_number(name) that converts the string name into a number between 0 and 4 as described above. This function should use a sequence of if/elif/else clauses. You can use conditions of the form name == 'paper', etc. to distinguish the cases.To make debugging your code easier, we suggest including a final else clause that catches cases when name does not match any of the five correct input strings and prints an appropriate error message.
  2. Next, you should build a second helper function number_to_name(num) that converts a number in the range 0 to 4 into its corresponding name as a string. Again, we suggest including a final else clause that catches cases when number is not in the correct range.
  3. Build the first part of the main function rpsls(name) that converts name into the number player_number between 0 and 4 using the helper function name_to_number.
  4. Build the second part of rpsls(name) that generates a random number comp_number between 0 and 4 using the function random.randrange(). I suggest experimenting with randrange in a separate CodeSkulptor window before deciding on how to call it to make sure that you do not accidently generate numbers in the wrong range.
  5. Build the last part of rpsls(name) that determines and prints out the winner. This test is actually very simple if you use the remainder operation (% in Python) to the difference between comp_number and player_number. If this is not immediately obvious to you, I would suggest reviewing the "More operations"  and "RPSLS" videos on remainders and modular arithmetic as well as experimenting with the remainder operator % in a separate CodeSkulptor window to understand its behavior.
  6. Using the helper function number_to_name, you should produce four print statements; print a blank line, print out the player's choice, print out the computer's choice and print out the winner.
This will be the only mini-project in the class that is not an interactive game. Since we have not yet learned enough to allow you to play the game interactively, you will simply call your rpsls function repeatedly in the program with different player choices. You will see that we have provided five such calls at the bottom of the template. Running your program repeatedly should generate different computer guesses and different winners each time. While you are testing, feel free to modify those calls, but make sure they are restored when you hand in your mini-project, as your peer assessors will expect them to be there.
The output of running your program should have the following form:
Player chooses rock
Computer chooses scissors
Player wins!

Player chooses Spock
Computer chooses lizard
Computer wins!

Player chooses paper
Computer chooses lizard
Computer wins!

Player chooses lizard
Computer chooses scissors
Computer wins!

Player chooses scissors
Computer chooses Spock
Computer wins!
Note that, for this initial mini-project, we will focus only on testing whether your implementation of rpsls() works correctly on valid input.
==============================================================================
Code :
#Mini-Project 1  : Rock-paper-scissors-lizard-Spock
"""
For Details and description: http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock
"""
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors

import random

def number_to_name(number):
    # convert number to a name 
    if number == 0:
        return "rock"
    elif number == 1:
        return "Spock"
    elif number == 2:
        return "paper"
    elif number == 3:
        return "lizard"
    else:
        return "scissors"
  
def name_to_number(name): 
    # convert name to number
    if name == "rock":
        return 0
    elif name == "Spock":
        return 1
    elif name == "paper":
        return 2
    elif name == "lizard":
        return 3
    else:
        return 4
    
def rpsls(name): 
    # convert name to player_number using name_to_number
    player_number = name_to_number(name)

    # compute random guess for comp_number using random.randrange()
    comp_number = random.randrange(0,5)
    
    # compute difference of player_number and comp_number modulo five
    difference = (player_number - comp_number) % 5
    # convert comp_number to name using number_to_name
    comp_name = number_to_name(comp_number)
    # print results
    print "Player chooses", name
    print "Computer chooses", comp_name
    if difference == 1 or difference == 2:
        print "Player wins!"
    elif difference == 3 or difference == 4:
        print "Computer wins!"
    else:
        print "Player and Computer tie!"
    print ""
# test your code
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")