2,646 Posted Topics
Re: 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 … | |
Re: 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) # … | |
Re: 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 ! | |
Re: With python 3.0, print is no longer a statement but a function and you must write [code=python] print("hello world") [/code] | |
Re: 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 :) | |
Re: 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__ == … | |
Re: type "prime C" in the search form at the top of this webpage ! | |
![]() | Re: 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 … |
Re: If you're using python 3.0, there is no raw_input. Use input instead. | |
Re: 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 … | |
Re: 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()) … | |
Re: 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 … | |
Re: 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. | |
Re: 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 … | |
Re: [code=python] >>> import random >>> print random.randint(0, 10) [/code] Also read a python tutorial ! | |
Re: 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] | |
Re: 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]. | |
Re: put [icode]from classA import classA[/icode] in classB.py instead of [icode]import classA[/icode] | |
Re: 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] ? | |
Re: 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 … | |
Re: may be it's blocked by a secret hook of the python interpreter too ! | |
Re: 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') … | |
Re: 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. | |
Re: 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") … | |
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", " … | |
Re: 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. | |
Re: 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'] … | |
Re: What is the output of [icode]print(Results)[/icode] ? | |
Re: 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. | |
Re: 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. | |
Re: 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] | |
Re: 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 ? | |
Re: 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 … | |
Re: 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. | |
Re: 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 … | |
Re: 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 … | |
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. … | |
Re: 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 … | |
Re: 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") … | |
Re: 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 … | |
Re: 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] | |
Re: 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] | |
Re: 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 + … | |
Re: 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] | |
Re: 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 … | |
Re: The syntax error is somewhere in your script. Can you post the script (or attach it) ? | |
Re: 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 :) | |
Re: 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 … | |
Re: 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 … |
The End.