lrh9 95 Posting Whiz in Training

This just doesn't sound like a good idea. If it were me, I'd specify interfaces and let other programmers work out how to fulfill those interfaces.

For instance, the sum function expects an iterable of summable objects. It doesn't care if a programmer stores his or her data in a csv file, json file, shelve, or whatever. It's up to the programmer to get the data he or she wants to use in the correct structure; he or she has to fulfill the interface.

It's better. You don't have to worry about what other programmers are doing. You don't have to write code to fulfill the interface for every situation. You can just specify the interface and let other programmers fulfill it. It's more robust. They can handle situations that you can't foresee. It keeps your code lean.

P.S. When I asked what your case was, I was talking about the project that you are writing this system for. I assume you are writing this to address something in another project? If you aren't, you are "solving" a "problem" that doesn't need to be solved.

lrh9 95 Posting Whiz in Training

So you are pretty much trying to make functions and methods that behave differently depending on an argument's type or behavior? That's not a very good idea. It's very difficult to ensure that you can appropriately handle all types or behaviors in one function or method. Even if you can, you make it very difficult for yourself or other developers.

If your function or method returns a copy when the object is immutable, what does it return when the object is mutable? The same object? Now imagine you call this function and have to work with the return value. You pretty much have to do the same mutability checking you did in your function or method to ensure you handle the return value properly. This introduces more code, more overhead, and more points where your software can break.

I don't know any standard solutions. What is your specific case? Do you have any code?

I ran into this problem myself when I was working on some trivial neural network code. I wanted to use either a pair of sequences or a pair of mappings to represent a pair of neuron inputs and corresponding neuron weights. If the inputs was a sequence I would use the index of each input to look up the corresponding weight, or if the inputs was a mapping I would use the key of each input to look up the corresponding weight. At first I decided to use the collections abstract base classes to check if …

lrh9 95 Posting Whiz in Training

Why do you need to check an object's mutability? Sounds like you need to solve a different problem or use a different solution. Technically you could try to make whatever changes you wanted to make and catch any AttributeError exceptions, but it still seems funny. So...?

hughesadam_87 commented: . +3
lrh9 95 Posting Whiz in Training

You can write a module that can also act as a script by using the idiom:

if __name__ == '__main__':
    pass

Importing a module and then executing the main body of that module is indicative of a design problem, but can be accomplished by wrapping the main body in a main function.

#module.py

def main():
    pass

if __name__ == '__main__':
    main()

#script.py

import module

module.main()
lrh9 95 Posting Whiz in Training

http://en.wikipedia.org/wiki/Pseudorandom_number_generator

There is even a link to an algorithm with a psuedocode implementation.

Personally, I think you should find something else to work on. I think reimplementing established algorithms will provide little educational value.

lrh9 95 Posting Whiz in Training

http://en.wikipedia.org/wiki/There's_more_than_one_way_to_do_it

lrh9 95 Posting Whiz in Training

I've never used it, but the subprocess module may be what you need. It seems to feature a function that will start a subprocess and wait for the subprocess exit code. If the exit code is non-zero then the function will raise an exception.

lrh9 95 Posting Whiz in Training

creature.metabolism
creature.metabolsim

Gribouillis commented: spot on -3
vegaseat commented: upvoted for Griboullis (was downvote error) +15
lrh9 95 Posting Whiz in Training

Hm. It seems like bisect assumes ascending order. I hadn't thought of descending order.

You can either write your own function or you can keep your data in ascending order until you need descending order.

It's possible to get a reverse iterator over a sequence using the function reversed.
A slice with a negative step will have reversed elements. Example: L[::-1]

lrh9 95 Posting Whiz in Training

I do think you should use bisect.

It works.

If you can be sure that your value will fall between two indices, you can specify a lower bound and an upper bound to restrict the search. (Thus reducing search times.)

The implementation isn't much different from your own.

def bisect_right(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e <= x, and all e in
    a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
    insert just after the rightmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]: hi = mid
        else: lo = mid+1
    return lo
lrh9 95 Posting Whiz in Training

If you can, check out the fractions module.

http://docs.python.org/library/fractions.html#module-fractions

The source is included with Python. If you can locate it, you can see how the author(s) did it.

lrh9 95 Posting Whiz in Training

I can't tell if this is an exercise.

Even if it is, the bisect source can still serve as an inspiration and guideline.

It's strange how people don't realize that a lot of things are in the standard module library and the source is available for most of it.

lrh9 95 Posting Whiz in Training

Isn't this what the bisect module is for?

lrh9 95 Posting Whiz in Training

An object is just an abstraction of data and functions.

An object has attributes (data) and methods (functions that interact with its attributes).

A class is a blueprint describing the objects created from it.

When you write a class you are 'declaring' a class.

An object created from a class is an 'instance' of that class.

Objects are most useful when the systems you are modeling in your program can be abstracted as objects.

Anything you can refer to with a noun is a potential candidate.

I recommend that people learning object-oriented programming model concrete objects.

http://www.chompchomp.com/terms/concretenoun.htm

lrh9 95 Posting Whiz in Training

I don't think there is a module or package providing key press event functionality for the console.

If you want user input, you should use the function raw_input in 2.x and input in 3.x.

lrh9 95 Posting Whiz in Training

Do you want to do a graphical application or a console application?

lrh9 95 Posting Whiz in Training

That will break if the user entered nothing.

lrh9 95 Posting Whiz in Training

I make my user input loops follow this pattern:

#Start a loop that will run indefinitely.
while True:
    i = input("Prompt: ")
    #Here I do my input checking. In this example it checks that i isn't an empty string.
    if i:
        #Break out of the indefinite loop.
        break
lrh9 95 Posting Whiz in Training

I learned it from someone at #python on irc.freenode.net

lrh9 95 Posting Whiz in Training

I like using dictionaries for my multidimensional containers using coordinate tuples as keys. It's not a conventional approach, but despite any disadvantages it has some advantages. For very small or very large coordinates, it has a memory advantage because "coordinates" don't need to exist until they are assigned to. The fact that coordinates can be any hashable objects also presents some interesting options.

griswolf commented: A nice bright light went off over my head. Thanks. +1
lrh9 95 Posting Whiz in Training

Seems to me like it would be good to use both concurrently. I've all ready written a few scripts that can run with both 2.x and 3.x.

Python packages and modules are open source. If you ever want them for a new version you can always refactor the old version. In fact, I think their creators and the community at large would be appreciative of such an effort.

Doing so would be a great opportunity to prove that you are not only a programmer capable of implementing useful Python packages and modules but that you are also well versed in the relevant Python versions.

lrh9 95 Posting Whiz in Training

God I want to smack the creators of some of those courses upside the head with a thick book.

lrh9 95 Posting Whiz in Training

Couple of problems. The first is poor class implementation.

It's OK to make your class without attribute getters and setters. You can access instance attributes by referring to the attributes themselves.

class Car:

    def __init__(self, year):
        self.year = year

mycar = Car(1999)
mycar.year

The second problem with implementation is that you require a speed argument to accelerate and decelerate the car, but inside of those methods you accelerate or decelerate by a constant of 5. Is that desired behavior, or would you rather to accelerate or decelerate by the amount passed as the argument?

The third problem is with your script's structure. You try to create the car before you've gotten the user's input. You must assign identifiers before you can use them elsewhere.

year = raw_input('What year is your car? ')
mycar = car.Car(year)
print mycar.year

You did a decent job with the class for a beginner. Don't get discouraged. Good luck.

lrh9 95 Posting Whiz in Training

Typecasting the numbers to a string doesn't make much sense to me, but whatever.

You are mistakenly using the sample function.

Here's what you want to do.

import random

def make_secret(numdigits):
    a = []
    for i in range(numdigits):
        a.append(str(random.randrange(0, 10)))
    return a
lrh9 95 Posting Whiz in Training

A technical term for creating a class is 'declare'.

When you create a class you are declaring a class, and when you see a class in code it is a class declaration. Just thought you might want to know the lingo.

b

lrh9 95 Posting Whiz in Training

A quick hack would be something like this:

def run_async(fnc):
    def newfnc(*args, **kwargs):
        thread = threading.Thread(target=fnc, args = args, kwargs = kwargs)
        thread.start()
    return newfnc

@run_async
def on_mode(self, connection, event):
    if event.arguments() [ 0 ] == "-v":
    vname = event.arguments() [ 1 ]
    self.connection.mode(channel + " +v", vname)
lrh9 95 Posting Whiz in Training

Python isn't a bad language, even when it comes to threading.

The 'vibe' I'm getting from the modules you are using is that the objects and process of creating and operating a bot are overly complex.

There isn't much that can be done about that except a rewrite with different design principles, philosophies, and use specifications in mind. (I'm working on an irc bot library at the moment. When I publish the source hopefully it will be more suited for your use and for other people.)

But in the meantime we must make do with what we have here.

Seems like to me you need to add your global handler to an event and that should do the trick.

Doesn't the on_mode method you defined in the bot do what you want?

If so when you initiate your bot you should do something like this I think.

self.add_global_handler("mode", self.on_mode)

P.S. I posted after you said you needed to add threads.

lrh9 95 Posting Whiz in Training

If you don't mind me asking, what are the "ircbot" and "irclib" modules or packages you imported, and where could we acquire them or view the source?

lrh9 95 Posting Whiz in Training

I'm talking about dotted relative imports.

lrh9 95 Posting Whiz in Training

Try relative imports.

http://www.python.org/dev/peps/pep-0328/#guido-s-decision

Seem like just the thing. I've used them. They permit you to import modules from a relative parent package.

They're hard to figure out though. The documentation is somewhat lacking so you might have to tinker until you get it right.

lrh9 95 Posting Whiz in Training

Don't separate the user id from the entry.

import csv, contextlib

usernfo = {}

with contextlib.closing(open(data.csv)) as ifile:
    for entry in csv.DictReader(ifile):
        usernfo[entry['id']] = entry

print(usernfo)

Fixed.

lrh9 95 Posting Whiz in Training

Don't separate the user id from the entry.

import csv, contextlib

usernfo = {}

with contextlib.closing(open()) as ifile:
    for entry in csv.DictReader(ifile):
        usernfo[entry['id']] = entry

print(usernfo)
lrh9 95 Posting Whiz in Training

Nice catch.

Python's builtin rounding function can help with that. Trouble is determining the number of significant digits for rounding.

lrh9 95 Posting Whiz in Training

That's not what I would do. Two integer objects are equal if and only if their numeric value is the same and unequal if and only if their numeric value is different. That isn't dependent upon their existence as an object. Looking at the '__eq__' method on the shapes it checks only that both shape objects are the same type and that their dimensions are equal. Two shapes are equal if and only if they are the same type and the same size. Two shapes are unequal if and only if they are a different type or they have a different size.

But the decision isn't up to me. That's just what I would think if I were in the poster's position.

lrh9 95 Posting Whiz in Training

P.S. I skimmed over the problem set. I'm not seeing any stipulation that the set needs to be sortable. Where did you see it?

lrh9 95 Posting Whiz in Training

You are also right about '__repr__'. However, for this assignment the set's '__str__' method does need to be overwritten.

OK. Hash returns an integer value representing an object. Two objects with the same value will return the same hash value, but the opposite is not necessarily true. Two objects with the same hash value may not necessarily have the same value. However, since set uses this value it must be accurate enough for the purposes of set.

I'm thinking that if I implement a '__hash__' method on each shape then set will work properly. I'm thinking that since tuples are hashable I should make each shape return the hash value for the tuple of its data.

class Square(Shape):

    def __hash__(self):
        return hash((type(self), self.side))

class Circle(Shape):

    def __hash__(self):
        return hash((type(self), self.radius))

I tested sets composed of shape object's with this method. They worked as specified. Only shapes with unique values were added to the set.

from ps9 import Square, Circle

myset = set([Square(9.5), Circle(4.2), Square(9.5)])
print(myset)

That should result in a representation of the contents. One circle object and one square object. (I overrode the '__repr__' methods to ensure that they had the values I specified. They did.)

lrh9 95 Posting Whiz in Training

I made another error. ps9 does have '__str__' methods for some of the classes.

I should have tested what I was suggesting. It didn't work for me. I assumed it would but I made an ass out of myself.

I'm getting a different bug though. My interpreter is complaining that the Circle type is not hashable.

Maybe fixing this would solve the problem? I'll get back when I learn what hashing is all about.

P.S. Nice work importing all from ps9. Me having to type ps9 over and over should have been a good indication to import the names that I needed.

lrh9 95 Posting Whiz in Training

To express my opinion frankly, the instructions are stupid. I'll explain why later.

However, let me see if I can help.

We're looking at Problem 2?

In this problem you are implementing a custom container class to hold shape objects. The main purposes of this container are to ensure that each shape is unique, provide a method to return a string representation of the shapes in the container, and to provide a method to iterate over the shapes in the container.

You won't have to worry about creating a list of several element tuples. Each shape is represented by a shape object. The shape classes are in ps9.py. When you add a shape to the container you'll be adding a shape object not the shape's data.

If you were making a program you would import the ps9 module to provide access to the shape classes. Then you can add a shape to a ShapeSet. (Reading the ps9 module some more I see that the ShapeSet should be in the ps9 module, but let's keep it in the script for the moment.)

import ps9

class ShapeSet:

    def addShape(self, sh):
        #Add shape 'sh' to the container after ensuring that it is unique.
        pass

myShapeSet = ShapeSet()
mySquare = ps9.Square(9.5)
myShapeSet.addShape(mySquare)

Luckily each shape has a '__eq__' method you can call to compare it to another shape. (And you won't have to bother to ensure that each shape is of the same type. The '__eq__' method of …

lrh9 95 Posting Whiz in Training

Gribouillis makes some good suggestions.

As for storing the data to a file there are really two standard, commonplace options that I think are suited to this.

I'd either pickle or marshal the object.

pickle and marshal can store and retrieve a Python object on file.

Both are similar, but pickle creates a file that will work across platforms and marshal creates a file that will only work on a type of system it is created on.

I read another post you have, and if structured text is necessary I'd try to devise a solution using json, but I'm not familiar with it so I can't help you there.

lrh9 95 Posting Whiz in Training

That's going to be a tougher one if I think you are asking for a procedure that can work on lists with mixed items in them down to an arbitrary number of levels.

In a real application you could probably find a better way of representing the data and use simpler programming logic to access it.

lrh9 95 Posting Whiz in Training

Actually, this code is wrong. I retested it, and I noticed an error. This code when run prints "This is my class both times."

I'll get to the bottom of it.

P.S. I realize what it is. The new_method definition doesn't create a new function each time it is called, its name is merely rebound to the new function.

lrh9 95 Posting Whiz in Training

It was a ***** to do, but I believe I figured out how to decorate each and every method in a class by decorating only the class itself.

def method_decorator(class_declaration):
    class NewClass():
        pass
    for key in class_declaration.__dict__:
        if hasattr(class_declaration.__dict__[key], '__call__'):
            def new_method(*args, **kwargs):
                print("This is a decorator.") #Replace this with your code.
                class_declaration.__dict__[key](*args, **kwargs)
            setattr(NewClass, str(key), new_method)
    return NewClass

@method_decorator
class MyClass(object):

    def __init__(self):
        print("This is my class.")

    def method(self):
        print("This is my method.")

x = MyClass()
x.method()
Gribouillis commented: A class decorator is the solution. +2
lrh9 95 Posting Whiz in Training

mmmm, i would use decorators as well... i was just thinking if you didnt want to have to type that arbitraryFunction() that you probably wouldn't want to type @arbitraryDecorator

I didn't catch that reply.

If you used decorators you would have to copy and paste the decorator for each method. I can understand the problem there.

The more interesting trick would be to create a decorator that could handle each and every method in a class as per the user's specifications.

I think it might be possible. I tested some code and I discovered that a decorator can also be applied to a class.

Now what I was thinking is that this decorator could loop through each callable name in the class dictionary and then manipulate this name the way a normal decorator does. It might be simple for a basic class, but a problem that occurred to me was if the class inherits other classes, and also the issue of method resolution order.

lrh9 95 Posting Whiz in Training

Try using decorators.

They are a language feature in at least Python 3.0 that perform code on a function or method defined after them. Optionally, they can return a new function that will be assigned to the newly defined function. There are function decorators and class decorators. I haven't studied them in depth, so I could be wrong about some things or there could be more to them, but they seem to be a solution to your problem.

Here's the code using a function decorator in case I wanted "Hello, world!" printed whenever one of my functions is called.

def say_hello(function):
    def new_function():
        print("Hello, world!")
        function()
    return new_function

@say_hello
def myfunc():
    print("This is my function.")

@say_hello
def mysecondfunc():
    print("This is my second function.")

myfunc()
mysecondfunc()

The resulting output should be:

Hello, world!
This is my function.
Hello, world!
This is my second function.

The first function is the decorator. It takes only one argument, the function it is to modify or use.

The "@say_hello" is the decorator syntax. It indicates to the interpreter which function or class I want to call to use or modify the function.

Inside the first function, it defines a new function that prints "Hello, world!" and executes the function it took as an argument. I should mention that I think that if it is used on functions with arguments, this new function definition should accept *args and **kwargs in order to support your function arguments.

lrh9 95 Posting Whiz in Training

I have heard of this and understand this. Although I doubt I'll be importing my module...

Understandable, but something I do is keep a basic python file that I can copy and edit on the fly.

#!/usr/bin/env python

def main():
    pass

if __name__ == "__main__":
    main()

The line at the beginning is a comment for the courtesy of Linux users. It is called a shebang, and it lets the Linux OS know where the Python interpreter is so that when a Linux user executes the file it is automatically opened with the interpreter. It does not affect people who use other operating systems.

You don't have to remove the pass statement in main() to add code. Simply write after it. I include the pass statement to prevent an exception if the script is executed as a program, even if there is no main() code.

I don't think the main() function is exactly Pythonic, but I use it so that I don't pollute the global namespace.

To each their own I guess.

lrh9 95 Posting Whiz in Training

Whitespace is recommended to make Python code clearer. Traditionally there is no space between related lines of code. A single line is recommended between different code sections and function definitions. Two lines are recommended between class definitions and I use two lines in method declarations if the methods are different enough to be logically separated. (For instance, I'll write my methods for accessing one property, and then I'll enter two blank lines and type more methods for accessing another property.)

I might have considered importing just the specific function I needed from pygame.mixer, or importing all functions and attributes.

I don't think you've been introduced to Python's object oriented features yet, but I probably would have used a few classes too to simplify some things.

Also, "if __name__ == '__main__'" is understood to be a standard Python idiom that you should research.

There are a few questions I have.

When you add a sound to the playlist, you automatically play it. Is that the functionality you desire?

lrh9 95 Posting Whiz in Training

I spotted this and thought it might help answer your questions. Especially section 24.1.5.

http://docs.python.org/library/tkinter.html

lrh9 95 Posting Whiz in Training

What do you mean by "Standardize how it draws widgets"? Do you mean that tkinter or Tk uses an API of the system telling the system to draw a certain widget instead of drawing the widget on its own?

Possibly. I don't know. Tkinter could also define its own API.

lrh9 95 Posting Whiz in Training

So how, then, does Tk manage to provide windows which look 'native' for the different operating systems?

I don't know the way it technically does it, but my best guess is that it uses an API - application programming interface - to standardize how it draws widgets without being aware of operating system details.

http://en.wikipedia.org/wiki/Application_programming_interface

lrh9 95 Posting Whiz in Training

If it interests you, I think that the code for Python's IDLE is available in the Python library. If it is, you can edit it to your liking.