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?

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 ...

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

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.

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 [URL="

Sounds like an application for collections.Counter.

First do the Python tutorial to learn the Python language.

[url]http://docs.python.org/py3k/tutorial/index.html[/url]

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

[url]http://docs.python.org/py3k/library/index.html[/url]

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

[url]http://docs.python.org/py3k/library/collections.html[/url]

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

vegaseat commented: very nicely said +15

"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.

pyTony commented: Nice signature links and nice explanation. +13

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

[COLOR="Green"]creature.metabolism[/COLOR]
[COLOR="Red"]creature.metabolsim[/COLOR]

vegaseat commented: upvoted for Griboullis (was downvote error) +15
Gribouillis commented: spot on -3

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

This technique can bin items without key collisions.

[code=PYTHON]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)
[/code]

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.

Gribouillis commented: Interesting idea +13
vegaseat commented: good idea +14

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.

[code=Python]#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)

[/code]

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

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:

[code=PYTHON]#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'[/code]
vegaseat commented: agree +13

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

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.

[url]http://www.chompchomp.com/terms/concretenoun.htm[/url]

That will break if the user entered nothing.

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

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.)

[code=Python]# -- 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_bysuit(cards):
suits
= {}
for suit in suits:
suits[suit] = []
for card in cards:
suits
[card.suit].append(card)
return suits_

def pigeonholed_byrank(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 a wheel.
(Straight ...

I'd typecast during the comparison. Good luck.

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.)

[code]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[/code]

Try relative imports.

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

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.

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.

[url]http://irclib.bitlbee.org/[/url]

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

[url]http://www.jibble.org/irchacks/[/url]

[QUOTE=lrh9;1263299]Don't separate the user id from the entry.

[code]import csv, contextlib

usernfo = {}

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

print(usernfo)[/code][/QUOTE]

Fixed.

Don't separate the user id from the entry.

[code]import csv, contextlib

usernfo = {}

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

print(usernfo)[/code]

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.

[code=Python]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 immutable so replacing each whitespace character takes ...

d5e5 commented: Good supplemental info. After reading your answer I see mine had an unnecessary step. +1

@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.

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:

[LIST]
[]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.
[/LIST]

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()".

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".

[code=Python]#!/usr/bin/env python

version = '3.1.1'

def main():
pass

if name is "main":
main()
[/code]

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 the "main" function is necessary ...