masterofpuppets 19

Hi,

Why don't you use a Set to keep track of all unique words. Maybe something like this:
[CODE]Set words = new TreeSet();[/CODE] and then in your code you would just have [CODE]words.add( word );[/CODE] The number of words should be the same as the size of the set.

Hope this helps :)

AhmedGhazey commented: Good Solution +0

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,
here's a small example illustrating the find function:

[CODE]s = """This is an example
string searching method."""

word = "searching"
print s.find( word )

-> 26
and some documentation for the function:
Help on built-in function find:
find(...)
S.find(sub [,start [,end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within s[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.[/CODE]

you should check vegaseat's example on highlighting words in text, I think it is in here:

[url]http://www.daniweb.com/forums/thread191210-8.html[/url]

hope this gives you some ideas :)

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

well you're almost right :)

[QUOTE]init creates a private attribute name?

The second line in main crit.talk() and prints Hi, I'm, self.name ("Poochie"), which it is able to get because get_name method?

print cirt.name prints "Poochie", again using the get_method?[/QUOTE]

(1)yes in this case, but if omit the underscores in the beginning and write it like this self.name = name, then self.name is not private anymore.
(2) self.__name is private to the outside world but you can use it in the class so I think this line doesn't use the get_name() method because you're calling a method which uses the private variable and you're not accessing the private variable directly.
(3) here crit.name uses the get_name method because you're accessing the class variable directly and since it is private it needs a get method.

As you mentioned in your comments name = property(get_name, set_name) allows a direct call to name, i.e. print crit.name calls the get_name method of the class which then returns the correct name .
You can rewrite the whole thing like this:

[CODE]class Critter(object):
"""A virtual pet"""
def init(self, name):
print "A new critter has been born!"

    self.__name = name

def get_name(self): #---------------------------------------reads a value to a private name?
    return self.__name

def set_name( self, new_name ): #-----------------------------set's a value to a private name?
    if new_name == "":
        print "A critter's name can't be the empty string."
    else:
        self.__name = new_name
        print "Name change successful."

def talk( self ):
    print "\nHi, I'm", self.__name
main

crit = Critter("Poochie") ...

masterofpuppets 19

hi,

[QUOTE][CODE]def gradeTest():
mark = input( "Please enter the mark: " )
if mark >25:
print "Your grade is", mark2Grade( mark )
else:
print"try again"
gradeTest()

gradeTest()[/CODE][/QUOTE]

be careful with the indentation for the else statement here :)

Now, this means that the result will be shown only if the mark is greater than 25, which is not helpful. You need the mark to be in range 0 <= mark <= 25 right? so the if would be:

[CODE]def gradeTest():
mark = input( "Please enter the mark: " )
if 0 > mark or mark > 25:
print "Try again!"
gradeTest()
else:
print "Your grade is", mark2Grade( mark )

gradeTest()[/CODE]

masterofpuppets 19

you almost have it, all you have to do is to call the function with mark as an argument like this:

[CODE]def mark2Grade( m ):
if m >= 20:
return "A"
elif m >= 15:
return "B"
elif m >= 10:
return "C"
else:
return "Fail"

def gradeTest():
mark = input( "Please enter the mark: " )
print "Your grade is", mark2Grade( mark )

gradeTest()[/CODE]

See if you can figure out how to implement the check for validity, i.e. < 0 and > 25 :)

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

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 :)

masterofpuppets 19

hi,
in order to clear the previous text you can use:

[CODE]t = cv.create_text( .................. )

do stuff

time.sleep( 1 )
cv.delete( t )
cv.update()[/CODE]

.delete(..) deletes the widget from the canvas
.update() updates the canvas

hope this helps :)

masterofpuppets 19

well you could do something like this:

[CODE]d = { "a":4, "c":3, "b":12 }

for v in sorted( d.values() ):
for key in d:
if d[ key ] == v:
print key, v
break[/CODE]

hope this helps :)

masterofpuppets 19

hi,
I recently created a fully working version of Minesweeper using Tkinter and I'll try to help you because it was rather hard to figure out the logic :) Here's my idea for all the buttons for the game:

Note: I am assuming that you know about dictionaries :) if not it gets more complicated :)

have a dictionary with the button instances as keys and a value that represents the button number 0 - 80 in your case. Here's what I mean:

[CODE]from Tkinter import *

root = Tk(); root.geometry( "225x300+530+180" )
buttons = {}

def makeChoice( event ):
global buttons
print buttons[ event.widget ]

def createBoard():
global buttons
buttonNum = 0
x = -225
y = 65
for b in range( 9 ):
for b2 in range( 9 ):
button = Button( root, text = " ", font = "Courier 9", width = 2, bd = 3 ); button.place( relx = 1, x = x, y = y )
buttons[ button ] = buttonNum
buttonNum += 1
button.bind( "", makeChoice )
x += 25
x = -225
y += 26

createBoard()
mainloop()[/CODE]

when you press a button, it calls the makeChoice function which then selects the value of the widget from the dictionary.

hope this gives you some ideas :) note that this is my approach, there are probably easier ways :)

MineSweep commented: Helpful and to the point. +0

masterofpuppets 19 Posting Whiz in Training

Here's a simple tutorial on dictionaries in Python:

Dictionaries:

Dictionaries are similar to other compound types except that they can use any immutable type as an index. One way to
create a dictionary is to start with the empty dictionary and add items. The empty dictionary is denoted {}:

[CODE]end2sp = {}
end2sp[ "one" ] = "uno"
end2sp[ "two" ] = "dos"[/CODE]

We can print the current value of the dictionary in the usual way:

[CODE]print eng2sp

--> { "one":"uno", "two":"dos" }[/CODE]

The elements of a dictionary appear in a coma-separated list. Each entry contains an index and a value separated by
colon. The indices are called keys, so the elements are called key-value pairs.
Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output.

[CODE]eng2sp = { "one":"uno", "two":"dos", "three":"tres" }
print eng2sp

--> { "one":"uno", "three":"tres", "two":"dos" }[/CODE]

Note: the key-value pairs are not in order but the elements in a dictionary are never indexed with integers so there
is no reason to worry about that. Instead we look up the key:

[CODE]print eng2sp[ "two" ]

--> "dos"[/CODE]

Dictionary operations:

The 'del' statement removes key-value pair from a dictionary.

[CODE]inventory = { "apples":430, "bananas":312, "oranges":525 }
del inventory[ "oranges" ]
print inventory

--> { "apples":430, "bananas":312 }[/CODE]

The 'len' function also works on dictionaries; it returns the number of key-value pairs.

len( invenroty )  returns 2

Dictionary methods:

A method is similar ...

masterofpuppets 19

hi,
I think the problem is here:

[CODE]def ConvertToCAD(self):

get text as string and convert it to float
money = float( self.entry.get() )
# do computation
money = money * 1.05
# update label by again convertion money into string
self.labelVariable.set("The converted currency in CAD is " + str( money ) )
self.entry.focus_set()
self.entry.selection_range(0, Tkinter.END)

[/CODE]

You should use the .get() method to get the text from the Entry field and convert it either to int or float and then do the multiplication. When you get text from Entry field the text is a string so you need conversion :)

hope this helps :)

masterofpuppets 19

here's my version of it :)

[CODE]items = { "a":[ "b", "c", "d" ], "b":[ "h", "i", "j" ], "c":[ "k", "l", "m" ] }

def has_data( d, key, value ):
availableValues = []

if key not in d:
    print "Key not in found."
    return False
if value in d[ key ]:
    return True
else:
    for each in d[ key ]:
        if d.has_key( each ):
            availableValues += d[ each ]
    if value in availableValues:
        return True
return False
tests...

print has_data( items, "a", "b" )
True
print has_data( items, "a", "c" )
True
print has_data( items, "a", "k" )
True
print has_data( items, "a", "m" )
True
print has_data( items, "b", "m" )
False
print has_data( items, "a", "i" )
True
print has_data( items, "d", "b" )
Key not in found.
False
[/CODE]

hope it helps. Note that it only checks if the key has the value, it doesn't check the other way around as well :)

masterofpuppets 19

I've tried the pygame example and it works fine :) But for the pyglet one I have a problem. I downloaded and installed pyglet and when I run this:

[CODE]# play an MP3 music file using Python module pyglet

download pyglet free from: http://www.pyglet.org/download.html
(no GUI window/frame is created)

import pyglet

pick an MP3 music file you have in the working folder
otherwise use the full file path

music_file = "Intro.mp3"

music = pyglet.resource.media(music_file)
music.play()

pyglet.app.run()[/CODE]

I get the following error:

[CODE]>>>
Traceback (most recent call last):
File "C:\Documents and Settings\jori\My Documents\Gogo\University of Glasgow\First year ( Python )\Lectures\Computing Science\CS - 1P\Python\Games and stuff\Music Player\test.py", line 11, in
music = pyglet.resource.media(music_file)
File "C:\Python25\lib\site-packages\pyglet\resource.py", line 582, in media
raise ResourceNotFoundException(name)
ResourceNotFoundException: Resource "Intro.mp3" was not found on the path. Ensure that the filename has the correct captialisation.

[/CODE]

the music file is in the working directory. Any ideas what might be going wrong?

masterofpuppets 19 Posting Whiz in Training

[CODE]from Tkinter import *
root = Tk()

tipwindow = None

Creates a tooptip box for a widget.

def createToolTip( widget, text ):
def enter( event ):
global tipwindow
x = y = 0
if tipwindow or not text:
return
x, y, cx, cy = widget.bbox( "insert" )
x += widget.winfo_rootx() + 27
y += widget.winfo_rooty() + 27

Creates a toplevel window
    tipwindow = tw = Toplevel( widget )
    # Leaves only the label and removes the app window
    tw.wm_overrideredirect( 1 )
    tw.wm_geometry( "+%d+%d" % ( x, y ) )
    label = Label( tw, text = text, justify = LEFT,
                   background = "#ffffe0", relief = SOLID, borderwidth = 1,
                   font = ( "tahoma", "8", "normal" ) )
    label.pack( ipadx = 1 )

def close( event ):
    global tipwindow
    tw = tipwindow
    tipwindow = None
    if tw:
        tw.destroy()

widget.bind( "<Enter>", enter )
widget.bind( "<Leave>", close )

b = Button( root, text = "Mouse over" ); b.pack()
createToolTip( b, "Mouse is over the button" )

mainloop()[/CODE]

Gribouillis commented: useful routine +14

masterofpuppets 19

hi,
i think you almost got it, here's what I have:

[CODE]from Tkinter import *
def doKey(e):
print(e.widget.get( 1.0, END + '-1c' ) + e.char )
root= Tk()
root.title('yada')
txta = Text(root, width=40, height=10)
txta.bind("", doKey)
txta.pack(side=LEFT)
root.mainloop()[/CODE]

Btw, that kind of behaviour is just what I need for my project, sooo thanks a lot for that dude :) hope this helps :)

masterofpuppets 19

hi here's my version of the stop watch. it is not the best one but you'll get the point. woooee's example is better though and I agree with vegaseat about the threading:

[CODE]from Tkinter import *
import time

root = Tk(); root.title( "Stop Watch" ); root.geometry( "250x100+500+200" )
c = Canvas( root, width = 250, height = 100 ); c.pack()

ms, seconds, minutes, hours = 0, 0, 0, 0
on = True

def stopWatch():
global seconds, minutes, hours, on, ms
h = c.create_text( 95, 30, text = str( hours ) + " :", font = "Arial" )
m = c.create_text( 120, 30, text = str( minutes ) + " :", font = "Arial" )
s = c.create_text( 145, 30, text = str( seconds ) + " :", font = "Arial" )
mSec = c.create_text( 165, 30, text = str( ms ), font = "Arial" )
stopB = Button( c, text = "Stop", bd = 4, width = 10, command = stop ); stopB.place( relx = 1, x = -158, y = 55 )
while on:
time.sleep( 0.1 )
ms += 1
if ms == 10:
ms = 0; seconds += 1
if seconds == 60:
seconds = 0; minutes += 1
if minutes == 60:
minutes = 0; hours += 1
c.delete( h, m, s, mSec )
h = c.create_text( 95, 30, text = str( hours ) + " :", font = "Arial" )
m = c.create_text( 120, 30, text = str( minutes ) + " :", font = "Arial" ...

masterofpuppets 19

well here's my solution to the problem. I think I tested it enough but there might be some more bugs to clean:

[CODE]def get_odd_palindrome_at( s, index ):

start and end point are at the index
startIndex, endIndex = index, index
# check if the startIndex doesn't go below 0 and the endIndex doesn't exceed the length of the word
while startIndex >= 0 and endIndex < len( s ): 
    #compare the strings at the start and end locations. if they are equal go to next positions, i.e decrease start and increase end
    if s[ startIndex ] == s[ endIndex ]: 
        startIndex -= 1
        endIndex += 1
    else:
        break #don't need to go further...

#this small loop constructs the final string using the start and the end indexes
finalString = "" 
countIndex = startIndex + 1 #needed because in the previous loop start is decreased by one
while countIndex < endIndex:
    finalString += s[ countIndex ] #add the char to the new string
    countIndex += 1
return finalString[/CODE]

hope this makes it a bit clearer :)

masterofpuppets 19

hi
try this:

[CODE]def remove_non_words( s ):
new_s = ""
for l in s.lower():
if l in "abcdefghijklmnopqrstuvwxyz":
new_s += l

return new_s

def is_palindrome( user_input ):
i = 0
user_input = user_input.lower() #lowercase
user_input = remove_non_words( user_input ) #remove punctuation and stuff...
result = True
while i <= len( user_input ) - 1 and result == True: #remove second while loop...
if user_input[i] == user_input[-1 - i]:
result = True
else:
result = False
i += 1
return result

print is_palindrome( "racecar" )[/CODE]

hope this helps :)

mms6 commented: Thanks +0

masterofpuppets 19

ok, right...here's what I came up with last night. It's not 100% complete but can give you some idea on what could be improved...:)

[CODE]from random import randint

Gets and returns the names of the players

def getNames():
print "*****"
player1 = raw_input( "Player 1, enter your name: " )
player2 = raw_input( "Player 2, enter your name: " )
print
return player1, player2

Picks a random card number and adds it to the current hand

def hit():
return randint( 1, 11 )

Checks if a player goes 'bust'

def checkBust( player1Nums, player2Nums ):
if player1Nums > 21 and player2Nums <= 21:
return 1
elif player2Nums > 21 and player1Nums <= 21:
return 2
elif player1Nums > 21 and player2Nums > 21:
return "both"
else:
return "none"

Available options for each player

def takeTurn( player ):
turnAction = raw_input( player + " do you wish to 'hit' or 'stand'? >> " )
while turnAction not in [ "hit", "stand" ]:
print "Wrong input"
turnAction = raw_input( player + " do you wish to 'hit' or 'stand'? >> " )
return turnAction

def printStatus( pl, value ):
print pl + ", you currently have a hand value of " + str( value ) + "."

Restart or quit

def endGame():
new_game = raw_input( "New game? ( y/n ) >> " )
print
if new_game == "y":
a, b = getNames()
startGame( a, b )

Deal with the situation where one player is bust and the other is stand

def checkBustAndStand( p1Bust, ...

PixelHead777 commented: Wow... thanks, man. This is like... -the- best thing you could do for me. Now that I know a little more about defining functions for uses, and of course getting to learn new functions (type() is going to be fun to find out about)? More learning! +0

masterofpuppets 19

here's a hint:

[CODE]l = [ 1, 5, 3, 7, 9, 2, 5, 6 ]
longest = l[ 0 ]
for i in l:
if i > longest:
longest = i
print longest[/CODE]

just modify the hailstorm function so it returns the length instead of printing the actual results and in every cycle compare it to the previous length :) hope this helps you

masterofpuppets 19 Posting Whiz in Training

A simple function to return the number of occurances of a letter in a text. An easier way to implement this would be by using a dictionary :)

P.S sorry if there already is a code snipped like that somewhere.

masterofpuppets 19 Posting Whiz in Training

This is my first GUI program in Java. If finds the day of the week for any given date which is after 1 January 1900.

masterofpuppets 19

maybe a simple program to take a string and print it out backwards
Then extend the program to check whether a word is a palindrome, i.e can be read the same way in either direction.
Further extension is to configure the program to determine whether a whole sentence is a palindrome.
Hint: remove all non-letter characters from the string first, including whitespaces :)

masterofpuppets 19

Hi
I havent really used pyGTK but I'll try to help anyway
I kinda did something similar to what you're trying to do but for a blackjack game If you have buttons like Fold, call, rise... why don't you just set the command to these buttons to be a separate function which you call, after having completed your turn. This finction then calls the other functions for the players. That way the fns for the other players will have to wait untill you make your move
I thinks it seems confusing so I'll try to code it a little:

[CODE]def amandaBet():

...

def billBet():

...
. so on..

def playerBet():

your code here...
do stuff

...
betInOrder() # here you could either start from the beginning, i.e. the first to bet by calling betInOrder() when you press Fold, Call etc. or do something else. That way the game will not continue untill you call betInOrder()

def betInOrder():
amandaBet()
billBet()
...
playerBet()[/CODE]

I don't know if this is any helpful but I used something similar