shadwickman 159 Posting Pro in Training

I'm still not entirely sure why sell result cannot start as an empty list. And why we add and then delete a zero. I'll play with it and figure it out. Thanks.

I have the line if SellResult[-1] < bn inside the BuyList for loop, because that way it will only cycle through the SellList to compare the current buy value IF the current buy value is more than the previous sell value (SellResult[-1] = last number in SellResult).
If SellResult starts as an empty list, then calling the last index of it will result in an error of "list index out of range". All I did was start it off with a zero so that this if statement wouldn't cause errors with the SellResult right off the bat, then I just removed that zero at the end.
You can write it so that you don't need to start SellResult off with a value in it, but I did just so the code would look simpler.

Here's that other way with SellResult starting off blank:

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

BuyResult = []
SellResult = []


def cycleSellList(bn):
    global BuyResult, SellResult
    for sn in SellList:
        if sn > bn:
            BuyResult.append(bn)
            SellResult.append(sn)
            break
    

for bn in BuyList:
    if SellResult:  # if it contains values
        if SellResult[-1] < bn:  # last number in it < bn
            cycleSellList(bn)
    else:  # no values in SellResult yet.
        cycleSellList(bn)
"""
My result:
1:7, 9:10, 11:12
"""

Or if you don't want …

shadwickman 159 Posting Pro in Training

Ok, that makes more sense once you said that they correspond to time periods. Before I just couldn't see a logical pattern to what you were matching up.

This code works, but it's kinda messy and hacked together. Not the best option but you can modify it from here. BuyResult and SellResult are the resulting lists with the correct output.

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

BuyResult = []
# if SellResult don't contain something to start,
# then the 'SellResult[-1] < bn' will throw an error.
SellResult = [0]

for bn in BuyList:
    if SellResult[-1] < bn:
        for sn in SellList:
            if sn > bn:
                BuyResult.append(bn)
                SellResult.append(sn)
                break
# remove that starting 0 from SellResult
SellResult = SellResult[1:]

"""
My result:
1:7, 9:10, 11:12
"""

Tell me if you need clarification for the code.

shadwickman 159 Posting Pro in Training

So you want to remove any buy numbers that are below any of the sell numbers?

shadwickman 159 Posting Pro in Training

Thanks Ene. But I'm trying to get the low numbers in the buy list and attach it to the first available number greater than that low number in the sell list.

So then why isn't this the solution:
(buy:sell)
1:7, 2:8, 3:10, 4:12, 9:15

That takes the low numbers in the buy list and attaches them to higher numbers in the sell list.

In your solution, you only listed 1:7, 9:10, 11:12. What happened to the "low numbers" of the buy list, as in 2, 3, and 4?

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

I'm curious why you have the lines

length_of_buy_list = []
length_of_sell_list = []
...
length_of_buy_list = len(BuyList)
length_of_sell_list = len(SellList)

You declared them as empty lists, then changed them to an integer of the list length...

And also, you store these lengths at the beginning but you don't change them throughout the script even though you have things like del BuyList[x] which will subtract from that list's length. Just don't use these variables you made and use len(SellList) and len(BuyList) everywhere else instead. That'll make sure that the real length of the lists is counted.

Do that and it may fix your range error. Tell me what result you get from that.

EDIT:
You can also change your conditionals from

if length_of_buy_list < length_of_sell_list:
    myrange = length_of_buy_list
elif length_of_buy_list > length_of_sell_list:
    myrange = length_of_sell_list
else:
    myrange = length_of_buy_list

to

if length_of_buy_list > length_of_sell_list:
    myrange = length_of_sell_list
else:
    myrange = length_of_buy_list

because that sets "myrange" to the length of the buy list if its length is less than or equal to the sell list's length. Just a cleaner looking way of writing it.

shadwickman 159 Posting Pro in Training

Doesn't the windows installer come with it?

EDIT:
for Ubuntu, it should be sudo apt-get install idle-python3.0

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

Well, if you ran what you posted, nothing will happen. You defined these functions and classes but you haven't actually done anything with them. None of these get called during the execution of the script.

shadwickman 159 Posting Pro in Training

Well, there's probably a much easier way of writing the data to the screen in a nice table, as all the conditionals you have in the header_content function don't look too pleasant, even though they get the stuff done.
I wrote a quick table function that accepts a list containing other lists as the indices, and prints the list out into the headings it receives, and makes sure the spacing is kept nice. You could fix it up to fit your script better, or just use it as a template to see how I went about doing it. Maybe if you want, make it spread the data over a fixed-width of 80 characters or something. Anyways, here's the function:

import sys

'''
Display a list of data, where list[0] is a list of headers, and each index after that contains a row of data, corresponding to the order of the headers.
'''
def display_table(matrix, colspace=4, sepchar='-', capheaders=True):

    # set-up variables
    headers = matrix[0]
    data = matrix[1:]
    spacer = ' ' * colspace
    if sepchar:  # if there is a separator
        if len(sepchar) > 1:  # if more than one character
            sepchar = sepchar[0]  # only keep first one
    colwidths = [ 0 for i in range(len(headers)) ]  # init all max lengths to 0
    
    # read lines and store longest values for each column
    for row in matrix:
        for index, item in enumerate(row):
            length = len(str(item))
            if colwidths[index] < length:
                colwidths[index] = length
        
    # write headers
    for index, …
shadwickman 159 Posting Pro in Training

Ok, I couldn't edit the above post, but here's the steps to follow:

1. You'll need to add the repository key to the api's list of trusted keys in order to get the wxpython packages. To do this, first install curl by using the command sudo apt-get install curl . Let this install, and then proceed to add the key via curl [url]http://apt.wxwidgets.org/key.asc[/url] | sudo apt-key add - .

2. Go to System > Administration > Software Sources and click on the Third-Party Software tab. Click the "Add" button and put deb [url]http://apt.wxwidgets.org/[/url] hardy-wx main then click "Add Source". Then, click "Add" again and this time, put in deb-src [url]http://apt.wxwidgets.org/[/url] hardy-wx main . When you've done this, click the "Close" button in the lower right. It should ask about updating/refreshing or downloading new packages, so let it do it that.

3. Update your local packages with sudo apt-get update .

4. Get and install wxpython and its dependencies with sudo apt-get install python-wxgtk2.8 python-wxtools wx2.8-i18n .

Once this is all done, try the command python and once in the interactive shell, type import wx . If it does this without any errors, then you've successfully got it! Hope that helped! :D

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

Thanks for calling me out on that. I got used to using tabs when I started out with Python, but switched to the 4-space standard. I'm still struggling with this though, as I am too used to being able to hit backspace once to return to the indentation of the outer level, so about a week ago I switched Notepad++ back to use tabs.

shadwickman 159 Posting Pro in Training

Just as a late clarification, lists are fairly different in Python from Arrays in C. I find lists much more pleasant to use, because:
- they are dynamically resizable, and no set length needs to be declared upon initialization, but you can't assign a value to an index past the current length of the string without appending it to update the list to the new length.
- they can contain any type of objects, i.e. mixed contents. One index may be a string, the next an int, then tuple, etc.

Anyways, you can read the documentation on lists and their built-in functions here if you'd like to know more.

shadwickman 159 Posting Pro in Training

I don't have time to fully check through all the above code right now, but if you're interested in the guidelines for standardizing Python code, you can have a read through PEP 8.

And as just a speculation, if you're importing this module to use in another program, but don't want certain global variables (as you have opted to use here) accessible by the module it is imported to, then name them with one underscore preceeding their name. Like _array_studentDetails .

shadwickman 159 Posting Pro in Training

It works - I get only one rectangle showing with it.

import pygame
from pygame.locals import *
from sys import exit

pygame.init()
screen=pygame.display.set_mode((640,480),0,32)
while 1:
	for event in pygame.event.get():
		if event.type == QUIT:
			exit()

	screen.fill((0,0,0)) # put it here
	pygame.draw.rect(screen,(0,255,0),(50,50,100,100))
	screen.blit(screen,(50,50))
	pygame.display.flip()
	pygame.display.update()

You need it called before every blit for the rectangle.

shadwickman 159 Posting Pro in Training

I use wxGlade when I'm not making the interface purely by coding, and I'd definitely suggest it. It did take me a little messing and tinkering around with to get the hang of it, but it's definitely worth the effort.

Edit:
Here's the wxGlade user manual:
http://wxglade.sourceforge.net/manual/index.html

and tutorial:
http://wxglade.sourceforge.net/tutorial.php

shadwickman 159 Posting Pro in Training

You haven't re-blitted the entire screen, i.e. refilled every pixel of it in order to fully wipe + refresh it. For this, add a screen.fill((0,0,0)) before you re-blit the rectangle. This will cover the screen in black again before redrawing the new rectangle. Hope that helps!

shadwickman 159 Posting Pro in Training

Can't you just keep track of a virtual camera position tuple, then when everything blits to the pygame display, adjust them by the camera's position?

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

There's always pygame if you want to check that out, and the PIL mixed with a GUI toolkit would also be a good bet. wxPython is my toolkit of choice.
Your idea of "dynamic" image rotation simply would be a while loop continuously redrawing the image with a new rotation based upon the CPU data it's being fed.

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

I know that this is slightly unnecessary but I can't stand the sight of the above code. I don't know if your colour codes are right (I didn't test them), but this is just a much cleaner way of writing your little program. Just putting the simplicity of Python to good use, that's all.

# this works, but I just don't know if the colour codes are correct...
import os, time

colourcodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']
colournames = ['black', 'blue', 'green', 'aqua', 'red', 'purple', 'yellow', 'white', 'grey', 'light blue', 'light green', 'light aqua', 'light red', 'light purple', 'light yellow', 'bright white']

def color(i):
	i = i.lower()
	return colourcodes[colournames.index(i)]
	
print '\n'.join([c.title() for c in colournames])

txc = raw_input('\nWhat colour do you want the text?  ')
bgc = raw_input('\nWhat colour do you want the background?  ')
a = color(bgc)
b = color(txc)
c = 'color %s%s' % (a, b)

os.system(c)
print '\n' + c
time.sleep(3)
shadwickman 159 Posting Pro in Training

So what you mean is that you have a sort of 'map' saved as an image as either black or white - white being spaces available to move to, and black being blocked sections (obstacles)?

If so, my idea would be to use the Python Imaging Library (PIL) in order to read the RGB or color data of the image and store it. Then, whenever the player moves, compare the location they would then be at to the data from the map image. Disallow the move if it would go into one of the 'black' areas of the map image's data.

There are probably other ways of doing this, but this is what first popped into my mind. Hope it's a good start!

shadwickman 159 Posting Pro in Training

What exactly is the filename of the file you're trying to import? It shouldn't be "file" because that's already a reserved word in Python, so it'll cause problems. And you wrote "From", yet it should be all lowercase ("from"). Drop the .py extension of whatever file you're importing too, so if I wanted to import "otherfile.py", I'd do it like so:

# keeps all aspects of otherfile accessible only by calling them through otherfile, such as: otherfile.myvariable
import otherfile
# OR
# imports everything from otherfile directly into the current file
from otherfile import *

Hope that cleared it up.

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

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

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

I'm not entirely sure what you mean by a 'grid', but if you only want to accept numeric input, you can use a function like this to return it:

def getNum():
    while True:
        n = raw_input('Enter a number:')
        try:
            n = float(n)  # or int(n) if you want an integer
            return n
        except:
            print 'Enter a number!'

As for the second part of your question, I'm not fully sure what that 'grid' is, so can you elaborate on it or show some code please? Thanks.

shadwickman 159 Posting Pro in Training

I've never tried this, nor has it crossed my mind. But it seems like it would be a great idea for sharing simple Python programs with friends without making them install Python first (damn you, Windows!). A HUGE online undertaking using Python is EVE-Online, which is a MMORPG on an incredible scale. Regardless of my current lack on knowledge, I shall start looking up whatever I can find about this, as I'm very interested myself now. I'll post back if I find anything.

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

Ah, I found the government site for Canada and such, and they actually have the cities' weather information available through XML files, so I was able to parse that to get the info I wanted. Thanks for getting me started there! I hadn't though about the .gov site and such.

shadwickman 159 Posting Pro in Training

This technically isn't fully a Python-related question, but I couldn't find a better place to post it than here. I'm just curious about how to get/update weather information from the internet... like say that sidebar gadget in Vista that updates the weather and temperature from some online-source. The problem is, I have no clue where/how this is obtained. I just wanted to integrate it into a Python app, and if anyone knows anything about this and could get me pointed in the right direction that would be amazing. Thanks! :D

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

Just a quick question, is this Python 3.0 or 2.6?

EDIT: nevermind, that was the stupidest question...

shadwickman 159 Posting Pro in Training

Yeah, as soon as the script is done in the command prompt, it'll exit. So put something like waiting for input at the end so that it pauses the program.

Alternatively, you could always make a batch (.bat ) file to run instead with the lines:

python "path\to\my\file.py"
pause

That'll make the DOS prompt pause after running your script.

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?