2,646 Posted Topics
Re: There is no memory leak in python. Python uses a generational garbage collector which deletes objects when there is no reference left to these objects. You can have look at the [icode]gc[/icode] module which gives you a few functions to interact with the garbage collector, but normally you don't have … | |
Re: Here is how you can write it with itertools [code=python] import itertools as itt from operator import itemgetter list1 = [ ('1101', '2'), ('1101', '3'), ('1101', '4'), ('4472', '2'), ('4472', '3'), ('4472', '4'), ('4472', '5'), ('5419', '2') ] list2 = [ ('1101', '3'), ('4472', '5'), ('5419', '3') ] # A … | |
Re: You can try this [code=python] # python 3 import re words = {'i':'jeg','read':'leste','book':'boka'} articles = set(["the", "a"]) while True: sentence =input('Write something: ') if sentence == 'quit': break sentence = sentence.split() result = [] art = [] for word in sentence: word_mod = re.sub('[^a-z0-9]', '', word.lower()) punctuation = word[-1] if … | |
Re: I once wrote a code snippet that parses command lines the way a C program parses argv. You could use it for your problem: save [url]http://www.daniweb.com/code/snippet234768.html[/url] as argv.py [code=python] >>> from argv import buildargv >>> print buildargv("10210 'ARDNA 10' 110.00 1 0.00 0.00 1 1 1.0432 -3.954")) ['10210', 'ARDNA 10', … | |
Re: The inner call to primes() does nothing at all. I added a few print statements so that you can see if your program does what you are expecting [code=python] def primes(p=2): while True: for n in range(2,p): if p % n == 0: p += 1 print("before calling prime(%d) for … | |
Re: It seems that your communication protocol adds null characters [icode]"\x00"[/icode] in the string. The first thing you could do is remove these characters with [code=python] myString = myString.replace("\x00", "") [/code] The other question, as you said, is to understand why your server sends these null chars. Without the server and … | |
Re: You could start filling a dictionary with knowledge, like this [code=python] holydays_dict = { (2, 18) : "February 18 is Presidents' Day.", } [/code] Then find how your program could select an entry in the dictionary. | |
Re: There is a colon missing at the end of [icode]for zone in zonelist[/icode]. Add [icode]:[/icode]. Also, when the interpreter says that there is an error, it prints a wonderful thing called a exception traceback. This is [b]very useful[/b] to helpers, so when you have an error, please post the traceback … | |
Re: [QUOTE=woooee;1135015]I have to be misunderstanding the concept. [/QUOTE] It looks like a way to measure an entropy. If you have n values x1,...xn and you take a convex function F (a function with positive 2nd derivative), you have an inequality F( (x1 + ... + xn)/n ) <= ( F(x1) … | |
Re: Try [icode]showntiles.extend(nexttile)[/icode] perhaps. It seems that python creates a local variable because of the +=. | |
Re: You should explain a little more. You are creating a dictionary [code=text] number1 ---> [ number2, list1 ] [/code] I suppose that number1 is an atom ID, but what are number2 and list1 ? | |
Re: Your program seems too complicated for what you are trying to do. You could split the lines on the first "," without regular expressions: [code=python] def rr_lines(lines): for line in lines: if line.startswith("RR"): yield line def splitted_lines(lines): for line in rr_lines(lines): fcode, desc = line.split(",", 1) yield (fcode, desc) if … | |
Re: There is a trick, you can compare [b]tuples[/b], for example [code=python] >>> (1980, 3, 15) < (1987, 7, 12) True >>> (1987, 3, 15) < (1987, 7, 12) True >>> (1987, 7, 15) < (1987, 7, 12) False [/code] So, instead of passing the years of birth to your function … | |
Re: The next step is to use regular expressions (learn [url=http://docs.python.org/3.1/library/re.html#module-re]the re module[/url]) [code=python] import re pat = re.compile(r"([+\-*/=]+)") print(pat.split("1+2-3")) # prints ['1', '+', '2', '-', '3'] pat = re.compile(r"[+\-*/=]+") print(pat.split("1+2-3")) # prints ['1', '2', '3'] [/code] If regular expressions are not sufficient, the next step is to use a parser … | |
Re: You should print explicitely the content of the file using repr() [code=python] content = open(fl,'r').read() print repr(content) [/code] You should be able to see if your file contains wild characters. You can also try the 'rb' opening mode if you are using windows, to see if it makes any difference. | |
Re: You can write first a generator for the child elements that you want to sort [code=python] def child_elements(the_structure): for number, subdict in the_structure.iteritems(): for A_name, sublist in subdict.iteritems(): yield (A_name, sublist) [/code] Then you define a score function for the extracted items and you sort the sequence according to this … | |
Re: [QUOTE=gunbuster363;1132423]but I want distinct strings.........and I don't want to loop it over to see if there is a existed string of the same.[/QUOTE] You can use a set of strings [code=python] s = set(["hello", "world"]) s.add("anotherstring") s.add("hello") print s [/code] or a dictionary (dict). Dict is the name of 'hash … | |
Re: Try this [code=python] from itertools import permutations for t in permutations(['e', 'n', 'o', 't', 'r']): print t [/code] ;) | |
Re: I had to modify your code to run it on my system. This is the modified version with the result that both times are the same [code=python] import random, sys, os, struct lib = os.path.dirname(os.__file__) sourcefilepath = os.path.join(lib, "random%spy" % os.extsep) testfilepath = sourcefilepath + "c" istream = open(testfilepath, 'rb') … | |
Re: The method Class2.button1 needs a Class2 instance to work, so you need to create an instance and you can write [code=python] obj2 = Class2() b1 = Button(self.can1,text="button 1",command=obj2.button1) [/code] | |
Re: You could start like this [code=python] mystring = "F' B D D2 A2 C'" mylist = mystring.split() print(mylist) print(mylist[3]) """ my output --> ["F'", 'B', 'D', 'D2', 'A2', "C'"] D2 """ [/code] | |
Re: I already see a problem, you should swap lines 20 and 21 because here, in line 21, you are giving a string value to self.value. In the __init__ method, you should never have written line 4 if you want to give self.rank a string value, you can work with the … | |
Re: [url=http://www.daniweb.com/code/snippet257449.html]Use this code snippet[/url]. Write [icode]com = Command("iwconfig").run()[/icode]. | |
Re: Once you saved the file quantile.py in the same directory, if you want to use the quantile function in program.py, you have to put [code=python] from quantile import quantile [/code] before you use quantile in program.py (typically at the top of the program). | |
Re: The problem is that the print statement is executed before the testit thread had time to establish a connection and receive data. The only thing to do is to [b]wait[/b] before the print statement. There are 2 ways to wait here: First way: you wait until the testit thread is … | |
Re: [QUOTE=Kruptein;1129804]Why can't I use tabs ? I hate it when I every time have to hit 4 times the tab. Btw every program I made till now works with those tabs.[/QUOTE] Your favorite editor DOES have a configuration option to write 4 spaces instead of a tab ! | |
Re: After [code=python] print (birth1,', am I correct,', yourname1,'?') [/code] the program should be able to get yourname1's answer and do something if the answer is no. | |
Re: It seems unbelievable to me that you obtain less matches with finditer. I wrote a small function to test this. Run it instead of risk_committee_search. It compares the output of search and finditer. If it raises AssertError, you should post the output here. If it does not, it means that … | |
Re: Also, all this should be written using module bisect: [code=python] from bisect import bisect limits = [100, 1000, 2500, 5000, 10000, 25000, 50000, 100000] pairs = [ (5, 70), (50, 700), (100, 1000), (250, 2000), (500, 5000), (1000, 7500), (2500, 10000), (5000, 10000), (1, 1000000000) ] a, b = pairs[bisect(limits, … | |
Re: Replace line 5 with [icode]money = int(f.readline().strip())[/icode]. | |
Re: You can use a code structure like this: [code=python] next_number = 52 for i, line in enumerate(fin): if i == next_number: fout.write(line) next_number += 102 [/code] | |
Re: Your folder D:\Logiciel\PYTHON\Exercices contains a suspicious file turtle.py which is probably not the module turtle from python's lib-tk. So check this file, and rename it if necessary. | |
Re: [url=http://www.daniweb.com/forums/announcement114-2.html]Read this first ![/url] | |
Re: The python 2.6 documentation says that the first argument None in str.translate is new in 2.6. Previously, the first argument had to be a string of 256 characters (translation table). I suppose you should write something like [code=python] import sys if sys.version_info < (2, 6): table = ''.join(chr(i) for i … | |
Re: See also [url=http://docs.python.org/library/shutil.html#shutil.rmtree]shutil.rmtree[/url] to remove an entire directory tree. | |
Re: An html file has no "output", it's just an html file. There are programs to convert an html file to a text file or a pdf file, you should google for that. | |
![]() | Re: You could try something like this [code=python] def mirrored(listtree): return [(mirrored(x) if isinstance(x, list) else x) for x in reversed(listtree)] [/code] then [code=python] >>> a=[[1, 2], ['apple', 'orange']] >>> mirrored(a) [['orange', 'apple'], [2, 1]] >>> a=[[1, 2], [['apple', 'banana', 5], 'orange']] >>> mirrored(a) [['orange', [5, 'banana', 'apple']], [2, 1]] [/code] |
Re: You could put this in __init__.py [code=python] # __init__.py def _load(): from glob import glob from os.path import join, dirname, splitext, basename for path in glob(join(dirname(__file__),'[!_]*.py')): name = splitext(basename(path))[0] exec "from %s import *" % name in globals() _load() [/code] Note that all the submodules will be loaded when you … | |
Re: [QUOTE=Krstevski;1124564]Hello... I have problem with regex, I want to get the tables from another site... the regex is re.compile(r'<table.*?>(.*?)</table>') but when I get the tables I don't know how to return the value into the tables. [CODE=Python] #html = the page tbl = re.compile(r'<table.*?>(.*?)</table>') return tbl.sub('', html) #return html without … | |
This snippet defines a class OptCmd which adds line and options parsing capabilities to the python standard lib's cmd.Cmd class. It allows you to quickly write an extensible command line interpreter. To use this module, you will need [url=http://www.daniweb.com/code/snippet234768.html]this other code snippet[/url], saved as a module named 'argv.py'. Enjoy the … | |
Some time ago, I was writing a small command line interpreter, with the help of [url=http://docs.python.org/library/cmd.html#module-cmd]the standard module cmd[/url] which offers minimal support for such tasks, and I had the problem that this module doesn't have a function to parse a command line to produce a list argv which can … | |
Re: [QUOTE=supanoob;1123171]Damm I knewed that I forget something. well something very importent for me is also to be able to make an windows binary out of my scripts[/QUOTE] There is a program called GUI2exe to make windows binary from wxpython code. About the board: you can write your posts in your … | |
Re: I think you're taking the problem the wrong way: you're writing classes and miscelaneous functions and you're missing the most important part. I think you should forget your classes for a moment and start thinking about Mr User of your program. I suppose that the user wants to input menus, … | |
Re: I've never heard of such a thing, but if it works, you should post the code, so that everybody can try it on some web pages ! | |
Re: In linux, there is a command called [icode]convert[/icode] that does just that. The shortest path is to call this command from python. It's part of a thing called ImageMagick which also seems to exist in windows, so you should have a look at it. | |
Re: If you have problems with reusing the same port, you should try this socket option [code=python] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) [/code] just after creating the socket with socket.socket(). | |
Re: Assuming the name of your service is [icode]service[/icode], you could try to run this program [code=python] # runservice.py import subprocess as sp import sys SERVICE_COMMAND = "service" def run_service(command): with open("output.txt", "w") as output_file: process = sp.Popen(command, shell=True, stdout=sp.PIPE) for line in process.stdout: for f in (output_file, sys.stdout): f.write(line) process.wait() … | |
Re: Perhaps you should call matplotlib.pyplot.show() after imshow. | |
Re: Your global variable monitor was initialized to None and never modified. Python won't set a 'clientIP' attribute for the None object: [code=python] >>> None.clientIP = "foo" Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'clientIP' [/code] | |
Re: [QUOTE=mahela007;1117519]Thanks... that's what I needed. However, I'd like to know HOW a timer is created in python.[/QUOTE] Apart from the sleep function, there is a Timer class in the threading module and there are timers in gui modules like tkinter and wxpython. Other ways to wait are the threading.Condition.wait() function, … |
The End.