2,646 Posted Topics

Member Avatar for revenge2

Here is the documentation for sys.path [url]http://docs.python.org/3.0/library/sys.html#sys.path[/url], and here is the documentation for sys.argv [url]http://docs.python.org/3.0/library/sys.html#sys.argv[/url]. At this point, you should start using python's documentation: add this page [url]http://docs.python.org/3.0/[/url] to your favorite pages :) A nice link in this page is the global module index. In this index you can find …

Member Avatar for Stefano Mtangoo
0
468
Member Avatar for revenge2

It's very simple, some idioms in a python program introduce a *block* of statements. The block of statements must be non empty and indented. They are introduced by lines ending with a [icode] : [/icode]. These idioms are [code=python] # class definitions class myClass(object): # block of statements (indented) # …

Member Avatar for mn_kthompson
0
122
Member Avatar for nrupparikh

I don't agree, because the compiler can see that sizeof(arr)/sizeof(int) never changes, so it certainly generates the code with a constant value. Isn't it a lack of knowledge Aia ? Knowledge, beauty, great philosophical problems to think about !

Member Avatar for Aia
-1
151
Member Avatar for revenge2

With python 3.0, print is no longer a statement but a function and you must write [code=python] print("hello world") [/code]

Member Avatar for sneekula
0
126
Member Avatar for Mr_Grieves
Member Avatar for lllllIllIlllI

I think python 3.0 will clean up the code with a better support for strings (unicode) and the print function. I like the context management protocol (the with statement). I think there is a lot to explore with this. Also class decorators look appealing :)

Member Avatar for Stefano Mtangoo
0
117
Member Avatar for mn_kthompson

I think you could write your own function like this [code=python] from random import random from math import sqrt def triangular(a, c, b): c = float(c) t = (c-a)/(b-a) y = sqrt(random()) d = a if random() < t else b return d + (c-d) * y if __name__ == …

Member Avatar for mn_kthompson
0
2K
Member Avatar for nrupparikh
Member Avatar for Gribouillis
0
153
Member Avatar for leegeorg07

I'd like to have a little philosophical discussion about this recurrent question: "Hey, I have this problem, how should I start ?", or "I'm stuck, what should I do ?". First question: are there valuable reasons to be stuck on a problem ? I think there are, and I see …

Member Avatar for Stefano Mtangoo
0
562
Member Avatar for woah
Member Avatar for mn_kthompson
0
108
Member Avatar for lllllIllIlllI

Hello again and merry christmas ! In fact I don't use decorators so much. The decorators I use most often are the builtin decorators [icode]@property[/icode], [icode]@staticmethod[/icode] and [icode]@classmethod[/icode]. I discovered decorators in the attached slides of pycon 2005, which don't seem to be available anymore at python.org. Decorators are useful …

Member Avatar for lllllIllIlllI
0
113
Member Avatar for dseto200

I suggest a refactoring using a class [code=python] # Character Development Dungeons and Dragons # pool are the total points that I can use. class CharacterDevelopment(object): attributes = "strength health wisdom dexterity".split() pool = 30 def __init__(self): self.attribs = dict((attr, 0) for attr in self.attributes) @property def current(self): return sum(self.attribs.values()) …

Member Avatar for dseto200
0
118
Member Avatar for Kezoor

This is so because of the history of the python language. In the early versions of python, classes were defined using [icode]class A:[/icode]. Then the implementation of python objects changed, mainly so that users could define subclasses of the builtin types like int, str, dict, list, etc.The 'new style' classes …

Member Avatar for Kezoor
0
130
Member Avatar for shr2408

There is the SendKeys module [url]http://www.rutherfurd.net/python/sendkeys/[/url]. I'm not using it, but other people in this forum can tell you more about it.

Member Avatar for shr2408
0
366
Member Avatar for codedhands

I see 2 solutions. The first one is to wait that the thread is dead before calling [icode]getHTML()[/icode], This is done with the [icode]join[/icode] method like this [code=python] ... loadhtml=LoadHtml("testindex.ind") loadhtml.start() loadhtml.join() print loadhtml.getHTML() [/code] The other method is to add a variable [icode]done[/icode] to the thread object which will …

Member Avatar for codedhands
0
2K
Member Avatar for Hrothgar

[code=python] >>> import random >>> print random.randint(0, 10) [/code] Also read a python tutorial !

Member Avatar for Stefano Mtangoo
0
175
Member Avatar for Rejinacm

However why do you need to create these variables ? In such cases, it's usually better to create a list of 10 elements [icode]a[0], ..., a[9][/icode] like this [code=python] a = [None] * 10 for i in range(len(a)): a[i] = 77 - i * i [/code]

Member Avatar for paddy3118
0
116
Member Avatar for Rejinacm

Here is a python enhancement proposal about the switch statement, by Guido Van Rossum which he apparently rejected because of lack of popular support [url]http://www.python.org/dev/peps/pep-3103/[/url].

Member Avatar for sneekula
0
137
Member Avatar for nuaris

put [icode]from classA import classA[/icode] in classB.py instead of [icode]import classA[/icode]

Member Avatar for nuaris
0
152
Member Avatar for codedhands

Did you try [icode]re.compile(r"\b%s\b" % url)[/icode] ? Or probably better [icode]re.compile(r"\b%s\b" % re.escape(url)[/icode] ?

Member Avatar for codedhands
0
124
Member Avatar for Littlerocks

There are many ways to do this. Here is a function which computes the index for which the first item of a sequence is repeated [code=python] def first_return(sequence): it = iter(sequence) first_item = it.next() for i, item in enumerate(it): if item == first_item: return i+1 return -1 # if the …

Member Avatar for Gribouillis
0
149
Member Avatar for adam291086
Member Avatar for adam291086
0
76
Member Avatar for MaxManus

It's very simple, when you write a 2nd order equation as a first order system, the technique is to introduce the vector (u, v) = (u, u') and to compute its derivative. You have (u, v)' = (u', v') = (v, u"). Now you replace u" by (1/m)(F(t) - f(u') …

Member Avatar for MaxManus
0
130
Member Avatar for tom7tom

If you can install matplotlib, look here [url]http://matplotlib.sourceforge.net/examples/pylab_examples/barh_demo.html[/url] what it can do with 10 lines of code. I didn't try it, but it looks like a simple way to draw your bar graph.

Member Avatar for Gribouillis
0
84
Member Avatar for shadwickman

I don't think it's possible. The normal way to do this is to create your own subclass of [icode]str[/icode] like this [code=python] class mystr(str): def __new__(cls, *args): return str.__new__(cls, *args) def findAll(self, other): print("Couldn't find '%s' in '%s'!" % (other, self)) if __name__ == "__main__": s = mystr("Hello world") s.findAll("Hi") …

Member Avatar for shadwickman
0
160
Member Avatar for Gribouillis

Python 3.0 comes with a builtin [icode]print[/icode] function which breaks old code. In order to write code wich is compatible both with the 2.x series and with the 3.x series, I'm using the following [icode]Print[/icode] function [code=python] import sys def Print(*values, **kwd): fout = kwd.get("file", sys.stdout) sep = kwd.get("sep", " …

Member Avatar for Gribouillis
0
169
Member Avatar for Puppetmaster

Running different functions in different threads give you a very good illusion of functions running at the same time (see the threading module). Of course, at processor's level, only one of the functions is running at the same time.

Member Avatar for Prahaai
0
105
Member Avatar for wotthe2000

To transpose, use zip(*L) where L is a list of tuples, like this [code=python] theList = ['xxxplanexx', 'xrxxxxxxxx', 'xexxxxxyxx', 'xdxxxxxexx', 'xxxxxxxlxx', 'xxxxxxxlxx', 'xxxxxxxoxx', 'xxxxxxxwxx', 'xkingxxxxx', 'xxxxxxxxxx'] tranposed = ["".join(t) for t in zip(*[tuple(w) for w in theList])] #my output ----> #['xxxxxxxxxx', 'xredxxxxkx', 'xxxxxxxxix', 'pxxxxxxxnx', 'lxxxxxxxgx', 'axxxxxxxxx', 'nxxxxxxxxx', 'exyellowxx', 'xxxxxxxxxx', 'xxxxxxxxxx'] …

Member Avatar for Murtan
0
277
Member Avatar for adam291086
Member Avatar for mmeclimate

There are some conversion functions in the module [icode]binascii[/icode]. For example you can convert to readable hex format with [icode]binascii.hexlify[/icode]. I don't know if it's what you're looking for.

Member Avatar for mmeclimate
0
2K
Member Avatar for krammer

To remove a directory, I suggest [code=python] import shutil shutil.rmtree(directory) [/code] Also I googled a while, and I discovered this python program [url]http://linux.softpedia.com/get/Utilities/trash-30080.shtml[/url]. I think it's worth browsing the source code.

Member Avatar for krammer
0
283
Member Avatar for jvignacio

how about this [code=python] from collections import defaultdict words = defaultdict(int) for word in (w.lower() for w in open("input.txt").read().split()): words[word] += 1 for word, cnt in sorted(words.items()): print word, cnt [/code]

Member Avatar for jvignacio
0
225
Member Avatar for jcafaro10

It means that one of the modules which you're using, directly or indirectly, tries to import a module name 'main' and can't find it. Do you have a more complete exception traceback ?

Member Avatar for jcafaro10
0
5K
Member Avatar for vmars

Tkinter is the gui toolkit which comes with the python distribution. However I think it's here mainly for historical reasons: it was the first gui toolkit available. I think wx python is a very good choice which gives excellent results, but you must download it separately from python. The other …

Member Avatar for Kezoor
0
317
Member Avatar for jcafaro10

The local namespace of a method doesnt see the namespace of the class. Inside a method, you can only access the variables from the local namespace and the variables defined at module level. So your [icode]global switch[/icode] is misplaced.

Member Avatar for jcafaro10
0
183
Member Avatar for adam291086

Here is a way [code=python] import re data = """ <Element Generation at d66238> <Element Vitals at d662b0> <Element Network at d66670> <Element Hardware at d66eb8> <Element Memory at d6ac88> <Element Swap at d6e0a8> <Element Swapdevices at d6e238> <Element FileSystem at d6e5d0> <Element Vitals at d662b0> """ expr = re.compile(r"<Element …

Member Avatar for Gribouillis
0
104
Member Avatar for jmn0729

There are different ways. The old simple way is [code=python] os.system("mycommand") [/code] Now it's considered better to write [code=python] import subprocess child = subprocess.Popen("mycommand", shell = True) [/code] You could add pipe arguments to write into your command's stdin and read from it's stdout or stderr (see the documentation of …

Member Avatar for Gribouillis
0
411
Member Avatar for Gribouillis

The following program is able to download the python programs contained in a thread of the python forum. Just start the program, it will prompt you for the thread number and create a directory with the code extracted from the thread. I used it to download all the wx examples. …

0
112
Member Avatar for MaxVK

I would suggest something like this, with the pickle module (completely untested) [code=python] import pickle class Tree(object): # a tree class, with a single root (a Node object) def __init__(self): self.root = None def fillCtrl(self, ctrl): # fills an empty wx.TreeCtrl (ctrl) with the content of the tree structure if …

Member Avatar for MaxVK
0
1K
Member Avatar for dseto200

Here is a random word generator for this dictionary file [code=python] from os.path import getsize from random import randint dic_path ="DictionaryE.txt" file_size =getsize (dic_path ) file_in =open (dic_path ,"rb") def random_word (): while True : offset =randint (0 ,file_size ) file_in .seek (offset ) L =file_in .read (25 ).split ("\r\n") …

Member Avatar for woooee
0
2K
Member Avatar for Darkangelchick

for PROBLEM 1, I suggest the following program [code=python] #!/usr/bin/env python # printdef.py # prints the names of all function definitions found in a program # usage: python printdef.py myprogram.py from tokenize import generate_tokens, NAME def getDefSequence(programPath): tokens = generate_tokens(open(programPath, "r").readline) for token in tokens: if token[0] == NAME and …

Member Avatar for Darkangelchick
0
215
Member Avatar for lllllIllIlllI

I would say the pickle or shelve modules :) ... I found this with google, which might be interesting [url]http://www.evilchuck.com/2008/02/tell-python-to-shove-it.html[/url]

Member Avatar for lllllIllIlllI
0
88
Member Avatar for adam291086

I suggest a generator [code=python] def find_text(element): if element.text is None: for subelement in element: for txt in find_text(subelement): yield txt else: yield element.text for txt in find_text(root): print txt [/code]

Member Avatar for adam291086
0
166
Member Avatar for Prahaai

I suggest this [code=python] from glob import glob as __g import re pattern = re.compile(r"/Count\s+(\d+)") def count(vPath): """ Takes one argument: the path where you want to search the files. Returns a dictionary with the file name and number of pages for each file. """ vPDFfiles = __g( vPath + …

Member Avatar for Prahaai
0
4K
Member Avatar for OB_

Here is how you could do this [code=python] import random result = 0 while True: # means forever roll = random.randint(1, 10) result += roll if roll != 10: break print result [/code]

Member Avatar for Gribouillis
0
78
Member Avatar for ping24

A nice module is [icode]ply[/icode] which has the functionality of the lex and yacc tools but with a pure python implementation. It might not be the fastest parser in python, but I think it's a very good starting point. It was written by David Beazley, who is also the author …

Member Avatar for Gribouillis
0
77
Member Avatar for payne_99

The syntax error is somewhere in your script. Can you post the script (or attach it) ?

Member Avatar for lllllIllIlllI
0
126
Member Avatar for Lardmeister

Note was the french president in question was Chirac and not Charic. I agree that after a certain age, some people should stop to work, like presidents, popes, etc. I don't vote in this poll because I'm french :)

Member Avatar for jbennet
0
3K
Member Avatar for superman71903

An easy way of communication is the pyro module. pyro stands for Python Remote Objects, it allows a process to register a python object in a name server and other processes to obtain proxies for the object. They can remotely call methods on the object, which is a very simple …

Member Avatar for superman71903
0
127
Member Avatar for tomtetlaw

An alternative to changing the method's name is this [code=python] class Troll(Monster): def getAttributesInfo(self): Monster.getAttributesInfo(self) [/code] It's a standard way of overloading a method in python: the method in the derived class calls the method with the same name in the parent's class. This allows you to define troll-specific behaviour …

Member Avatar for tomtetlaw
0
251

The End.