shadwickman 159 Posting Pro in Training

I can only assume that you put the indentation level of the if statements so that they were inside the loop. They should be outside of that while loop, like I had in my above code.

shadwickman 159 Posting Pro in Training

I was reacting to this:

"That is why i respect a blonde cute female c++ developer too much.
She could have taken advantage of her beauty instead of coding all her life..
She just likes to produce something with her brain, she likes contemplating and observing."

Nav33n is correct. Say hello to Serkan Sendur... if you search around for his posts you'll probably find most non-programming related threads seem to have been polluted with some (at times) disturbing material about a certain other member on this site :P
Welcome to DaniWeb hahaha :)

nav33n commented: :D heh.. +11
shadwickman 159 Posting Pro in Training

... Super Moderator badge?

can i have it?

You have my vote. I believe the forums would be filled with a lot less of the "i has homework give me code plz" posts.

jephthah commented: building an army, one comrade at a time +14
shadwickman 159 Posting Pro in Training

Remember that the script executes downwards; it doesn't all happen at once. Things like raw_input also stall until input is given, then the script continues. So this is fairly easy to do; here's an outline of what you'll want:

class MainMenu(object):
    def __init__(self):
        # do your stuff here
    def askWhichClass(self):
        choice = raw_input("Which class?  ")
        return choice

# define your player classes here...

mm = MainMenu()
choice = mm.askWhichClass()
if choice == 'serf':
    player = PlayerSerf()
elif choice == 'baron':
    player = PlayerBaron()
# etc...

This first initializes an instance MainMenu class (as mm). Then we call its method for getting the user's choice (via the raw_input statement) and then we check it with if statements to make player an instance of the appropriate class.
Hope this clears up your confusion!

shadwickman 159 Posting Pro in Training

if my best friends dont get featured i am going to organize them to leave for a better c# forum where their skills are appreciated.

I'm not trying to start slinging shit here, but is this a mutual agreement or are you just putting words into your friends' mouths? Hmm... by the way this isn't a union thing or nothing. Please feel free to leave if you are fed up helping people.

shadwickman 159 Posting Pro in Training

For Python 2.x:
People seem to overlook the usefulness of built-in functions for handling common issues with lists. A lot of times, filter , map , and reduce can easily and efficiently serve typical purposes that most people attempt without these. Here's an example of their usage (I use lambda expressions in them - you can read up on lambda expressions here):

# filter
# in the interactive shell, use help(filter) for more info.
# filter takes a function and a list, and returns a list of
# the items that returned True for the given function.
# This example takes a list and returns one with the
# unallowed words removed.

words = ['This', 'sentence', 'has', 'unallowed', 'words']
unallowed = ['has', 'words']
remainder = filter(lambda x: x not in unallowed, words)

"""result ->
['This', 'sentence', 'unallowed']
"""
# map
# in the interactive shell, use help(map) for more info.
# map takes a function and a list, and returns a list of
# the items after applying the specified function to them.
# This example takes a list and returns one in which
# every index was squared.

data = [2, 5, 9, 16, 31, 35]
squared = map(lambda x: x*x, data)
"""result ->
[4, 25, 81, 256, 961, 1225]
"""
# reduce
# in the interactive shell, use help(reduce) for more info.
# reduce takes a function and a list, and returns a single
# value formed by taking the result of …
Lardmeister commented: nice code examples +5
shadwickman 159 Posting Pro in Training

You can try the built-in filter function. Here's what I tried in the interpreter:

>>> a = [
	'filter',
	'lol',
	'filter',
	'lol',
	'lol',
	'filter',
	'lol'
        ]
>>> b = ['filter']
>>> c = filter(lambda x: if x in b, a)
>>> c
['filter', 'filter', 'filter']

As you can see, it takes each item in the list passed to filter (in this case, "a"), and returns a list of the values that returned True in the function passed to it.
In this case, the lambda function would return True if the current item (x) is in list "b". I hope that simplified your code a lot :P

Here's a Dive Into Python links concerning filter, and lambda.

Nyaato commented: Thanks for helping! +1
shadwickman 159 Posting Pro in Training

Yield is for generator functions. Return ends the function and sends back the specified value.
Generators are functions that return iterators, i.e. they 'yield' a value after each iteration of them, before proceeding to the next one. This is generally used for things where you don't need all the results returned at once (which must load them all into memory), but instead only gives back the results one at a time (which can vastly reduce memory usage).

Python documentation on generators,
And on iterators.

Here's their example of a simple generator:

def reverse(data):
    # start at the last index and step back one each time.
    for index in range(len(data)-1, -1, -1):
        yield data[index]

for char in reverse('golf'):
    print char

"""result:
f
l
o
g
"""

What this does is call each iteration of the reverse function each time the "for" loop executes in the statement for char in reverse('golf') . This way, only a single letter is sent back each time, rather than the fully-reversed string.
This isn't a great example of generator usage, but say if you had a dataset with 1000s of numbers and you needed to perform calculations on them, but you'd only be working on one item in the set at a time anyway. Then a generator would be useful as it would save a TON of memory by only returning each item as it's needed.
Hope that helped!

Your_mum commented: helpful +1
shadwickman 159 Posting Pro in Training

PLEASE! Use code tags! If you look at your post, you realize your Python code has no indentation anymore, and indentation is a crucial part of Python. I'm not going to bother looking through your code until you edit that post and put your code in those tags to preserve the spacing.

Salem commented: Well said! +36
shadwickman 159 Posting Pro in Training

In case you didn't notice, your linedata dictionary has no key "id". Hence you receiving the "KeyError" problem. You need the ID of the column you're inserting this into if I'm correct (I barely touched on MySQL about a year ago). Is the table you're inserting this into blank, and you're building it up? Or does it contain data and you're just overwriting/editing rows?
If you're building up a blank table, why not just track the number of rows you've added to the table so far and then you can use that as the id? Set "rowsadded" to zero at the beginning of your script and then increment it after each row input to the table. That way you can have your linedata dictionary as this:

linedata = {'id':rowsadded, 'time':data[1], 'date':data[9],'latitude':latitude,'longitude':longitude,'speed':data[7]}
sneekula commented: thanks for taking the tough ones +8
shadwickman 159 Posting Pro in Training

Ahahah! Wow, this is just getting a little odd guys (not to mention off topic, what happened to movies? :P)

William Hemsworth commented: *nods* i'll stop. +12
shadwickman 159 Posting Pro in Training

If anyone is still interested in those old, nostalgic text-based games to run in the console, there's Python Universe Builder by Joe Strout. Yes, it's a dead project as the last release dates back to 2006, but it still works fine if anyone is interested. On the Sourceforge page for PUB, the download section contains 1.0a2 and 2.0, but as far as I know 2.0 isn't a full release, so 1.0a2 is the working one (i'll need to double-check). And by 'working' I mean you'll need to manually install it into your site-packages folder for Python, after changing a few things like instances in its scripts of the "whrandom" module which was phased out long ago in lieu of the "random" module. Oh, and this will only work for Python 2.x installations, not 3.0.

I'm posting this here because I know an unbelievable amount of users post here about either making a 3D game or making a game engine, without actually knowing anything about those topics in the least. If people want to make a game, then a simple text-based one can still be a lot of fun (comes down to how well the story is written), and should provide good practice for anyone interested in Python or in getting into game development.

Here's a tutorial for it if anyone's interested.

Nick Evan commented: Nice project. +19
shadwickman 159 Posting Pro in Training

Got it :D

data = [['4/18/94', '29.125', '442.46'],
    ['4/19/94', '29.336', '442.54'],
    ['1/20/04', '75.175', '1138.77'],
    ['1/21/04', '75.711', '1147.62'],
    ['1/22/04', '75.595', '1143.94']]
    
result = []

for item in data:
    # current middle index as a float
    n = float(item[1])
    
    # if there are no items in the result list yet
    if not result:
        result.append(item)
        
    # otherwise, if there are,
    else:
        # previous number (last one in result list) as a float
        prevnum = float(result[-1][1])
        
        if (prevnum < 30 and n > 75) or (prevnum > 75 and n < 30):
            result.append(item)

"""
My result:
[['4/18/94', '29.125', '442.46'], ['1/20/04', '75.175', '1138.77']]
"""
rasizzle commented: excellent advice +1
shadwickman 159 Posting Pro in Training

Which Linux distro are you using? Regardless, if you want a visual editor for wxPython, I'd suggest wxGlade. It generates nice code but it may take a little getting used to using. I mostly just code all my GUIs by hand anyways.
As for good wxPython resources, here's some:

Style Guide - Not too comprehensive, but might offer some standardizing tips.
wxPython by Example - A short tutorial which has good examples for bare-bones apps.
wxPython Cookbook - Contains a lot of information on various aspects of wxPython. Lots of examples.
Widget Examples - Has a number of good application skeletons and examples about individual widgets and their uses.
Documentation - The regular documentation for wxPython.

VERY GOOD Tutorial - I'd recommend giving this a read through and looking at the example code as it's quite large and it covers a lot in an understandable way.

wxGlade Tutorial - If you decide to give wxGlade a go. Make sure to learn pure wxPython coding first so that you can do it by hand. Then use this for large GUIs just to speed things up if you want.

There was another very definitive page with all the widgets and examples and information about them, but I can't seem to find it at the moment. I'll post it later if I do find it. Hope these help for now! :)

shadwickman 159 Posting Pro in Training

Trainspotting
One Flew Over the Cuckoo's Nest
A Clockwork Orange
A Scanner Darkly
Fear and Loathing in Las Vegas

jephthah commented: quality head trips. +11
shadwickman 159 Posting Pro in Training

Actually, I hadn't realized it before but no matter what, your range will go to the pre-set length, yet you're removing items from the list, which is shortening it to less than that pre-set range. Changing the range inside the for loop has no effect either.
This will allow you to adjust the range inside the loop:

BuyList = [1,2,3,4,9,11]
SellList = [0,7,8,10,12,15]

myrange = 0

if len(BuyList) < len(SellList):
    myrange = len(BuyList)
else:
    myrange = len(SellList) 

x = 0
while x < myrange:
    if SellList[x] > BuyList[x]:
        del BuyList[x]
        myrange -= 1
    x += 1

print BuyList
print SellList

"""
Output:
[1, 3, 9, 11]
[0, 7, 8, 10, 12, 15]
"""

I'm still not 100% sure what you're trying to achieve with this code... unless you want it to assign the biggest "sell" index possible to each "buy" index? So there is the biggest difference between indices of the two lists?

Anyways, you should look at Ene Uran's code because that may be what you're looking for, as it looks close to what you want and it's a nice, clean-looking solution.

shadwickman 159 Posting Pro in Training

Your "items" dictionary doesn't have a key named "o" which apparently you are trying to locate. The line if p.weapon == items[sitem[1]] is basically equating to if p.weapon == items["o"] . That seems to not be in the chunk of "relevant code" that you posted, but even so, the code you posted throws an error on its own.

Regarding the code, you shouldn't cycle the dictionary "items" like you are currently doing. Cycle the list of the values in the dictionary, and unpack them to variable names like this:

items = {'sword':['sword', 3, 15],
    'axe':['axe', 5, 25],
    'bow and arrow':['bow and arrow', 4, 20]}
for item, price, damage in items.values():
    print item
    print "\tprice", price
    print "\tdamage", damage

Your items dictionary is a little repetitive though, by putting the item name as both the key and the first index in the value of it. This is much better:

items = {'sword':[3, 15],
    'axe':[5, 25],
    'bow and arrow':[4, 20]}
# cycle through the (key, value) list of the dict
for item, stats in items.items():
    print item
    print "\tprice", stats[0]
    print "\tdamage", stats[1]

Hope that helped!

Ene Uran commented: very nice example +7
shadwickman 159 Posting Pro in Training

I haven't done this in forever, and I'm not on a linux machine at the moment, but I'll try to say what I remembered doing :P

If you originally installed it using "sudo apt-get install ...." then you may have not installed any other packages it requires to run.

I would use the package manager GUI instead of the terminal commands because I don't know the package name for wxpython off the top of my head, and the GUI will auto-tick all the dependencies. Search for "wx" in the GUI and when it populates the list with the results, find your wxpython package that you installed and remove it and any dependencies.

Let that finish uninstalling and then open the Synaptic GUI again and search 'wx'. Then find the wxpython package that fits your version of Python (if you're not sure what Python you have, just type "python" in the terminal to get to the interactive shell, which should list the version number in the first line). Check the wxpython package and if it asks about other dependencies, allow it to check those for installation too. Then let it do its thing, and wxpython should work after that!

I will try to get onto an Ubuntu machine within the next 30 minutes or so, and from there I'll edit this with a better description, as I know this is my recollection and it's too vague.

vegaseat commented: thanks for helping out +12
shadwickman 159 Posting Pro in Training

All it does is split the input into a list and save it as b like we did before. As of then, we have a list of numbers, but they are actually strings (e.g. ).

From there, we use a for loop to cycle though list b (i is the index number, and n is the index value from the enumerate function). All we do then is tell it to replace b (the current index it's on) with the old value of it (the string, n) converted to an integer through the int function.

I hope that clarifies it a bit!

max.yevs commented: really helpful, thanks a lot +1
shadwickman 159 Posting Pro in Training

I'm highly confused... so what are you asking to call? Assuming you have the attributes __employee_name and __employee_number on the class this function is a part of, this should run fine...
So I'm going to assume that the objects in this list you mentioned are instances of this class, in which case you could cycle through it and just call this function from each one, like this:

for instance in myList:
    instance.show_employee()

Hopefully this is what you wanted; just tell me if I was way off from your question or something.

eyewirejets commented: Awesome +1
shadwickman 159 Posting Pro in Training

I would say you could take the input string, and split it at each whitespace into a list. Index 0 would be the function name, and each index after would be the arguments. Like:

cmdlist = usercmd.split(' ')  # split at each space

This would make a list like:

[ 'test', '1', '2', '3' ]

Then you just need to call the function and pass the indices 1 and above. If you want more details, just ask but I hope this got you started in a new direction!

crumpet commented: thanks! put me on the right track straight away +1
shadwickman 159 Posting Pro in Training

The variable timesflipped used for the while loop is undefined before the comparison while timesflipped < 100: . This script should just return a NameError and not run.
Here's a fixed version:

import random

coin_heads, coin_tails, times_flipped = 0, 0, 0

timesflipped = 0  # <-- here's what I added.
while timesflipped < 100:
	coin_flips = random.randrange( 2 )
	if coin_flips == 0:
		coin_heads += 1
	else:
		coin_tails += 1
	timesflipped += 1
	

print "Out of 100 flips, " + str(coin_heads) + " were heads and " + str(coin_tails) + " were tails."

The above is the same, except that I declared timesflipped = 0 right before evaluating the while loop. Hope this helped!

vegaseat commented: thanks for spending your time on this! +11
shadwickman 159 Posting Pro in Training

Why not keep a list of lists for responses corresponding to each user answer? Such as:

responses = [
    ["Q1, A", "Q1, B", "Q1, C" ],
    ["Q2, A", "Q2, B", "Q2, C" ],
    ["Q3, A", "Q3, B", "Q3, C" ]
]

and if you collect the user input as an integer, and you keep track of the number of the question you're asking (0, 1, 2, etc.) you can just call up the appropriate response to print by saying:

print responses[questionNumber][userAnswer]

Collecting the user input could use a function that returns an integer from 0 to 2 (inclusive) depending on if the user gave A, B, or C as the answer. Here's an example:

def getAnswer():
    while 1:
        ans = raw_input( "Enter answer:  " ).upper()
        if ans == "A": return 0
        elif ans == "B": return 1
        elif ans == "C": return 2

answer = getAnswer()  # equals 0, 1, or 2 corresponding to A, B, C

There are better ways of writing this, but the above is a very basic and easy to understand form of it. The above does account for A, B or C not being given at all, and loops until it receives one of the letters.

The above isn't much, but it should be a good start on this sort of project. This sounds exactly like a homework assignment, so as such, I won't be giving any more in-depth tips, but I'll try to help a bit more if needed.

sneekula commented: I like your style +6
shadwickman 159 Posting Pro in Training

All I was able to find was this article, but from what it says, it sounds risky as each platform/distro is quite different and difficult.
http://lists.wxwidgets.org/pipermail/wxpython-users/2007-March/062720.html

lllllIllIlllI commented: Great post, helped, worked, brilliant +1