shadwickman 159 Posting Pro in Training

Well for starters, your List construction will cause an error as there is a comma after the 3rd string, which is the last index so it shouldn't have the comma after it.

Here's an example I think will help:

mylist = [
	'abcdefg',
	'hijklmno',
	'pqrstuv'
]
listindex = 2
charindex = 2

temp = mylist[listindex]
mylist[listindex] = temp[:charindex] + 'd' + temp[charindex + 1:]

Which changes the "r" in the third string in the list to a "d".
It's simple slicing: current string up to (but not including) the character's index, plus the new character, plus everything after the character's index. Then it reassigns that to the list's index.

It may look fine to update "temp" with the newly sliced string, but "temp" is only a copy of the original list index I made to make the slicing expression look cleaner. You have to actually modify the list's index for the change to be assigned back in.

Hope that helped!

shadwickman 159 Posting Pro in Training

That's weird.... so import pygame is causing the "module not found" error?
Other than trying to install the wrong version of pygame for your python installation, I don't know what could be wrong.
What OS are you using? A GNU/Linux distro or Windows?

shadwickman 159 Posting Pro in Training

Yes, evstevemd, but if there is a raw_input statement waiting for the user to type "break" or "exit", it will hold up the rest of the script from executing until it has received input. He wants the loop to run while also waiting for user input in case they want to break it. That's why I suggested a thread.

shadwickman 159 Posting Pro in Training

My first thought would be to use a separate thread to handle a function waiting for user input. Then if it receives the signal to quit, it terminates the program. You can use the threading module to accomplish this.

I don't know if this is considered to be a no no in terms of "good programming" but I think it would work. Anyone else have a good idea?

shadwickman 159 Posting Pro in Training

The constructor has two underscores on either side of the name. def __init__(self) .

shadwickman 159 Posting Pro in Training

Um... you provided absolutely no information. So as of right now, I can't answer your question. What are you using as a 2D engine for Python? etc.

shadwickman 159 Posting Pro in Training

Oh wow, I'm sorry. I completely forgot about raw_input returning them as strings. You can run each index through the int() function, changing it to an integer, but a problem arises if someone enters something other than digits. Let me give two solutions...

This one is simple, yet throws an error if the user enters any non-digit characters.

b = raw_input("Enter numbers separated by a space: ").split(" ")
for i, n in enumerate(b):
    b[i] = int(n)

# can also be written as:
# b = [int(i) for i in raw_input("Enter numbers separated by a space: ").split(" ")]

This one loops if there are any non-digits, and handles the error they present.

while 1:
    end = True  # end loop unless error
    b = raw_input("Enter numbers separated by a space: ").split(" ")
    for i, n in enumerate(b):
        try:
            b[i] = int(n)  # will cause error if i can't be converted to int
        except:
            print "Non-numerical input found. Only enter numbers!"
            end = False
    if end:
        break
shadwickman 159 Posting Pro in Training

If you want, you can have it take input and split it at every space, or comma, etc:

b = raw_input("Enter numbers separated by a space: ").split(" ")

It works like this:

>>>Enter numbers separated by a space: 3 4 10
>>>b
>>>[3,4,10]
shadwickman 159 Posting Pro in Training

siddhant3s, you may notice that your option has in fact removed the three 10s from list a, when you only input one 10. In the question, the other two 10s are left in list a after only one 10 is input.

shadwickman 159 Posting Pro in Training

How about:

for number in b:
    if number in a:
        a.remove(number)

That should go through each number in b and remove it from a if it appears in a...

shadwickman 159 Posting Pro in Training

You understand the problem it contains right? rand = random.randint(0,2) can get either 0, 1, or 2. Then you have it check for a 1 as heads, and the else statement catches the 0 or 2 as a tails. Therefore, you have 2 chances for a tails for every one chance for a heads.

shadwickman 159 Posting Pro in Training

So just a question... do you know any Python code at all? Because the actual program wouldn't be too hard. Regardless of the extension you can read the contents of the file and parse them in Python, then just output them to a new file with the .asc extension.

shadwickman 159 Posting Pro in Training

Oh I didn't notice that problem he had in his code before. Nice catch there woooee!

shadwickman 159 Posting Pro in Training

I'm perfectly willing to help, but only after he makes some effort himself.

shadwickman 159 Posting Pro in Training

Well I changed the code so that it makes the quad list full of blank objs by default, then updates it with the numbers from the values passed to it if possible. This is the result:

class obj:
          def __init__(self,cargo=None,next=None):
                    self.next = next
                    self.cargo = cargo
class circular:
          # added 'values' list as a param, for the obj list.
          def __init__(self, values=[], next=None):
                    self.next = next
                    self.quad = [obj(),obj(),obj(),obj()] # set blank first
                    if len(values) > 0:  # set object list to values in list
                              self.quad = [ ]
                              for val in values:
                                        self.quad.append(obj(val))
                    self.setlink()  # call linking func
          def setlink(self):
                    for i in range(3):
                              self.quad[i].next = self.quad[i+1]
                    self.quad[3].next = self.quad[0]
>>>a = circular([1, 2, 3, 4])
>>>print a.quad[0].next.cargo
2

It seems to be working for me. And what's this about forgetting to set the link each time? Because when you initialize the circular class, the link gets set without you having to call it...

Unless you mean that if you edit one of the quad values, that it doesn't update the variables in the other quads. In which case you could just write a function on the circular class that you call in order to assign a new value to an index of the quad, and then it afterwards updates the links on its own. So instead of using the regular assignment operator =, you could call the function with the new value passed instead.

shadwickman 159 Posting Pro in Training

Yeah, so I take it that is the content of a file or something he wants to read using a Python program so he can find the lines in red, and then change them.... I think?

shadwickman 159 Posting Pro in Training

Maybe if you just set it so that the function call to 'setlink' happens at the end of the '__init__' function. This will make the function call for 'setlink' happen automatically, but you will need to pass the cargo values to the class on initialization, otherwise it won't have the correct obj() instances in the list before linking.

class obj:
          def __init__(self,cargo=None,next=None):
                    self.next = next
                    self.cargo = cargo
class circular:
          # added 'values' list as a param, for the obj list.
          def __init__(self, values=[], next=None):
                    self.next = next
                    if len(values) == 0:  # if no values passed...
                              self.quad = [obj(),obj(),obj(),obj()]
                    else:  # set object list to values in list
                              for val in values:
                                        self.quad.append(obj(val))
                    self.setlink()  # call linking func
          def setlink(self):
                    for i in range(3):
                              self.quad[i].next = self.quad[i+1]
                    self.quad[3].next = self.quad[0]
>>>>a = circular([1, 2, 3, 4])
>>>print a.quad[0].next.cargo

If you ever change the values in the obj list, then you'd need to call the 'setlink' function manually again, but this should work for the purpose you illustrated in your post.
Hopefully that does the trick! :D

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

Is it just me or does this make no sense? Just to clarify, the code you posted between your "code tag starts/ends here" tags is in what language? Obviously it's not Python, so what is this "correct format" you're taling about?
Are you asking for a program to be written in Python in order to read out the filenames from this block of code above? I just need a better description of what it is you're asking. Thanks.

shadwickman 159 Posting Pro in Training

So if I read that correctly, you need a way of turning "12345.9876" into a float without using the float() function, but by making your own?

shadwickman 159 Posting Pro in Training

I started out a few days ago, and one of the first things I did was follow Narue's guide (a member here on DaniWeb). Here's the PDF of it:
http://www.daniweb.com/forums/attachment.php?attachmentid=1765&d=1142611276

It uses NASM and GCC (for Windows, use can use the MinGW binaries for that).

Narue's little guide was a good starting point for me for Assembly, and it definitely helped a lot with getting the basics down.

P.S. once you download NASM and install MinGW, an easy way to make the commands 'gcc' and 'nasm' function in the DOS cmd prompt as sort of global commands, you can add the folders containing 'nasm.exe' and 'gcc.exe' into your Windows PATH variable.

shadwickman 159 Posting Pro in Training

And? Sorry if it seems obvious, but can you at least put a bit of depth into that response?
Running your script yields something like:

376.87  #what I input.
12345.9876376  #int_string afterwards

So what exactly do you mean by 'a lexer to read decimal numbers'? As in floats (numbers with a decimal point), or as in numbers with a base of 10 (as opposed to hex or binary numbers)?

shadwickman 159 Posting Pro in Training

Please use CODE tags! It's pretty much essential for Python so I can tell if your indentation is off. That being said, I put your code in tags for you:

myinput = raw_input() # Grab raw keyboard input
int_string = "12345.9876"

for c in myinput :
    if c.isdigit (): # state : digit
        int_string += c
    else: # state : accept
        break

Refrain from using 'input' as a variable name as it's already the name of a Python function; I changed 'input' to 'myinput'.

What exactly is it you need to do to? Sorry, I'm just a little confused with your description about state-transition diagrams and such. Why are you appending the digit characters from the user input into the int_string?
I'm just not fully sure what it is you're wanting to accomplish. The above code should work fine, but to what end?

shadwickman 159 Posting Pro in Training

Everyone else is right. Please show some effort of your own; attempt the problem and then post the code you have so far. We can try to point out hints from there.

P.S. Remember to use CODE tags. We need to see your indentation.

shadwickman 159 Posting Pro in Training

So, your explanation is really difficult to follow, but I think you mean something about raising an error if it finds a blank tag in the Mp3tag object? Like an instance of it having a blank 'title' string? If that's the case then you could just write a function to check each of those tags and then if it detects one as blank, execute the appropriate code you want for dealing with it.
Sorry if I'm way off with what you're actually wanting to do. I've reread your description/explanation of it, but I'm having trouble understanding precisely what you want; it seems a bit vague to me. Sorry if I couldn't be of help.

shadwickman 159 Posting Pro in Training

Yes, Arrorn, but she said she was at a basic level, and it sounds like this program isn't really going to need much future expansion. It's a simple probability program consisting of very few lines. And even if it did, rewriting it requires pretty much no time to do. Plus, I know your code isn't very advanced either, but at a basic level, most people have trouble handling such large blocks of code together.
I hope the new program works for you Stephanie953! You should try to work your way through Arrorn's code though, it's a good resource too, and a great example of another step up.

shadwickman 159 Posting Pro in Training

What exactly do you want returned by the __len__ function? The length of the genre string, the title string, album string, etc? Or do you want it to return something to do with some of those strings being blank?

Also, as far as I know, len() is for strings, but I could be off about that. Like len('Hello World') returns 11.

P.S. you should restructure your Mp3tag class I think. Just like:

class Mp3tag:
    def __init__( self ):
        self.error = ""
        self.date = ""
        self.trackNumber = ""
        self.artist = ""
        self.title = ""
        self.album = ""
        self.genre = ""
        self.numFiles = ""

Whenever you initialize a Mp3tag object, the function __init__ gets called. Self just refers to the class itself, so in other functions within the class, you can access the variable title by writing self.title .

shadwickman 159 Posting Pro in Training

EDIT: The below isn't too helpful as vegaseat posted a better (and full) verison.

What do you mean by

d={"flight":T34712, From:ABERDEEN, scheduled 0800, remark landed}

The other keys need to be enclosed in quotes to, so that

d['flight'] = 'T34712'
d['from'] = 'ABERDEEN'
#etc...

The best solution I think is paulthom12345's suggestion. Although, I'm still confused about the set-up you seem to want. There's a better way to organize it, such as one list with each index a separate flight, and each of those indices holding a dict with the keys for 'flight', 'from', 'scheduled', 'remark', etc. Like:

flights = [
    { 'flight': 'T34712', 'from': 'ABERDEEN', 'scheduled': 0800, 'remark': 'LANDED 08:00 ' },
    { 'flight': 'BE171', 'from': 'SOUTHAMPTON', 'scheduled': 0820, 'remark': 'LANDED 08:07 ' }
]

OR

flights = {
    'T34712': { 'from': 'ABERDEEN', 'scheduled': 0800, 'remark': 'LANDED 08:00 ' },
    'BE171': { 'from': 'SOUTHAMPTON', 'scheduled': 0820, 'remark': 'LANDED 08:07 ' }
]

using the flight number as a key in the dict, and it's value as a dict with the other info.

shadwickman 159 Posting Pro in Training

I don't know about awk, but I what would happen if you changed

ot, et = ex.communicate('''abc
def
ghi
jkl
mno''')

to

ot, et = ex.communicate('abc\ndef\nghi\njkl\nmno')

It just didn't seem to like something about the triple-quoted string. But of course I could be completely off seeing as I don't know anything about awk, but I thought I could suggest that one thing :P
Tell me if that change fixes the errors!

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

There are multiple issues with your code. The first one to catch my attention was

def area (math.sqrt (s(s-a)(s-b)(s-c))

Why did you say 'def'? That defines a function, not any other data type. Not only that, but you didn't even close the final bracket pair, you left it hanging unclosed. Lastly (still with this one line), you need to multiply 's' and '(s-a)(s-b)(s-c)', but that requires an asterisk * between them, like s*(s-a)*(s-b)*(s-c) . Putting the 's' right against the first parenthesis works in mathematics, but in python, putting parenthesis right after a variable calls the function that variable points to, and 's' is not a function, it's a float. So here's how that one line should read as:


Secondly, the last line is wrong.

print area

This will cause an error. Declaring 'area' inside of the function 'heron' means that 'area' is within that function's scope, and can't be accessed from outside of the function. If you want to get the value of area from the function, then return that value, and store it to a variable when you make the call to the 'heron' function.

Finally, you never actually made a call to the 'heron' function. You need to do this and pass the parameters (s1, s2, s3), and store the value it returns (the area). So the line

print area

becomes

area = heron( s1, s2, s3 )

Here's what the final code should look like:

s1 = …
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

Thanks woooee, I didn't really think about floating point inputs for the first program, just plain old integer input.

shadwickman 159 Posting Pro in Training

Wrapping your code in the BB code tags is usually essential (keeps indentation), so remember to do it next time.

First Program
For the first program, raw_input returns a string, therefore when comparing the values, you're comparing something like "3" + "5" < "9" (i.e. "35" < "9"). This is why it's returning False each time. You need to take the inputs and turn them into integers, so the result would be 3 + 5 < 9 . To do this, you can do:

a = int( raw_input("Length of first side?") )
# example:   raw_input returns "9", then int() turns it into 9, and then it's stored in a

Plus, print isTriangle won't work, it needs to be print isTriangle( a, b, c ) .
And, finally, you can condense your function by writing:

def isTriangle(a, b, c):
	if ( a + b < c ) or ( a + c < b ) or ( b + c < a ):
		return 0
	else:
		return 1

(As a side note, importing the math module in this program is useless, as no functions or constants from it are being used.)

Second Program
The indentation has been lost due to not using CODE tags. As you (should) know, indentation in Python is essential. One thing I do notice that is odd is the line with print halfPerimiter . All this would end up doing is printing the object (pointer/address? I'm not sure of the …

shadwickman 159 Posting Pro in Training

Why don't you try using a wxListBox set with the style flag for allowing only a single item to be selected at once? It's a simple solution if you're using wxPython.

shadwickman 159 Posting Pro in Training

I can try to help with #2. First, change im, im1, im2, etc to strings, so that the command for im looks like im = "image.crop(box)" . The value should be a string. When you want to call that specific command use exec im1 etc for each command.

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
shadwickman 159 Posting Pro in Training

Oh, ok. The reason why I stick with 2.5 is because of WConio, and I haven't been able to find out how to get it to work with 2.6 yet. I'd need to modify the .pyd file for it, but I have no idea how to do that (the file looks like gibberish to me when I open it in Windows).
http://newcenturycomputers.net/projects/wconio.html

shadwickman 159 Posting Pro in Training

why don't you upgrade to 2.5? I'm curious if there is special feature or just you love it!

Sorry, I don't understand you. What are you trying to say about Python 2.5? It's what I use, even though Python 2.6 is out now (or the early releases for 3.0).

shadwickman 159 Posting Pro in Training

Ah, brilliant! I didn't know that the exec function could be used to execute a python script... thanks - I learned something new! :D

shadwickman 159 Posting Pro in Training

Ah, I didn't know that myself either. Is there more of a general definition of it? I get what the example does, but I'm just curious about the sort of extent/functions that this term can be used to/for.

shadwickman 159 Posting Pro in Training

I don't know if there's a "proper" method of doing this, but I have the code look something like this:

# function to call
def myFunction():
    print "code here"
    return True


# main program
redo = True
while redo == True:
    redo = myFunction()
    # if myFunction does not return True, then the code will end.

That's a pretty basic, although most likely not "proper" or "correct" way of doing it. Hope that helped!

shadwickman 159 Posting Pro in Training

I've tried that but I get an error saying that the list index is out of range, I'm guessing because everytime you delete a letter, the range changes.

Yes, but it's easy to fix. Here's the updated code:

let = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]

import random

for i in range(3):
    pos = random.randint(0,len(let))
    letter = let[pos]
    print letter,

All I did was change the line with the random function so that it went from 0 to the length of the array, therefore making sure indices that don't exist anymore don't get called.

shadwickman 159 Posting Pro in Training

You could always just add del let[ pos ] after that letter has been printed, thus deleting that letter from the list. It'll never be selected again.

shadwickman 159 Posting Pro in Training

The % operator is used to return the remainder if one number were to be divided by another. So 5 % 2 would return 1, because 2 goes into 5 twice, with 1 left over. Another example is 10 % 2 which would return 2. 4 goes in twice, with 2 left over.
So x % n == 0 just means that there is no remainder (it fits perfectly).
Hope that helped!

shadwickman 159 Posting Pro in Training

Thanks for pointing that out! Must be the sun was shining in my eyes. I corrected it

No problems! And thanks for this other post you found by shanenin; it has restored my interesting in small-scale logic games (which I had no idea where/how to start work on before).

shadwickman 159 Posting Pro in Training

It's just that the link that Vegaseat posted didn't include the last ')' in it. Here's the corrected one:

http://en.literateprograms.org/Tic_Tac_Toe_(Python)

shadwickman 159 Posting Pro in Training

Wow, I've been wanting to do something like this for a while. Thanks for the link Vegaseat!

shadwickman 159 Posting Pro in Training

Originally, I started Java at age 11 and C++ at age 13, and at the time, I found the strict and very rigid declarations/style of Java and C++ to be a little confusing and overwhelming.
After finding Python, I just came to love its simplicity compared to these other two languages, and the more relaxed form. I just find Python to be much more flexible; but this is a personal thing, as I don't make professional or exceedingly complex programs. All these languages have pros and cons (first one that comes to mind is the speed of C++ vs. Python - where C++ wins in most cases), but I myself found it easier to work with a more lax language when experimenting with ideas I've never tried before (namely an A.I.).
I've still been having fair trouble with a real artificial intelligence, but I haven't worked on anything dealing with that in a few months. This thread makes me want to get back into that though haha!
As Vegaseat mentioned, Python's string processing/manipulation is quite extensive, and I love that. That is also one of the reasons that I've stuck with Python mainly, and dictionaries are incredibly useful. Not sure if that fully answered your question, evstevemd!

shadwickman 159 Posting Pro in Training

Why don't you just loop a function that opens each file one at a time and writes the processed information to the corresponding output file? Have an array of the .cvs files and for every one in the array, call the processing/writing function.