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?

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.

Builtins are the way to do it, but in your function you reset s to zero each loop because it is inside the loop. It needs to be set to zero before the loop.

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

At present the survey requires only a username to participate. Aren't you concerned that someone might vote using other usernames?

If you want to have a save system, you would be better off using an object serialization or data persistence module. You should read the documentation for the pickle and shelve modules.

This little example guess the number game shows a way to keep a record of the total number of correct guesses from one game to another. Try running it and play until you get a couple of guesses right. Then close the game. Then run it again and play a few more times. You should see that your total score is the sum of the correct guesses the first time you played and the correct guesses you made the second time you played.

import random
import shelve

if __name__ == '__main__':
    save ='guess.sav')
    score = 0
    while True:
        choice = input('Guess a number from 1 to 10? (Y)es/(N)o: ')
        if choice.lower() in ('yes', 'y'):
            secret = random.randint(1, 10)
            while True:
                    guess = int(input('Guess the number from 1 to 10! Your guess: '))
                    if guess == secret:
                        score += 1
                        print('Sorry! The number was {0}.'.format(secret))
        elif choice.lower() in ('no', 'n'):
    print('Your score this session is {0}!'.format(score))
        save['score'] += score
    except KeyError:
        save['score'] = score
    print('Your score all time is {0}!'.format(save['score']))

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 flagged this as a bad post because the code is wrong. I should have tested it more thoroughly. It fails to send messages appropriately. It will respond to pings correctly, but if I write code to send a notice or a private message, it will take a matter of minutes to send any data, and it is only partially transmitted. Possible problems I have considered are blocking problems, asyncore timeout problems, and buffered sending problems. I haven't been able to resolve this issue on my own, so I am examining other irc bot implementations for a possible solution

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

if __name__ == '__main__':

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.

def main():

if __name__ == '__main__':

import module


The Python standard library features a csv module for CSV file reading and writing. Read the module documentation to learn how to use it.

I'd use a dictionary or collections.OrderedDict to associate each unique key with a list of values.

I had been wanting to write an IRC bot with asynchronous IO for a while. My bot responds to pings, but can be extended by defining functions and registering them to get called when the bot receives certain commands. My bot uses the RFC 1459 USER command and parameters, but can be made to comply with RFC 2812 by replacing my on_connect function with a compliant one. Here is what I wrote based on the asyncore and asynchat modules:

[code=PYTHON]import asynchat
import asyncore
import collections
import socket

def parse(data):
data = data.split(b' ')
if data[0].startswith(b':'): #prefix present
prefix = data[0][1:]
data = data[1:]
prefix = None
command = data[0]
data = b' '.join(data[1:])
if data.startswith(b':'): #only trailing parameter
parameters = [data[1:]]
data = data.split(b' :')
if len(data) > 1: #trailing parameter present
trailing = b' :'.join(data[1:])
trailing = None
parameters = data[0].split(b' ') #regular parameters
if trailing is not None:
parameters.append(trailing) #add trailing parameter to regular parameters
return prefix, command, parameters

class Connection(asynchat.async_chat):

def __init__(self, nick, user, realname, host, port=6667):
    self.nick = nick
    self.user = user
    self.realname = realname
    self.address = (host, port)
    self.received = list()
    self.handlers = collections.defaultdict(set)

def collect_incoming_data(self, data):

def found_terminator(self):
    data = b''.join(self.received).rstrip(b'\r')
    del self.received[:]
    prefix, command, parameters = parse(data)
        for handler in self.handlers[command]:
            handler(self, prefix, parameters)
    except Exception as exception:
        for handler in self.handlers[exception]:
            handler(self, exception)

def message(self, string):
    string = ''.join((string, '\r\n'))

def establish(self):
    self.create_socket(socket.AF_INET, socket.SOCK_STREAM)

#We use a "plugin" oriented system so we can ...

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

Task 1 is probably something that could be accomplished using system utilities if you were willing to research the options. I bet you could write a command line script or something to do it.

Task 2 can have many approaches. If the program in question supports the right command line options then it would be a similar thing. However, if you want to do complex tasks that require interaction with the program interface... not many options except a macro scripting language like AutoHotkey.


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.

I am doing some hobby coding regarding neural networks, and I was wondering if this is a correct and good use of abstract base classes or not.

[code=PYTHON]import abc
import collections
import math
import weakref

class AbstractNeuron(metaclass=abc.ABCMeta):

def __init__(self, weights, f=math.tanh, bias=1, biasWeight=0):
    self.weights = weights
    self.f = f
    self.bias = bias
    self.biasWeight = biasWeight

def __call__(self, inputs):
    return self.activate(inputs)

def activate(self, inputs):
    raise NotImplementedError

class MappingNeuron(AbstractNeuron):

def __init__(self, weights=None, f=math.tanh, bias=1, biasWeight=0):
    if weights is None:
        weights = collections.defaultdict(int)
    super().__init__(weights, f, bias, biasWeight)

def activate(self, inputs):
    return self.f(math.fsum(inputs[key] * self.weights[key] for key in inputs.keys()) + self.bias * self.biasWeight)

class WeakNeuron(MappingNeuron):

def __init__(self, weights=None, f=math.tanh, bias=1, biasWeight=0):
    if weights is None:
        weights = weakref.WeakKeyDictionary()
    super().__init__(weights, f, bias, biasWeight)

class SequenceNeuron(AbstractNeuron):

def __init__(self, weights, f=math.tanh, bias=1, biasWeight=0):
    super().__init__(weights, f, bias, biasWeight)

def activate(self, inputs):
    return self.f(math.fsum(inputs[i] * weight for i, weight in enumerate(self.weights)) + self.bias * self.biasWeight)


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.

No. Put it after "words=aline.split()".
Also, move "count={}" to above "for aline in infile:".

Each word in words should be a key.

[code=PYTHON]for word in words:
if word not in count:
count[word] = 1
count[word] += 1[/code]

"count" needs to be a dictionary.
"line.split" is a function so it should be "line.split()".
"line.split" returns an iterable of words. You need to use a for loop to iterate over each word and increment its counter.

Not a bad start.

You are counting words, so your keys are going to be words and the values are going to be integers.

If a word isn't present in the dictionary you need to add it. Otherwise you need to increment the counter.

[code=PYTHON]if word not in counter:
counter[word] = 1
counter[word] += 1[/code]

You have enough of a grasp to do it. The only thing you need to do is learn about string methods so when you decide how you want to handle stuff like whitespace and punctuation you know what to do.

Sounds like an application for collections.Counter.

First do the Python tutorial to learn the Python language.


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


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


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

vegaseat commented: very nicely said +15

Long time no update. I've been studying finite state machines and it has me thinking that some of this might be better solved using finite state machines. The basic idea is that you have a collection of cards you want to find a hand for. You can iterate over the cards and update the state of the hand as you go. When you get to the end of the collection you have the rank and value.

The upside to this approach is that it is time complexity O(n) where n is the length of the collection of cards you are trying to rank.

One downside is that the size of the state transition table is large. I don't remember how to calculate how large, but in Hold'em you would be evaluating a collection of 7 cards chosen from a pool of 52 cards. Plus you could have intermediate states. Statistics could tell you if you have enough memory to make this approach feasible.

A second downside is that generating the state transition table may be difficult. It's impossible to do by hand, and you'd have to be pretty clever to generate a correct state transition table (including any intermediate states) programmatically.

Just thought I'd post this so someone reading this might solve the problem another way.

You mean you want to write your own implementation?

The source for most standard modules is included with the standard Python distribution. On Windows they can typically be found in "C:\Python32\Lib". The two digits can be different depending on your Python version.

The source for "insort_right":

[code=PYTHON]def insort_right(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.

If x is already in a, insert it to the right of the rightmost x.

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
a.insert(lo, x)[/code]

Bisect is one of the better options.

There are performance implications with any kind of sorting. Bisection has logarithmic time complexity. I don't know what the time complexity is for sorting in the standard Python distribution.

If we are adding a lot of items then at some point simply extending the list and sorting it will be faster than insorting each item individually. (Probably.) It's much more elegant too.

[code=PYTHON]import bisect

making a new list

x = [5, 4, -3, 100, 88.3, -23.9]

sort it


[-23.9, -3, 4, 5, 88.3, 100]
adding an item to an existing list
preserving sorting

bisect.insort(x, 65.5)

[-23.9, -3, 4, 5, 65.5, 88.3, 100]
adding many items to an existing list

x.extend((75.4, -100, 999))

sort it


[-100, -23.9, -3, 4, 5, 65.5, 75.4, 88.3, 100, 999][/code]

"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

Is this for production or is it just an exercise?

If it is for production use bisect.insort to insert items into a list in sorted order.

Erm... Didn't notuce until just now, but the line "print(name, 'says hello.')" should be "print(, 'says hello.')".


Let me try to explain object-oriented programming.

Object-oriented programming is programming with objects.

Objects are data structures consisting of fields of data (attributes) and functions that interact with that data (methods).

Objects are instances of classes (types). Classes represent the data structure. When you make a new class, you are "declaring" a class.

In Python, classes possess special methods for certain functions. Their names are usually between double underscores. "init" is a special method to initialize a new object and its data. The call to init is usually implicit. Normal methods have an implied first argument (usually called "self") that reflect back to the object. Methods can access an instance's data using "self".

An example:

[code=PYTHON]class Person:

#Special method. Each person we make has a name.
def __init__(self, name): = name

#Method accesses the instance's name to print it.
def introduce(self):
    print(name, 'says hello.')
init called implicitly
sets this person's (and only this person's) name

x = Person('John')

a different person

y = Person('Jane')

printing their names