2,646 Posted Topics
Re: Here is a way def parse(annotation): return list((int(x), int(y)) for (x,y) in (item.strip(" ()").split('..') for item in annotation.split(','))) print parse('(1834..2736), (348..7734)') """ my output --> [(1834, 2736), (348, 7734)] """ Edit: try and use the [code] button in the editor window at the bottom of this page! Edit: it seems … | |
Re: Here is a version with timeit [code=python] # 619480 import time from random import * from timeit import Timer timer = Timer("binarySearch(Spam.value, Spam.lst)", "from __main__ import Spam, binarySearch") class Spam: pass def main(): lst = [] result, length = 0, 500000 while result <= 0.50 and length < 10**7: for … | |
Re: I suggest a system based on generic functions: for each type, you define a function iround(x) to convert instances to the nearest integer, and a function equals_integer(x, n) which tells if instance x should be considered equal to the integer n. Then isinteger() is true if x must be considered … | |
Re: The standard terminology is to call the three [i]slice[/i] arguments start, stop and step [code=python] L[start:stop:step] [/code] The elements in the returned list are [code=python] L[start], L[start + step], L[start + 2*step], L[start + 3*step], ... [/code] [LIST] [*][i]step[/i] cannot be zero and defaults to 1 [*][i]stop[/i] must not be … | |
Re: You must not insert or remove items in a list while iterating on this list. In your case, you could simply use [code=python] for x in a: print x a[:] = () [/code] If you want to delete only some items, use a pattern like [code=python] a = range(10) print … | |
Re: You could perhaps store the labels like in [code=python] from itertools import product def indices(self): return product(xrange(ROW), xrange(COLUMN)) def create_labels(self): self.labels = list(list() for i in range(ROW)) for row, column in self.indices(): label = tk.Label(self) label.grid(row = column, column = row) self.labels[row][column] = label [/code] then update the labels with … | |
Re: If you want to execute commands on a remote computer, the simplest solution is a ssh server on the remote computer. See this thread [url]http://www.daniweb.com/software-development/python/threads/375262/1615004#post1615004[/url] . | |
Re: It's a really strange idea to mix wxpython and tkinter in the same program. You should probably use a wx.FileDialog. See the FileDialog example in this page [url]http://wiki.wxpython.org/Getting%20Started#Dialogs[/url] | |
Re: [QUOTE=pyTony;1730563]The result should include sublists of length k which do not contain first element and lists of first element followed by all sublists from other elements of length k - 1, when length of argument is more than k.[/QUOTE] I don't agree with Tony, I think it's better to find … | |
Re: I think it is cheating, you can cheat even more [code=python] def MinMax(numbers): ''' This function finds the minimum and maximum values. Input a list of real numbers. ''' return min(numbers), max(numbers) [/code] Try to write a function without sort(), min(), max(). You can use a loop and the comparison … | |
Re: It works almost fine for me in a linux box, I only had to add this [code=python] else: # ADDED return 0, 0 # ADDED [/code] to ToolTip.coords() (there are probably better values to return), and I used [code=python] t1 = ToolTip(b, text="The Rejuvenation Power", delay=500) #or t1 = ToolTip(b, … | |
Re: I think this motto should not be understood too strictly. Here are a few hints 1) If there is only one (preferably obvious) way to do things, this reduces considerably the design part of writing software. Everybody agrees on the unique possible solution. 2) Obviously (and hopefully) this is not … | |
Re: [QUOTE=tcl76;1729585]great. the output is right. it's strange though when i open using output.txt using notepad, it shows: 17 BC_1 CLK input X 16 BC_1 OC_NEG input X 15 BC_1 D 1 but when i use other editor like wordpad it shows (which is what i want) 17 BC_1 CLK input … | |
Re: Something like [code=python] from itertools import dropwhile, takewhile def not_advanced(line): return not line.startswith("-- Advanced") def not_num(line): return not line.startswith("-- num") with open("sample.txt") as lines: lines = takewhile(not_advanced, dropwhile(not_num, lines)) for line in lines: print line [/code] | |
Re: Add the following line to your file ~/.bashrc [code=text] export PYTHONPATH="$HOME/MyModules:$HOME/fooo/bar/baz/qux/someotherdirifyouwant" [/code] then restart a bash shell (or a terminal). You don't need an __init__.py in MyModules because it is not a python package. | |
Re: 'r' was encountered only twice, add a few prints to see what happens [code=python] s = ['b','a','r','r','i','s','t','e','r'] for x in s: print x, if(x == 'r'): print "\n", s, "-->", s.remove(x) print s print "Second version: " s = ['b','a','r','r','i','s','t','e','r'] for x in list(s): print x, if(x == 'r'): print … | |
Re: I suggest [code=python] def touch(filename): os.close(os.open(filename, os.O_WRONLY | os.O_CREAT, int("666", 8))) os.utime(filename, None) def load(filename = 'Database.csv'): if not os.access(filename, os.F_OK): touch(filename) with open(filename, 'rb') as ifh: return list(list(row) for row in csv.reader(ifh)) [/code] Also, for your safety, indent python code with 4 spaces, no tab characters, and avoid module … | |
Re: To break the loop on empty input, use [code=python] while True: x_str = raw_input('Enter Start,Stop,Increment: ') if not x_str: break else: ... [/code] edit: where is indention in your code ? Configure your editor to indent with 4 spaces when you hit the tab key. | |
Re: It should be [code=python] def is_prime(n): i = 2 while n > i: if n % i != 0: i += 1 else: return False return True [/code] but this code is inefficient. Search this forum for similar functions. | |
Re: What are you looking for exactly in the string "Johnny" ? What is this .group doing here ? Why is J out of the string in the re.search statement. Hint: experiment with the re module by using [url=http://kodos.sourceforge.net/]kodos[/url] the python debugger (works with python 2, should be installable with easy_install). | |
Re: Perhaps you mean [code=python] >>> len('string') 6 [/code] | |
Re: I don't have the time to study your code now (the whole program could be useful) but I think it could be a use case for this snippet that I wrote some weeks ago [url]http://www.daniweb.com/software-development/python/code/395270[/url] . See if it applies to your problem. | |
Re: Try [code=python] >>> print "[%s]" % ", ".join(listtest) [Bureau, Téléchargement] [/code] | |
Re: [QUOTE=thepythonguy;1722963]Okay.Need a little more help. Is there something wrong with this? [CODE]import time import sys print """Enter your name """ myname = chr(sys.stdin.readline()) print """Hello %s. How are you today? Would you mind entering your age?: """% myname myanswer = (sys.stdin.readline()) if myanswer == "yes": myage = int(sys.stdin.readline()) print "Hello … | |
Re: It's very simple. First python finds modules installed in some site-packages directories. For example /usr/lib/python2.7/site-packages or /usr/lib64/python2.7/site-packages if you have a 64 bits python, or your per-user site-packages directory ~/.local/lib/python2.7/site-packages (you can create it yourself if it does not exist). If you want python to find modules in other directories, … | |
Re: I think arguments to logchoose() should be swapped [code=python] from scipy import exp, special def logchoose(n, k): lgn = special.gammaln(n+1) lgk = special.gammaln(k+1) lgnk = special.gammaln(n-k+1) return lgn - (lgnk + lgk) def hypgeo(x, r, b, n): u = logchoose(x, r) v = logchoose(n-x, b) w = logchoose(n, r + … | |
Re: Hitting the up-arrow key should bring back the previous lines of input, at least this is the case if you are running python in a shell (or cmd) window. If you are using idle, use ALT-p intead of up-arrow. Other interfaces may have different shortcuts. Also please use descriptive thread … | |
Re: I suggest creating a module or an object named pp (like preprocessor) and create methods that stick to the C preprocessor [code=python] if pp.ndef("BUG_XF_STALL"): pp.define("BUG_XF_STALL") # etc [/code] The implementation shouldn't be too difficult as there is only one namespace involved. If your intention is to replace portions of code … | |
Re: Under linux/KDE, I was able to start a program in a terminal like this [code=python] >>> import subprocess >>> child = subprocess.Popen("konsole -e python foo.py", shell=True) [/code] It also works with xterm instead of konsole if you're not using KDE. | |
Re: In removePhone(), [icode]if y:[/icode] should be [icode]if a == 'y':[/icode]. In the same way, you must select an action in update_phone_info(), depending on the user choice: [code=python] if user_choice == '1': x = input(str('enter new manufacturer')) self.manufact = x elif user_choice == '2': y = input(str("enter new model")) self.model = … | |
Re: The only problem I see is that your np arrays don't match your description of the problem. The following works for me [code=python] import numpy as np data = """ 1000 36 2000 40 3000 45 4000 50 """.strip().splitlines() data = zip(*(map(float, item.split()) for item in data)) x, y = … | |
Re: Probably with glob.glob [code=python] import glob import subprocess filelist = glob.glob("./FEED1/bin/*") if filelist: cmd = subprocess.Popen(["dos2unix"] + filelist, stdout=subprocess.PIPE) [/code] see also this snippet [url]http://www.daniweb.com/software-development/python/code/257449[/url] | |
Re: It depends on your output shell. If you are using python in a terminal, you can print in colors with this module [url]http://pypi.python.org/pypi/colorama[/url] . On the other hand, it won't work if you are using idle or another IDE with a graphical user interface (each GUI widget has its own … | |
Re: You can use [code=python] from time import sleep sleep(1.5) # sleep 1.5 seconds [/code] The precision of the sleep depends on your system (see timemodule.c for implementation details). Also you may want to try [code=python] import os os.system("pause") [/code] Finally, if you want to wait until ENTER is pressed, simply … | |
Re: [QUOTE=jacob501;1712908]Wel...if you ignore all of that...what do you think about the gzip error. I don't understand it at all...[/QUOTE] The gzip error may happen because your site sometimes sends gzipped data and sometimes uncompressed data. I suggest a function which recognizes compressed data [code=python] from urllib2 import urlopen from gzip … | |
Re: I get a better result with [code=python] page = urllib2.urlopen('http://www.locationary.com/place/en/US/North_Carolina/Raleigh/Noodles_&_Company-p1022884996.jsp').read() [/code] (I replaced %26 with &) | |
Re: Did you try [icode]print repr(self.RX_BUFFER)[/icode] instead ? Your buffer may contain special characters which confuse the terminal screen. | |
Re: This discussion reminds me of a class that I wrote once to create an object which __dict__ is an arbitrary dictionary. It allows funny access to global variables like this [code=python] >>> class Odict(object): ... """Odict(dictionary) -> an object which __dict__ is dictionary""" ... def __init__(self, dictionary): ... self.__dict__ = … | |
Re: Or even [code=python] with open('Blueprints.txt','a') as file: file.write( "world.setBlockWithNotify(i {X}, j {Y}, k {Z}, Block.{B}.BlockID);" .format(X=X, Y=Y, Z=Z, B=B)) [/code] | |
Re: Another hint is this: for every permutation of 1, .. 6, like [code=python] (3, 2, 5, 1, 6, 4) [/code] you can generate 7 permutations of 1, ... 7 by inserting 7 somewhere, like in [code=python] (3, 2, 7, 5, 1, 6, 4) [/code] | |
Re: You could perhaps start with the statistics package in scipy: scipy.stats. Among other things, it contains classical tests like chisquared to test a sample against a known distribution (you must know some statistics to use this). See here [url]http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html[/url] | |
Re: Your tutorials may be written for python 2. You could try [code=python] ser.write(bytes('a', encoding='ascii')) # or ser.write(b'a') [/code] | |
Re: You can use the following [code=python] neededwordlist= ['a','p','p','l','e'] rawlist = ['a','l','p','p','e'] need, raw = list(neededwordlist), list(rawlist) # make copies for i in range(min(len(need), len(raw))): if need[i] == raw[i]: need[i] = raw[i] = '!' wrongposition = set(need) & set(raw) wrongposition.discard('!') print wrongposition """ --> my output set(['p', 'l']) """ [/code] The … | |
Re: Take a look at pyTony's snippet [url]http://www.daniweb.com/software-development/python/code/373120[/url] | |
Re: You need to post some code. The most obvious solution is to write a function reset_my_class_variables() and to call it when it is needed. | |
Re: You should provide more information and example data. If you are working in python 3, a way to write a raw integer is f.write(bytearray((n,)). Otherwise what are the types of the values prependByte, fileLength, pngChunk, etc ? | |
Re: Read this first, which explains arguments for optparse [url]http://www.alexonlinux.com/pythons-optparse-for-human-beings[/url] . You can do it also with argparse which is more recent and even better than optparse (see [url]http://www.doughellmann.com/PyMOTW/argparse/[/url]) | |
Re: Another way [code=python] >>> from operator import itemgetter >>> from itertools import groupby >>> dic = {'1': ['a', 'c'],'2': ['a', 'b', 'c'], '3': ['b']} >>> dict((x, list(t[1] for t in group)) for (x, group) in groupby(sorted(((j, k) for k, v in dic.items() for j in v), key=itemgetter(0)), key=itemgetter(0))) {'a': ['1', … | |
This snippet defines a function walk() which generically performs a depth-first traversal of a tree, using preorder, inorder or postorder rules. Here, genericity means here that there are no hypotheses on what the tree nodes are or the implementation of the tree. Walk() only needs an arbitrary object used as … | |
Re: I suggest to write another function numbered_line(n, start), then call this function. |
The End.