masterofpuppets 19

Hi,

As jackmaverick1 said, the Scanner is simpler to use, depending on what you want to do - if you just need to enter commands, use scanner.nextLine() and then parse the command. As for the DataInputStream, I think you should use it for reading bytes and file transfer.

masterofpuppets 19

hi,
you could do something like this:
[CODE]men = [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 10 ], [ 11 ], [ 12 ], [ 13 ], [ 14 ], [ 15 ] ]
for gender in men[ :10 ]:
print gender

Output:

"""[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]"""[/CODE]

I'm not sure whether the format of the list I'm using is the same as the one you specified, so pls. correct me if this is not right.

hope this helps :)

masterofpuppets 19

yeah sorry about that I guess I should've mentioned that I'm using Python 2.5.2 :)

masterofpuppets 19

hi,
here's a way of doing this using a class:

[CODE]from random import *

class Hangman:
def init( self, textFile ):
self.word = self.generateWord( textFile )
self.
used = []
self.guessed = []
self.
tries = 10
self.__checkWord = self.removeDuplicateLetters()
self.newGame()

def generateWord( self, fileName ):
    f = open( fileName, "r" )
    words = f.readlines()
    f.close()

    return words[ randint( 0, len( words ) - 1 ) ].strip()

def removeDuplicateLetters( self ):
    l = []
    for w in self.__word:
        if w not in l:
            l.append( w )
    return l

def displayWord( self ):
    for l in self.__word:
        if l in self.__guessed:
            print l,
        else:
            print "_ ",
    print

def newGame( self ):
    win = False
    while not win and self.__tries > 0:
        self.displayWord()
        guess = raw_input( "Enter your guess >> " ).lower()
        while guess not in "abcdefghijklmnopqrstuvwxyz":
            print "Enter a letter please!\n"
            guess = raw_input( "Enter your guess >> " ).lower()
        if guess in self.__word and guess not in self.__used:
            print "You guessed a letter!\n"
            self.__guessed.append( guess )
            if len( self.__guessed ) == len( self.__checkWord ):
                win = True
        else:
            if guess in self.__used:
                print "Letter already used.\n"
            else:
                self.__tries -= 1
                print "The letter is not in the word. Tries left >", self.__tries, "\n"

        self.__used.append( guess )

    if not win:
        print "You lost the game!"
    else:
        print "You guessed the word!"

if name == "main":
Hangman( "words.txt" )[/CODE]

it may not be the best way to implement but I think you'll get the idea :)
As for the word list, Why don't ...

JuvenileMango commented: So helpful! +0

masterofpuppets 19

hi,
as mentioned in the above post you need to use the raw_input function because input reads in an integer/float value :)

masterofpuppets 19

hi,
using woooee's example, this becomes:

[CODE]test_matrix = [ ["A", "b", "c"], \
["R", "S", "s"], \
["X", "Y", "Z"] ]

for x in range( len( test_matrix ) ):
for y in range( len( test_matrix[ x ] ) ):
if test_matrix[ x ][ y ] == "S":
start = ( x, y )

now you can use start here as a tuple.

print "\nS found in", start, "\n"

output
-> S found in (1 1) [/CODE]

hope this helps :)

masterofpuppets 19

hi,
well it depends on what you want to do, why don't you just define the function and then reuse it in the class methods. :)

masterofpuppets 19

[QUOTE=vegaseat;1067218]Hide the root window with:
root.withdraw()

Remove root window border and title bar with:
root.overrideredirect(1)

Bring the full root window back up with:
root.update()
root.deiconify()[/QUOTE]

thanks dude, that's really useful, I'll use it as well :)

masterofpuppets 19

@ hondros
:) yeah.. sorry about that I forgot to mention that you'll need to convert the character into lowercase as well :) Have a go at doing this and if you have any problems we'll be happy to help :)

masterofpuppets 19

hi,
a better way to do this is to use a dictionary for the letters instead of all these if..elif statements, like this:

[CODE]def createLetterDictionary(): # Creates the dictionary of letter-number pairs
l = {}
letters = " abcdefghijklmnopqrstuvwxyz"
for i in range( len( letters ) ):
l[ letters[ i ] ] = i
return l

message = raw_input()

letters = list( message )
alphabet = createLetterDictionary()
message_number = []

for letter in letters:
if letter in alphabet: # check if the character is in the dictionary
message_number.append( alphabet[ letter ] )

print message_number[/CODE]

I'm assuming you've heard of dictionaries, otherwise you can do something like this:

[CODE]message = raw_input()

letters = list( message )
alphabet = " abcdefghijklmnopqrstuvwxyz"
message_number = []

for letter in range( len( letters ) ):
if letters[ letter ] in alphabet:
for i in range( len( alphabet ) ):
if letters[ letter ] == alphabet[ i ]:
message_number.append( i )
break

print message_number[/CODE]

hope this helps :)

masterofpuppets 19

hi,
here's what you can do:

[CODE]for i in range( 4 ): # since you want 4 repetitions
employeeName = str( input( "Enter employee name: " ) )

rate = float( input( "Enter rate: " ) )
hours = float( input( "Enter hours worked: " ) )

if hours>40:
    pay = 40 * rate + ( hours - 40 ) * 1.5 * rate
    overtime = ( hours - 40 ) * 1.5 * rate
    print ( "For this week overtime earned $", overtime )
else:
    pay = hours * rate
    overtime = ( hours - 40 ) * 1.5 * rate
    print ( "For this week overtime earned $",overtime )
print ( "For this week you earned $", pay )
print[/CODE]

just put everything in a for loop :)
pls next time put code tags, it's hard to read otherwise

hope this helps :)

kaydub123 commented: very helpful information +0

masterofpuppets 19

hi,
here's my version of this:

[CODE]s = "bananasplit"
newS = ""

for e in range( 0, len( s ), 3 ):
newS += s[ e:e + 3 ][ 0 ]
if len( s[ e:e + 3 ] ) == 3:
newS += "xy"
elif len( s[ e : e + 3 ] ) == 2:
newS += "x"

print newS

-> >>>

bxyaxysxyix

[/CODE]

Note that since the last symbol is 11th only x is added at the end

hope this helps :)

masterofpuppets 19

hi,
[CODE]elif 5 <= unhappiness <= 10[/CODE]
is the same thing as
[CODE]elif 5 <= unhappiness and unhappiness <= 10[/CODE]

it's useful if you have long expressions and is evaluated to True only if the two conditions are True :)

the endless loop seems to be in the main function. I think you've got the indentation wrong. You need to ask for the input inside the while loop and all if..elif should be inside as well. Like this:

[CODE]def main():
crit_name = raw_input("What do you want to name your critter?: ")
crit = Critter(crit_name)

choice = None

while choice != "0":
    print \
    """
    Critter Caretaker

    0 - Quit
    1 - Listen to your critter
    2 - Feed your critter
    3 - play with your critter
    """

    choice = raw_input("Choice: ")
    print

    # exit
    if choice == "0":
        print "Good-bye."

    # listen to your critter
    elif choice == "1":
        crit.talk()

    # feed your critter
    elif choice =="2":
        crit.eat()

    # play with your critter
    elif choice == "3":
        crit.play()

    # some unknown choice
    else:
        print "\nSorry, but", choice, "isn't a valid choice."[/CODE]

masterofpuppets 19

hi,
well one of the main purposes of the classes is to be able to create multiple objects of the same type using just one class. So your code could be simplified so that the class creates only one matrix. You can of course create many matrices by having many class instances. Here's what I mean:

[CODE]print ''
print 'Enter the following:'
print '\'1 for Entering a matrix'
print ' \'1 for a 2x2 matrix'
print ' \'1\' for matrix A'
a = 0
b = 0

class Matrix:
"""Class to create a single 2x2 matrix using user input."""
def init( self ):
self.matrix = self.createMatrix()
self.showMatrix()

def createMatrix( self ):
    matrix = []
    for i in range( 2 ):
        row = []
        for j in range( 2 ):
            print 'Row', i + 1, 'column', j + 1, ':'
            entry = input()
            row.append( entry )
        matrix.append( row )

    return matrix

def showMatrix( self ):
    print "The matrix is:\n"
    for row in self.matrix:
        print row

m1 = Matrix() #Create the first matrix object
m2 = Matrix() #Create the second matrix object[/CODE]

if you don't understand parts of this I'll be happy to explain :)

hope this helps :)

P.S. of course you can extend this so that it can create mxn sized matrices as well! :)

masterofpuppets 19

yeah... this really looks weird !?

is this what you mean?
[CODE]startingWeight = input( "Enter starting weight in lbs: " )
print( "Starting weight of food in lbs entered is", startingWeight )[/CODE]

Not sure whether you want to use a dictionary or not for this :)

masterofpuppets 19

hi,
I think the problem is that you're using the readlines method in the loop. You only need to read the lines from the initial file once and just copy them in the other files, so try to move the readlines outside the loop like this:

[CODE]initFile = open( "filename.txt", "r" )
fileHandle = initFile.readlines()

maxValue = 20
for i in range( 1, maxValue + 1 ):
onitFile = open( "File%d.txt" % i, "w" )

for fileLine in fileHandle:
onitFile.write( fileLine )
onitFile.close()

initFile.close()[/CODE]

this should work

hope this helps :)

masterofpuppets 19

hi,
you could also use a dictionary if you want to assign values to the variables, e.g.:

[CODE]d = {}
for i in range( 10 ):
d[ "x" + str( i ) ] = i

print d

-> {'x8': 8, 'x9': 9, 'x2': 2, 'x3': 3, 'x0': 0, 'x1': 1, 'x6': 6, 'x7': 7, 'x4': 4, 'x5': 5}
then you can just use the value from the dictionary like this

print d[ "x5" ]

-> 5[/CODE]

not sure if this is what you mean but hope it helps anyway :)

masterofpuppets 19

ok I'll try my best to explain what's goig on here :) sorry if it doesn't work out any good :)

for your first question:
I've never used the staticmethod function before but I ran the code and I think it changes the type of the argument method, in this case status, to static. This means that you can call the method without using an instance of the class, in this case Critter. And that's exactly what the code does, i.e it calls status via the class name rather than an instance variable for the class - Critter.status().
Now if you remove or comment the statement status = staticmethod( status ) and run the code, you'll get an error like:

[CODE]Traceback (most recent call last):
File "C:/Documents and Settings/jori/Desktop/t.py", line 27, in
Critter.status()
TypeError: unbound method status() must be called with Critter instance as first argument (got nothing instead)[/CODE]

And this is because status is an unbound method and you need to put self as a parameter like this
[CODE]def status( self ):
print "\nThe total number of critters is", Critter.total[/CODE]
to connect it to the class ( not sure for the exact terminology ) Of course now you have to call the method with an instance of the class because it is not static anymore :)

as for the second question:
The mandatory 'self' argument in the constructor is used in the whole class as a parameter to the methods. So 'self' refers to the self in the ...

masterofpuppets 19

Because at the end you need to call main instead of fahrenheit2celsius :)
like this:

[CODE]def main():
fahrenheit2celsius()
for i in range(10000):
cont = raw_input('Would you like to continue converting? (yes/no): ')
if cont == 'yes' or cont == 'Yes':
fahrenheit2celsius()
else:
break

main()[/CODE]

masterofpuppets 19

thanks, this makes it better :)

right, so for your first loop the range should be range( maxValue ) or range( maxValue + 1 ) if you want to include maxValue in the output.
In the second loop wou want to pring all the numbers up to the value of the counter for the first loop. Sorry if this sounds confusing, here's what I mean:

[CODE]maxValue = input( "Enter a value >> " )

Here you start from 1 so that in the second loop '0' is printed once
You need to add 2 to maxValue because you start counting from 1 and the range function
doesn't include the second parameter, so if you had maxValue + 1 and maxValue is
20, say, the loop will continue until i reaches 19, 20 is not inicluded.

for i in range( 1, maxValue + 2 ):
for j in range( i ):
print j,
print

output:

Enter a value >> 10
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 10
[/CODE]

the comma after the first print statement means that the next print is on the same line ...

masterofpuppets 19

hi,
it depends on how many numbers you want in a row :) And yeah you need a double loop for this.

Here's a hint:

[CODE]for i in range( number of rows ):
for r in j in range( number of numbers per row ):
print j,
print[/CODE]

try to be more specific about what you want to do and put your code here so that we can see what you've done so far and give you advice :)

masterofpuppets 19

well, the code is probably giving an error message, saying that 'fahrenheit' or 'celsius' is not defined and this is correct - you haven't defined them anywhere. They are just parameters in the two functions. That means you can't use them anywhere else but inside the function. So you should call the functions with 'temperature' as an argument like this:

[CODE]def fahrenheit2Celsius( fahrenheit ):
return ( fahrenheit - 32 ) * 5.0 / 9.0

def celsius2Fahrenheit( celsius ):
return 9.0 / 5.0 * celsius + 32

def fahrenheit2celsius():
temperature = input( "Please enter the temperature to convert: " )
fahrenheitorcelsius = input( "1 = farenheit / 2 = celsius: " )

if fahrenheitorcelsius == 1:
    print temperature, "in Fahrenheit is", fahrenheit2Celsius( temperature ), "Celsius"
elif fahrenheitorcelsius == 2:
    print temperature, "in Celsius is", celsius2Fahrenheit( temperature ), "Fahrenheit"

fahrenheit2celsius()[/CODE]

suppose that the user enters 43 and also enters 2 after this. Here's what happens - the if is skipped because fahrenheitorcelsius is 2; then the program prints the message and calls the function celsius2Fahrenheit with temperature, which is 43, as an argument, so inside the function 'celsius' becomes equal to 43 so the function performs the computation 9.0 / 5.0 * 43 + 32 and returns the result.

hope this helps :)

ddanbe commented: Very good explanation! +5

masterofpuppets 19

yes this has to work, I found graphics.py and downloaded it and it worked :)

masterofpuppets 19

ah yes I think I haven't defined color :)

try this:

[CODE]import time

def trafficLights():
win = GraphWin()
red = Circle(Point(100, 50), 20)
red.setFill("black")
red.draw(win)
amber = Circle(Point(100, 100), 20)
amber.setFill("black")
amber.draw(win)
green = Circle(Point(100, 150), 20)
green.setFill("black")
green.draw(win)

color = "red"

changeColor = { "red":"yellow", "yellow":"green", "green":"red" }
while True:
    for light in [ red, amber, green ]:
        light.setFill( color )
        # not sure what the update function for the screen is but you need to call it before you call time.sleep()
        time.sleep(5)
        light.setFill( "black" )
        color = changeColor[ color ][/CODE]

masterofpuppets 19

what's the error message?

masterofpuppets 19

sorry I forgot that when you change the color you need to set the color of the previous light to black again:

[CODE]while True:
for light in [ red, amber, green ]:
light.setFill( color )

not sure what the update function for the screen is but you need to call it before you call time.sleep()
    time.sleep(5)
    light.setFill( "black" )
    if color == "red":
        color = "yellow"
    elif color == "yellow":
        color = "green"
    elif color == "green":
        color = "red"[/CODE]

you could simplify the if..elif to this

[CODE]changeColor = { "red":"yellow", "yellow":"green", "green":"red" }
while True:
for light in [ red, amber, green ]:
light.setFill( color )

not sure what the update function for the screen is but you need to call it before you call time.sleep()
    time.sleep(5)
    light.setFill( "black" )
    color = changeColor[ color ][/CODE]

masterofpuppets 19

hi,
as Ene Uran mentioned, not sure what GUI toolkit this is but I'll try to help anyway, I think I get the overall idea :)
Just a note: put the import statements in the beginning of the program.

It's something like this:

[CODE]import time

def trafficLights():
win = GraphWin()
red = Circle(Point(100, 50), 20)
red.setFill("black")
red.draw(win)
amber = Circle(Point(100, 100), 20)
amber.setFill("black")
amber.draw(win)
green = Circle(Point(100, 150), 20)
green.setFill("black")
green.draw(win)

color = "red"
while True:
    for light in [ red, amber, green ]:
        light.setFill( color )
        # not sure what the update function for the screen is but you need to call it before you call time.sleep()
        time.sleep(5)
        if color == "red":
            color = "amber"
        elif color == "amber":
            color = "green"
        elif color == "green":
            color = "red"[/CODE]

Note I think this should work but I'm not sure because I haven't tested it :)

hope this helps :)

masterofpuppets 19

sorry for the double post :)

here's another way by using radiobuttons instead:

[CODE]from Tkinter import *

root = Tk(); root.geometry( "180x190+400+200" )
root[ "bg" ] = "white"

players = { 1:0, 2:0 }
close = False

def increaseScore():
global players, close, buttons
if close:
root.destroy()

v = var.get()
players[ v ] += 1
if players[ 1 ] == 11:
    b1[ "text" ] = str( players[ v ] ) + "\nWIN"
    close = True
elif players[ 2 ] == 11:
    b2[ "text" ] = str( players[ 2 ] ) + "\nWIN"
    close = True
else:
    buttons[ v ][ "text" ] = players[ v ]

var = IntVar( root, 0 )
b1 = Radiobutton( root, text = "0", indicatoron = 0, height = 14, width = 13, variable = var, value = 1, command = increaseScore ); b1.place( relx = 1, x = -180, y = 0 )
b2 = Radiobutton( root, text = "0", indicatoron = 0, height = 14, width = 13, variable = var, value = 2, command = increaseScore ); b2.place( relx = 1, x = -88, y = 0 )

buttons = { 1:b1, 2:b2 }

mainloop()[/CODE]

see if you could implement the algorithm for a two point win :)
post your code if you're stuck at some point :)

masterofpuppets 19

ok,
here's one ( not very good way of doing it ) but it'll give you some idea I hope. Since you haven't done classes I'll use functions and a dictionary for the players:

[CODE]from Tkinter import *

root = Tk(); root.geometry( "180x190+400+200" )
root[ "bg" ] = "white"

players = { 1:0, 2:0 }
close = False

def increaseScore1():
global players, b2, close
if close:
root.destroy()
players[ 1 ] += 1
if players[ 1 ] == 11:
b1[ "text" ] = str( players[ 1 ] ) + "\nWIN"
close = True
else:
b1[ "text" ] = players[ 1 ]

def increaseScore2():
global players, b2, close
if close:
root.destroy()
players[ 2 ] += 1
if players[ 2 ] == 11:
b2[ "text" ] = str( players[ 2 ] ) + "\nWIN"
close = True
else:
b2[ "text" ] = players[ 2 ]

b1 = Button( root, text = "0", height = 14, width = 13, command = increaseScore1 ); b1.place( relx = 1, x = -180, y = 0 )
b2 = Button( root, text = "0", height = 14, width = 13, command = increaseScore2 ); b2.place( relx = 1, x = -88, y = 0 )

mainloop()[/CODE]

P.S I'm not sure whether this is what you mean. That is how I understand the problem :)

hope this helps :)

masterofpuppets 19

hi,
a couple of errors in your functions:
first, try to fix your indentation in the while loop, i.e. for the first if statement
second, the error occurs because you are calling the functions with variables c and f which are not defined in your main function. You should be calling the functions with the variable start instead. c and f are just parameters in the functions :)
third, you need to get the input from the user again at the end of the while loop because otherwise you go into an infinite loop.

it should be something like this:

[CODE]def main1( f ):
return (f - 32) * 5.0 / 9.0

def main2( c ):
return 9.0 / 5.0 * c + 32

def temperature():
start = int(raw_input("Please enter a temperture: "))
option = raw_input('Enter C for celcius, F for farenheit, or Q for quit:')
while option != "Q":
if option == "F":
print main1( start )
if option == "C":
print main2( start )

    start = int(raw_input("Please enter a temperture: "))
    option = raw_input('Enter C for celcius, F for farenheit, or Q for quit:')

temperature()[/CODE]

hope this helps :)