Another beautiful day in this miserable world

Archive for the ‘programming’ Category

Python Programming: An Introduction to Computer Science by Zelle Chap 3 Ex 6

6. Two points in a plane are specified using the coordinates (x1,y1) and (x2,y2). Write a program that calculates the slope of a line through two (non-vertical) points entered by the user.

def main():
    pt1x, pt1y = eval(input("Input the first point seperated by a comma "))
    pt2x, pt2y = eval(input("Input the second point seperated by a comma "))
    sloy = pt2y - pt1y
    slox = pt2x - pt1x
    print("The slope is",sloy,"/",slox)
main()

Python Programming: An Introduction to Computer Science by Zelle Chap 3 Ex 5

5. The Konditorie coffee shop sells coffee at $10.50 a pound plus the cost of shipping. Each order ships for $0.86 per pound + $1.50 fixed cost for overhead. Write a program that calculates the cost of an order.

def main():
    cof = 10.50
    ship = 0.86
    ovh = 1.50
    pds = eval(input("How many pounds of coffee? "))
    ans = ovh + (cof*pds) + (ship*pds)
    print("The cost of your order would equal $",ans)
main()

Python Programming: An Introduction to Computer Science by Zelle Chap 3 Ex 4

My math may be off on this subject. If you see a problem, let me know, I’ll be happy to fix it!

4. Write a program that determines the distance to a lightening strike based on the time elapsed between the flash and the sound of thunder. The speed of sound is approximately 1100 ft/sec and 1 mile is 5280 ft.

#Find how much time has elapsed
#Input formulas
#Convert to miles

def main():
    time = eval(input("What is the time (in seconds) elapsed between the flash and thunder? "))
    sound = 1100*time
    ans = sound/5280
    print("The distance to a lightening strike is ", ans , "miles")
main()

Python Programming: An Introduction to Computer Science by Zelle Chap 3 Ex 3

3. Write a program that determines the molevular weight of a hydrocarbon based on the number of hydrogen, carbon, and oxygen atoms. You should use the following weights H = 1.0079 grams/mole C = 12.011 grams/mole O = 15.9994 grams/mole

(Bare with me here, I am a Comp Sci major not a Chem major :P)
#We must define the weight of a single gram/mole before we start our calulation
#Find out how many of each molecule is in the hydrocarbon
#Add together the weight times the amount of molecules and add them together


def main():
    print("This program determines the molecular weight of a hydrocarbon.")
    h = 1.0079
    c = 12.011
    o = 15.9994
    hnum = eval(input("How many hydrogen atoms are there? "))
    cnum = eval(input("How many carbon atoms are there? "))
    onum = eval(input("How many oxygen atoms are there? "))
    ans = (h*hnum) + (c*cnum) + (o*onum)
    print("The molecular weight of the hydrocarbon is ", ans)
main()

Python Programming: An Introduction to Computer Science by Zelle Chap 3 Ex 2

2. Write a program that calculates the cost per square inch of a circular pizza given it’s diameter and height. The formula for area is A = pir^2

#We must import the math module to incorporate the “pi” function
#Ask for both the diameter and price of the pizza
#The formula uses the radius, so we will have to divide the diameter in half to get the radius
#Using the formula given to us, we can put it in python terms
#To find the cost per square inch, we divide the area by the price

from math import * 
def main():
    diam = eval(input('What is the diameter of the whole pizza? '))
    price = eval(input("What is the price of the pizza? "))
    rad = diam/2
    area = 4*pi*rad**2
    ans = area/price
    print("The cost per square inch is ", ans)
main()

Python Programming: An Introduction to Computer Science by Zelle Chap 3 Ex 1

1. Write a program to calculate the volume and surface area of a sphere from it’s radius, given it’s input.


#V = 4/3pir^3
#A = 4pir^2
#We must import the math module in order to obtain the "pi" function
#Using the formulas given, we place the formula's in python form

from math import *
def main():
    rad = eval(input('What is the radius of the sphere? '))
    vol = ((4*pi*rad**3)/3)
    area = (4*pi*rad**2)

    print('The volume of the sphere is', vol, ' The area is', area)
main()

Dancing Man – Rick Roll

This was the very first “long” program that I wrote. It incorporates math modules, random modules, a graphics module (a tkinter spin off provided by Zelle) and functions. This was a little bit of extra credit I did during the semester. I am sure that there are plenty of short cuts that I could have used and some of my code may be obsolete, but considering it’s my very first complicated program, I figure its all good. I also wanted to show it off to people that would understand the fundamentals behind it. To a normal person, it’s just a dancing stick figure. To me, it’s 3 long nights of straight work and 5 pages worth of code. I submitted it with the Rick Ashley song in the background for fun effect. Enjoy!

Click here for The final Product with the Rick Roll song

from graphics import *
from time import *
from random import *


def drawMan(center, size, moverr, moverl, moverLL, moverRL, window):
    bodyLength = size * 3
    topllx = 225
    botllx = 190
    toplrx = 275
    botlrx = 310
    topy = 435
    boty = 470
    end = Point(center.getX(), center.getY() + bodyLength)
    leftLTop = Line(end, Point(topllx + moverLL ,topy + moverLL))
    llbpt = leftLTop.getP2()
    llbptx = llbpt.getX()
    llbpty = llbpt.getY()
    leftLBot = Line(Point(llbptx,llbpty), Point(botllx + moverLL * 3 ,boty + moverLL * 3))
    rightLTop = Line(end, Point(toplrx + moverRL,topy + moverRL))
    rlbpt = rightLTop.getP2()
    rlbptx = rlbpt.getX()
    rlbpty = rlbpt.getY()
    rightLBot = Line(Point(rlbptx,rlbpty), Point(botlrx + moverRL * 3,boty + moverRL * 3))



    toplx = 220
    consty = 325
    botlx = 190
    toprx = 280
    botrx = 310
    mid = Point((center.getX()+center.getX())//2, (center.getY() + (center.getY()+bodyLength))//2)
    leftTop = Line(mid, Point(toplx, consty))
    
    lbpt = leftTop.getP2()
    lbptx = lbpt.getX()
    lbpty = lbpt.getY()
    leftBot = Line(Point(lbptx,lbpty), Point(botlx + moverl * 2,consty + moverl * 2))
    varleft = leftBot.getP1()

    rightTop = Line(mid, Point(toprx + moverr,consty + moverr))
    rbpt = rightTop.getP2()
    rbptx = rbpt.getX()
    rbpty = rbpt.getY()
    rightBot = Line(Point(rbptx,rbpty), Point(botrx + moverr * 2,consty + moverr * 2))


    eyeSize = 0.15 * size
    eyeOff = size / 3.0
    mouthSize = 0.8 * size
    mouthOff = size / 2.0
    head = Circle(center, size)
    head.setFill("yellow")
    leftEye = Circle(center, eyeSize)
    leftEye.move(-eyeOff, -eyeOff)
    rightEye = Circle(center, eyeSize)
    rightEye.move(eyeOff, -eyeOff)
    p1 = center.clone()
    mouth = Circle(p1, size/1.5)
    p2 = center.clone()
    p2.move(0,-10)
    mouth1 = Circle(p2, size/1.4)
    mouth1.setFill('yellow')
    mouth1.setOutline('yellow')
    bodyM = Line(Point(center.getX(),center.getY()), (Point(center.getX(), center.getY()+bodyLength)))
    bodyM.draw(window)
    head.draw(window)
    mouth.draw(window)
    mouth1.draw(window)
    leftEye.draw(window)
    rightEye.draw(window)
    leftTop.draw(window)
    leftBot.draw(window)
    rightTop.draw(window)
    rightBot.draw(window)
    leftLTop.draw(window)
    leftLBot.draw(window)
    rightLTop.draw(window)
    rightLBot.draw(window)
    sleep(0.2)
    leftLTop.undraw()
    leftLBot.undraw()
    rightLTop.undraw()
    rightLBot.undraw()
    leftTop.undraw()
    leftBot.undraw()
    rightTop.undraw()
    rightBot.undraw()
    head.undraw()
    bodyM.undraw()
    leftEye.undraw()
    rightEye.undraw()
    mouth.undraw()
    mouth1.undraw()


def disco(window):
    filler = ['white', 'black', 'blue', 'purple', 'yellow', 'pink', 'green']
    rand = randint(0,6)
    setFi = filler[rand]
    disco = Circle(Point(100,75), 50)
    disco1 = disco.clone()
    disco1.move(150,0)
    disco1.setFill(setFi)
    disco1.setOutline(setFi)
    disco2 = disco1.clone()
    disco2.move(150,0)
    disco2.setFill(setFi)
    disco2.setOutline(setFi)
    disco2.draw(window)
    disco1.draw(window)
    disco.draw(window)
    disco.setFill(setFi)
    disco.setOutline(setFi)

    


def intervals():
    rand = randint(0,5)
    rand1 = randint(0,1)
    nega = [1,-1]
    mover = rand * nega[rand1]
    return mover
def faceMove():
    rand = randint(0,5)
    rand1 = randint(0,1)
    nega = [1,-1]
    mover = rand * nega[rand1]
    return mover


def main():
    win = GraphWin("", 500, 500)
    bg1 = Rectangle(Point (0,0), Point(500, 500))
    bg1.setFill('red')
    bg1.draw(win)
    center = Point(250, 250)
    size = 50
    moverl = 0
    moverr = 0
    moverRL = 0
    moverLL = 0
    amoverl = 0
    amoverr = 0
    amoverRL = 0
    amoverLL = 0
    disco(win)

    
    while win.checkMouse() == None:
        center = Point(center.getX() + faceMove(), center.getY() + faceMove())
        cgx = center.getX()
        cgy = center.getY()
        amoverl = amoverl + moverl
        amoverr = amoverr + moverr
        amoverRL = amoverRL + moverRL
        amoverLL = amoverLL + moverLL
        drawMan(center,size, moverr, moverl, moverLL, moverRL, win)
        moverl = intervals()
        moverr = intervals()
        moverRL = intervals()
        moverLL = intervals()

        if amoverl > 20:
            moverl = moverl * -1

        if amoverRL > 20:
            moverRL = moverRL * -1

        if amoverl < -20:
            moverl = moverl * -1

        if amoverRL  20:
            moverr = moverr * -1

        if amoverLL > 20:
            moverLL = moverLL * -1
            

        if amoverr < -20:
            moverr = moverr * -1
            

        if amoverLL < -20:
            moverLL = moverLL * -1
            

        if cgy  260:
            center = Point(250,250)
            disco(win)
        if cgx < 240:
            center = Point(250,250)
            disco(win)

    win.getMouse()
    win.close()

main()

Click here for The final Product with the Rick Roll song

Simple ASCII encoder and decoder using Python

I’m skipping a little bit ahead in the chapters because I think this is pretty cool.

Ever want to send hidden messages to somebody, but don’t know how? Here’s a simple ASCII encoder and decoder for you. You can modify this any way you want, but sure that you change both the encoder and the decoder.

A basic rundown of the program is such:
The program takes the letters of whatever message you are encoding and turns it into the ASCII equivalent. You can find the complete table here ASCII Table . The encoded message you get out of it will just be numbers. Whoever you send the numbers to puts the message into the decoder and that turns the numbers back into letters! Awesome right? Simple, easy, and most normal people don’t know it.

If you want to modify it to be a little bit harder for somebody to catch onto, you could take the numbers that you’re encoding and add 2 or multiply by 7. Remember in the encoder you would have to do the opposite to make the message come out right. Be careful dividing in the encoder, the numbers might not come out right. If you wanted to be really sneaky, You could even do the mod of the number and then find out the numbers equivalent to the mod and have the decode print out what the different messages could be based on the mod. That actually sounds like fun, I might try that sometime 🙂

Remember, my indents are not correct do to the layout of the page. It should look like what’s in the pictures.

Encoder:

def main():
    mess = input("Message: ")

    for ch in mess:
        print(ord(ch), end = " ")
    print()

main()

Decoder:

def main():

    for i in range(10000):
        inString = input("Code: ")

        chars = []
        for numStr in inString.split():
            codeNum = eval(numStr)
            chars.append(chr(codeNum))

        message = "".join(chars)

        print(message)

main()


Here’s a little bit of extra information. Run it through your decoder to find out what it says 🙂

84 104 105 115 32 105 115 32 97 32 118 101 114 121 32 115 105 109 112 108 105 115 116 105 99 32 119 97 121 32 116 111 32 108 101 97 114 110 32 104 111 119 32 110 101 116 119 111 114 107 115 32 97 114 101 32 101 110 99 111 100 101 100 32 97 110 100 32 100 101 99 111 100 101 100 46 32 73 110 32 98 105 103 32 110 101 116 119 111 114 107 115 44 32 116 104 101 114 101 32 105 115 32 117 115 117 97 108 108 121 32 115 111 109 101 32 116 121 112 101 32 111 102 32 97 108 103 111 114 105 116 104 109 32 116 104 97 116 32 100 101 102 105 110 101 115 32 119 104 97 116 32 105 115 32 101 110 99 114 121 112 116 101 100 46 32 84 104 105 115 32 105 115 32 104 111 119 32 99 111 109 112 97 110 105 101 115 32 99 97 110 32 114 101 99 101 105 118 101 32 121 111 117 114 32 99 114 101 100 105 116 32 99 97 114 100 32 110 117 109 98 101 114 32 119 105 116 104 111 117 116 32 105 116 32 98 101 105 110 103 32 104 97 99 107 101 100 32 105 110 32 116 114 97 110 115 105 116 33 32 67 111 111 108 32 114 105 103 104 116 63 32 84 114 121 32 105 116 32 121 111 117 114 115 101 108 102 44 32 115 101 101 32 105 102 32 121 111 117 32 99 97 110 32 99 111 109 101 32 117 112 32 119 105 116 104 32 97 32 99 111 111 108 32 97 108 103 111 114 105 116 104 109 32 58 41

Python Programming An Introduction to Computer Science by Zelle. Chapter 2 Question 11

11. Write an interactive Python calculator program. The program should allow the user to type a mathematical expression, and then print the value of the expression. Include a loop so that the user can perform many calculations (say, up to 100). Note: To quit early, the user can make the program crash by typing a bad expression or simply closing the window that the calculator program is running in. You’ll learn better ways of terminating interactive programs in later chapters.

#Chapter 2 Question 11
#This program performs simple user input calculation
#I didn’t eval the input because I would like to print what the problem is in the
#final print statement. Since I didn’t eval the input, the input will be treated
#as a string instead of integers. To fix that, I can name the input as a
#different variable and then eval the input that way. This gives me the option
#To get the input from the user, print the user given input, and also
#print the answer to the equation in a simple way.

def main():
    print("This program calculates your input.")
    prob = input("Enter a calculation: ")
    problem = eval(prob)

    print(prob, "=", problem)

main()

Python Programming An Introduction to Computer Science by Zelle. Chapter 2 Question 9

9. Write a program that converts distances measured in kilometers to miles. One kilometer is approximately 0.62 miles.

#Chapter 2 Question 9
#This program takes the user input in kilometers and converts it to miles

def main():
print("This program converts kilometers into miles")    kilo = eval(input("How many kilometers? "))
mile = kilo * 0.62
print(kilo, "kilometers is", mile, "miles")
main()