lrh9 95 Posting Whiz in Training

Databases might be applicable. Python has the sqlite3 module for simple databases. Do you have some examples of the data you want to work with?

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

It depends on the structure of your file and what you are trying to do.

To update (read and write) a file you usually open it with mode r+.

From your other posts, I can see you are making a game. Are you trying to develop a save system or game data system? There may be better alternatives than the manipulations you are attempting. You should also read a good tutorial on file steams.

lrh9 95 Posting Whiz in Training

I think that if someone takes the time to get an abstract overview of programming languages, he or she finds that programming languages are relatively simple and those featuring the same programming paradigms are quite similar.

It's a fascinating subject. When a person studies a specific programming language, he or she is primarily learning how to code with that language. That person does not necessarily learn transferable knowledge and skills. For instance, comments in Python are slightly different from comments in C or C++.

Look at the Python tutorial and the C++ tutorial side by side.

Both teach the user:
How to begin coding.
About variables and data types.
About control flow.
About functions.
About complex data structures.
About memory.
About input/output.
About classes.
About errors and exceptions.

They diverge on language specific features. Python features a section on modules, and C++ has information on pointers.

If a person can learn one, he or she can learn the other. However, studying one probably won't make a person a better programmer in the other. Knowing one may make the other easier to learn, because the person all ready knows the concepts. For instance, he or she will know what a function is. That person will only need to learn how to implement it in the language.

That is why I recommend that beginning programmers learn Python. In Python they do …

lrh9 95 Posting Whiz in Training

Sounds like an application for collections.Counter.

First do the Python tutorial to learn the Python language.

http://docs.python.org/py3k/tutorial/index.html

Then review the library reference to get an overview of Python's built in functionality.

http://docs.python.org/py3k/library/index.html

Finally, read the documentation for collections and try to write your program.

http://docs.python.org/py3k/library/collections.html

We can't help you if you don't do the work.

vegaseat commented: very nicely said +15
lrh9 95 Posting Whiz in Training

"Production" is a word that refers to source or code used for practical application. It means you're writing a real program that someone, somewhere is going to use to do something.

"blist" is a third party module. People write third party modules for other people to use to make programs. Third party modules can offer things the standard Python distribution doesn't offer, such as additional functionality or better performance.

I suggested bisect thinking you wanted to write a program using just what is available in a standard Python distribution, but pyTony is right that if you have differing requirements such as a more performant implementation you should research which third party options are available and decide which - if any - to use.

TrustyTony commented: Nice signature links and nice explanation. +13
lrh9 95 Posting Whiz in Training

I ended up checking out Panda3D's task and event system. Thanks for the replies.

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

It's also possible to bin items to a collection like a set or list.

This technique can bin items without key collisions.

import collections

data = ((5.639792, 1.36),
        (4.844813, 1.89),
        (4.809105, 2.33),
        (3.954150, 2.69),
        (2.924234, 3.42),
        (1.532669, 4.50),
        (0.000000, 5.63))

bucket = collections.defaultdict(list)
for each in data:
    bucket[int((each[1]))].append(each[0])
print(bucket)
lrh9 95 Posting Whiz in Training

Begin a class repository and write one every so often. They can come in handy more often than you think. Pick a single real world or virtual object and write a class for it.

vegaseat commented: good idea +14
Gribouillis commented: Interesting idea +13
lrh9 95 Posting Whiz in Training

Use an online resource that makes it easy to retrieve data. Many sites have an API (Application Programming Interface) that allow programs to retrieve data with a few function calls.

For instance, Yahoo lets you retrieve a csv file of stock quotes with a url.
You can use the urllib.retrieve module to retrieve the data, and the csv module to process it.

#Written for and tested on Python 3.1.
import csv
import urllib.request

def yahoo_quotes_csv_url(tickers):
    return ''.join(('http://finance.yahoo.com/d/quotes.csv?s=',
                    '+'.join(tickers),
                    '&f=snl1'))

if __name__ == '__main__':
    tickers = ('GOOG', 'AAPL')
    url = yahoo_quotes_csv_url(tickers)
    print(url)
    urllib.request.urlretrieve(url, 'quotes.csv')
    reader = csv.reader(open('quotes.csv'))
    for row in reader:
        #row[0]=ticker, row[1]=company, float(row[2])=value
        print(row)

Different sites will provide different interfaces and have more data, but if you remember to read the documentation about retrieving data and if you remember to use the right modules you can use it.

Thisisnotanid commented: Very helpful! +2
lrh9 95 Posting Whiz in Training

I like to code a simple switch using True or False. When you need to flip the switch then changing state is as easy as:

#Switch in the 'off' state
state = False
#Flip the switch
state = not state
#Switch is now in the 'on' state
#Flip again
state = not state
#Switch is back 'off'
vegaseat commented: agree +13
lrh9 95 Posting Whiz in Training

Lardmeister, that is a good use of itertools.permutations to find string permutations.

I just want to explicitly caution others that when working with permutations you should use generators like Lardmeister is. The number of permutations of a string is the factorial of its length. Don't attempt to store all of the permutations in a collection. You can quickly run out of memory.

Lardmeister commented: good point here +6
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

That will break if the user entered nothing.

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

I was looking for a high level language to program a.i. in and after trying AutoHotkey I decided to try Python since it provides standard library support for more processing primitives. (Threading and multiprocessing.)

lrh9 95 Posting Whiz in Training
# -*- coding: utf-8 -*-

##Copyright © 2010 Larry Haskins
##This program is free software: you can redistribute it and/or modify
##it under the terms of the GNU General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.

##This program is distributed in the hope that it will be useful,
##but WITHOUT ANY WARRANTY; without even the implied warranty of
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##GNU General Public License for more details.

##You should have received a copy of the GNU General Public License
##along with this program.  If not, see <http://www.gnu.org/licenses/>.

import collections
import copy
import itertools
from random import shuffle

#Lookup tables are faster than functions for string operations.
PLURALS = {'ace': 'aces',
           'king': 'kings',
           'queen': 'queens',
           'jack': 'jacks',
           'ten': 'tens',
           'nine': 'nines',
           'eight': 'eights',
           'seven': 'sevens',
           'six': 'sixes',
           'five': 'fives',
           'four': 'fours',
           'three': 'threes',
           'two': 'twos',
           'spade': 'spades',
           'heart': 'hearts',
           'diamond': 'diamonds',
           'club': 'clubs'}

"""Next three functions use certain attributes as keys to group items
according to the value of that key."""
def pigeonholed_by_suit(cards):
    suits_ = {}
    for suit in suits:
        suits_[suit] = []
    for card in cards:
        suits_[card.suit].append(card)
    return suits_

def pigeonholed_by_rank(cards):
    ranks_ = collections.OrderedDict()
    for rank in ranks:
        ranks_[rank] = []
    for card in cards:
        ranks_[card.rank].append(card)
    return ranks_

def pigeonholed_by_len(values):
    lens = collections.OrderedDict()
    for i in (0, 1, 2, 3, 4):
        lens[i] = []
    for value in values:
        lens[len(value)].append(value)
    return lens    

"""Helper function for checking …
lrh9 95 Posting Whiz in Training

I'd typecast during the comparison. Good luck.

lrh9 95 Posting Whiz in Training

It's bad because it isn't friendly to other objects that act like your class.

You should use hasattr instead to check that the object you are working with is appropriate. That way as long as the object has the required attribute or method it will work with your code as well as your own objects. (If it is a method it still must accept the appropriate arguments.)

class YourClass:

    def required_method(self):
        pass

class MyClass:

    def required_method(self):
        pass

yourobj = YourClass()
myobj = MyClass()

isinstance(yourobj, YourClass)    #True
isinstance(myobj, YourClass)    #False
hasattr(yourobj, 'required_method')    #True
hasattr(myobj, 'required_method')    #True
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

Make an irc bot to connect to an irc server and channel and respond to users in various ways.

Download irclib to get some code to start from.

http://irclib.bitlbee.org/

If you can, get a copy of IRC Hacks published by O'Reilly.

http://www.jibble.org/irchacks/

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

First, Python doesn't use semicolons to terminate lines of code.

P.S. Someone beat me to it, but maybe I can help a little more.

A fairly quick way to accomplish what you wish to accomplish is to create a set of the string and then check the length of that.

A set is a container for unique, hashable objects. (Strings are hashable because they are immutable, but hashability and mutability are really tangent to this discussion.)

Typecasting a string to a set will automatically filter out duplicate characters with three caveats. First, it won't preserve the order of the characters as they were in the original string. Second, lowercase letters and uppercase letters are represented using different values meaning a set won't filter out a capital 'T' if there is a lowercase 't' or vice versa. Third, it will also count whitespace meaning if it has spaces the set will have one space or if it has newlines the set will have one newline.

However, the first doesn't appear to be an issue for you and the second can be remedied using a string's 'lower' method. The third can be remedied by using a string's 'replace' method to replace any whitespace with a no character of two single quotes.

I'll give you an example using code like yours.

from string import whitespace

def char_items(string, count_caps = False, count_whitespace = False):
    if not count_caps:
        string = string.lower()
    if not count_whitespace:
        """
        Inefficient.
        Strings are …
d5e5 commented: Good supplemental info. After reading your answer I see mine had an unnecessary step. +1
lrh9 95 Posting Whiz in Training

@Ene Uran

While anyone is free to use any directory they wish, I think the common directory to store third party modules and packages in is the "site-packages" directory in the "lib" directory.

Even better, you don't have to append the "site-packages" directory to the search path which means that any import statement should be able to find your modules and packages.

lrh9 95 Posting Whiz in Training

Create an operating system prototype/emulator in Python. You might research into various operating systems to get an idea for what to implement.

Things you can implement:

  • A login.
  • A shell system.
  • A explorer system (If done well enough, you can disable your own explorer process at startup and execute your own.)
  • A desktop window.
  • A web browser. (A project in and of itself.)
  • A plain text editor. (Another individual project.)
  • A control panel/system configuration set of utilities.
lrh9 95 Posting Whiz in Training

There is a variable in the os module called linesep that represents the line separator in text files.

In order to get the bytes for the linesep all you have to do is "os.linesep.encode()".

lrh9 95 Posting Whiz in Training

One thing that I'm very glad I learned to do as a beginner and still use today - even though I'm probably still a beginner - is to have a basic file with code that is used more often than not in the script. I can copy this file each time I want to create a script and have several things I'd normally want to do in a polished script all ready done.

I call my file "base.py".

#!/usr/bin/env python

version = '3.1.1'

def main():
    pass

if __name__ is "__main__":
    main()

The first line is called a "shebang" I think. I'm a Windows user, but as I understand it having this line in a script allows Linux users to execute the script more easily than if it wasn't included. Having the line doesn't alter program execution so it isn't necessary, but I do it out of consideration for Linux users when I publish code.

The variable "version" does not represent the script's version, but it is the version of Python I wrote the script in. I do this out of consideration for users who might be using different versions of Python.

The 'if __name__ is "__main__":' idiom allows a script to function as an executable script or a module. If the program is executed as a script, the __name__ attribute is "__main__" and the "main" function is called. However, if the script is imported then this code is not executed. The pass statement in …

lrh9 95 Posting Whiz in Training

There is no such thing as "separation of church and state".

What about the fact that there is no mention of a deity anywhere in the United States Constitution?

Or the fact that Thomas Jefferson - author of the Declaration of Independence, founding father, and third President of these United States - coined the phrase in a letter written to Danbury Baptists, in which he referred to the First Amendment to the United States Constitution as creating a "wall of separation" between church and state.

The United States Supreme Court also recognizes the separation of church and state. First in 1878, and then in a series of cases starting in 1947.

And contrary to the argument that only the government is prohibited from interfering in religion, the Treaty of Tripoli has stated, and I quote:

As the Government of the United States of America is not, in any sense, founded on the Christian religion;

This is a strong indication that the founding fathers never intended the United States to be a Christian nation, especially considering that it was drafted by George Washington's administration and Thomas Jefferson.

In addition, the Constitution is a living document that has always traditionally been considered open to the reasonable interpretation of law makers and judges. While there are no explicit words "separation of church and state" in the Constitution, the Establishment clause along with what I've mentioned above as well as the opinions of the founding fathers have been considered …

lrh9 95 Posting Whiz in Training

U.S. Military Weapons Inscribed With Secret 'Jesus' Bible Codes
Pentagon Supplier for Rifle Sights Says It Has 'Always' Added New Testament References

http://abcnews.go.com/Blotter/us-military-weapons-inscribed-secret-jesus-bible-codes/story?id=9575794

I saw this. I think this is wrong.

lrh9 95 Posting Whiz in Training

1) Thread titles should be descriptive. A generic request for help is not descriptive.

2) This appears to be homework. Part of homework is to take the initiative to learn for yourself. That means you must complete the essential portions of the assignment for yourself. No one will do it for you.

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

I was wondering if anyone knows of any resources about building a custom importer.

I've found this: http://www.doughellmann.com/PyMOTW/sys/imports.html.

I am also aware of PEP 302 and PEP 369 and imp and importlib.

Are there any other resources I might need?

lrh9 95 Posting Whiz in Training

Actually, a frame alone is enough to produce the effect I desired. I'm sorry to waste space and time.

Here's the code.

#!/usr/bin/env python
#Python 3.1

from tkinter import *

master = Tk()
nameentryframe = Frame(master, background = 'BLACK', borderwidth = 1, relief = SUNKEN)
nameentry = Entry(nameentryframe)
nameentryframe.pack()
nameentry.pack()

master.mainloop()
lrh9 95 Posting Whiz in Training

The class if functionally correct. A few things I'd like to suggest.

1) As far as I'm aware, protected names usually begin with one underscore.

self._name #"Correct"
self.__name #"Incorrect"

2) I'd probably put an underscore in front of "get_name" and "set_name" and use the property to handle attribute access.

3) Whenever I consider using the "==" comparison operator, I consider using "is".

if name is "":

is much clearer than

if name == "":

In fact, I'd probably import string earlier in the module and do this:

import string

if name is not in string.whitespace:

The python module string contains string constants that might be useful to you. It will be a great help to you if you know the python standard library, or are at least able to navigate it.

4) There is another syntax for a property involving class decorators. You don't need to understand how class decorators work at the moment, but you should be able to recognize that this:

@property
def name(self):
    return self._name

@name.setter
def name(self, value):
    self._name = value

is the same as:

def _get_name(self):
    return self._name

def _set_name(self, value):
    self._name = value

name = property(_get_name, _set_name)
lrh9 95 Posting Whiz in Training

Isn't it the join() method of the thread?

lrh9 95 Posting Whiz in Training

I'm just wondering if it is possible to import a module as an object attribute.

The basic description of what I want to accomplish is that I'm creating a software agent object. This agent will have a set of abilities (functions), but I don't know what these are ahead of time. Logically, it is simplest to encapsulate these abilities in a module, and then have the agent import it. Then it would have access to these abilities. This would also allow it to use the standard modules or any other previously developed modules. Another benefit is that each object has its own namespace for modules. If all modules were in the global namespace of the program, every agent would have access to it. This is something I do not want.

Now I obviously don't know how things work, so I resorted to perhaps one of the worse ways to code something: experimentation. The first thing I tried was to simply attempt to import a module as an object attribute. That failed. Then I checked to ensure that a module could indeed be imported to a local namespace. So I defined a class method that imported the random module, printed the local dictionary, and printed a random number. Then to ensure that the module was only accessible by that function, and not globally, I tried to print a random number in the main function. random was in the local dictionary for the test function, and it printed a random …

lrh9 95 Posting Whiz in Training

Here's what I came up with.

#!/usr/bin/env python

import random

class pool(list):
    
    def rand_index(self):
        length = len(self)
        return random.randint(0, length - 1)

    def unique_rand(self):
        return self.pop(self.rand_index())

def main():
    print("""Prints each element in a sequence at random once and only once.""")
    my_pool = pool("AaBbCcDd")
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    try:
        print(my_pool.unique_rand())
    except:
        print("The ninth attempt failed because it attempted to remove a ninth element from a sequence of eight elements that had eight previous removals.")
    
    
if __name__ == "__main__":
    main()
lrh9 95 Posting Whiz in Training

Hello. I'm lrh9, a new user. This is my first time visiting these forums. I've posted on www.programmingforums.org under the same user name.

I'm a hobbyist and amateur computer programmer. My primary languages are C++, a custom scripting language for Windows named AutoHotkey, and Python which I've just started out learning but am determined to learn. I learned some Visual Basic 6 - my first programming language -in high school, but I've forgotten most of it. I've also used programming features of graphing calculators to a small extent.

I think I'm naturally inclined to computer programming. When I was a child, I'd often assemble and disassemble objects to learn how they worked. Legos were one of my favorite toys for instance. It was a relatively easy transition from assembling and disassembling physical components to assembling and disassembling virtual components.

I was introduced to computing technologies when my mother bought me my first video gaming system, the Sega Genesis. It was only natural that when I encountered computer games, I wanted a computer. My grandmother purchased my first computer in the late 1990s, my second around 2005, and I assembled a computer using parts purchased with my own money this year.

My current interest in software development is general purpose artificial intelligence. I am an amateur a.i. researcher, with a focus in computer learning. After surveying approaches to artificial intelligence last year, I decided that I'd pursue the child machine hypothesis as it made the …