2,646 Posted Topics
Re: The correct way to do this is [code=python] elif talk_in in ("quit", "q", "exit", "x"): etc [/code] | |
Re: The logical and in python is the [icode]and[/icode] operator, not the [icode]&[/icode] which is bitwise and. | |
Re: A standard way to save states between executions is to store persistent objects on disk. Look if the pickle module can help you. | |
Re: Here is a possible solution to this problem. I don't know if it's "optimal" (in which sense ?). However, you shouldn't reach a recursion limit, because the recursion depth is proportional to the logarithm of the length of the word. [code=python] #-*- coding: UTF-8 -*- class PermutatorException(Exception): pass class Permutator(object): … | |
Re: I would suggest this [code=python] tnls = [100, 250, 450, 650, 900, 1200, 1550, 1950, 2400, 2900] def LVL(): global level, xp if 1 <= level <= len(tnls): tnl = tnls[level-1] if tnl <= xp: level += 1 if level > len(tnls): level = 100 xp = 0 print("Your new … | |
Re: This script should work [code=python] import re, os pattern = re.compile("(\+|\-)?\d+\.txt") def find_name(): folder = "C:/Users/Sam/Desktop" for filename in os.walk(folder).next()[2]: if pattern.match(filename): return filename def main(): filename = find_name() number = int(filename[:-4]) newname = str(number-1) + ".txt" os.rename(filename, newname) print("file %s renamed %s" % (filename, newname)) main() [/code] You could … | |
Re: [icode]elif[/icode] and [icode]else[/icode] must have the same indentation than the corresponding [icode]if[/icode]. Edit: sorry, in your code, the 2 lines before the elif should be indented like the for statement above. | |
Re: [QUOTE=daviddoria;868291]If I have /home/doriad/Scripts/Python/ and inside I have a bunch of folders, ie Geometry, Math, Other, etc that each contain scripts (.py files), is there a way I can just add /home/doriad/Scripts/Python to PYTHONPATH and then somehow [code] from Geometry/Spherical import * [/code] rather than having to add every subdirectory … | |
Re: You could replace the [icode]for field in row[/icode] part by this [code=python] fields = [f for f in row[1:6] if f] if fields: print "%s,%s" %(PCID, fields[0]) else: raise Exception("No field for %s" % PCID) [/code] | |
Re: You could start idle like this in a terminal [code] idle -r complicated_nonsense.py [/code] Another way is to run python with the PYTHONSTARTUP environment variable set to the file complicated_nonsense.py. It will then be executed when you start the interpreter. | |
Re: I have all these tricks in my notes. I found all this somewhere on the web. See if it works ! [code=python] # linux, mac os.kill(pid, signal.SIGKILL) killedpid, stat = os.waitpid(pid, os.WNOHANG) if killedpid == 0: print >> sys.stderr, "ACK! PROCESS NOT KILLED?" # windows handle = subprocess.Popen("someprocess here", shell=False) … | |
![]() | Re: [code] >>> L = range(1, 10) >>> L [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> reduce(int.__mul__, L) 362880 >>> [/code] but there are other problems in your program :) for example [icode]float[/icode] should be [icode]int[/icode]. Also, what is b ? |
Re: The pickle format is encoded. If you want to output the list in plain text, you could try this [code=python] from pprint import pprint pprint(mu1List, fileHandle) [/code] | |
Re: I posted a [url=http://www.daniweb.com/code/snippet1032.html]code snippet[/url] for this kind of problems. It's an elementary solution, but it works. A more sophisticated approach is to use the standard module [icode]cmd[/icode] | |
Re: You don't even need regexes: your file is 'object orientated' ;) I fact in your file, there is a list of 'blocks'. Each block has a headline (the 1st line) and the other lines are lists of pairs key/value which can be readily transformed into dictionaries (2 pairs are separated … | |
Re: Please, use [url=http://www.daniweb.com/forums/announcement114-3.html]code tags[/url]. Your program is unreadable. | |
Re: And don't forget to read [url=http://www.daniweb.com/forums/announcement114-2.html]this announcement[/url] about homework. | |
Re: In this [url=http://en.wikipedia.org/wiki/Adder_(electronics)]wikipedia page[/url], you have a description of a half adder I think A, B, C, S are your variables i1, i2, o1, o2. There is a table showing all possible inputs and outputs. | |
Re: You could as well use a regex like this [code=python] import re pattern = re.compile("J=(\d+)") def Digit(line): match = pattern.search(line) if match is None: return 0 else: return len(match.group(1)) print (Digit("28 J=5202,5204,7497,7498 SEC=WALL1")) print (Digit("1185 J=289,3875,2673 SEC=SLAB2")) """ my output ---> 4 3 [/code] | |
Re: Transposition plus reversing each line should give you a rotation of the matrix. This question of the 'likeness' of 2 lists is very interesting. I think you should check the Levenshtein distance between 2 strings, which measures the 'likeness' of 2 character strings. You will easily find a python implementation … | |
Re: google is your friend [url]http://commons.wikimedia.org/wiki/File:Dragon_curve.png[/url] | |
Re: You can use [code=python] while an not in (a, b): ... [/code] | |
Re: I suggest this [code=python] ... for k, word in enumerate(response): ... word += "ay" response[k] = word return " ".join(response) [/code] The problem is that your code modifies the variable 'word', but not the strings stored in the list. For example [code=python] >>> L = ["hello", "world"] >>> word = … | |
Re: I think this function should help you [code=python] import re keyPatt = re.compile(r"\b\w+=") testData='name="My Mobile Blog" url="http://caydab565.blogspot.com/" name="Creative Disaster" url="http://kevinlara.blogspot.com/" ...' def gen_pairs(dataString): key, pos = None, 0 for match in keyPatt.finditer(dataString): startPos, endPos = match.span() if key is not None: value = dataString[pos:startPos].strip() yield (key, value) key, pos = … | |
Re: You don't need to add atimer. You can call the instance's method 'after' [code=python] after_id = my_widget.after(milliseconds, myFunction, arg1, arg2, arg3) [/code] The returned Id can be used like this [code=python] my_widget.after_cancel(after_id) [/code] to cancel the timer. | |
Re: I made a small experiment: [code=python] >>> class A(object): ... def __init__(self): ... self.value = 12 ... >>> a = A() >>> class B(A): ... def printvalue(self): ... print self.value ... >>> a.__class__ = B >>> a.printvalue() 12 [/code] so the object 'a' was turned into a 'B'. What do … | |
Re: I think the problem is in your arguments list for Popen: [code=python] >>> cmd = "awk '{print $0}'" >>> cmd.split(' ') ['awk', "'{print", "$0}'"] [/code] It should be [icode]['awk', "'{print $0}'"][/icode]. | |
Re: Starting with python 2.5, you can write [code=python] print("You Win!" if playerWins else "You lose!") [/code] The syntax is [icode]value = expressionA if conditionExpression else expressionB[/icode]. Note that the condition is always computed first, and only one of A an B is executed. | |
Re: You can use the 'index' method [code=python] >>> line = '<b>(words only):</b><font color= "#0000FF"> BABY MILESTONES</font><br /><br />' >>> line.index("B") 44 >>> line.index("<", 44) # 44 is the number of chars before BABY MILESTONES 59 >>> line[44:59] 'BABY MILESTONES' [/code] | |
![]() | Re: Perhaps you could start with the [url=http://wiki.wxpython.org/AnotherTutorial#head-0df444402c06def691ecaad400df75aef7d0c7b4]wx.ScrolledWindow example[/url] in wxpython's another tutorial, which displays an image. ![]() |
Re: There are many ways to do this. One of them is to append your characters to a list instead of printing them directly. Then you join the list items with an empty string and you print the result. [code=python] alph = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',\ 'q','r','s','t','u','v','w','x','y','z'] num =[2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9] phone = raw_input('enter phone number … | |
Re: I found [url=http://code.google.com/p/pyftpdlib/]this link[/url], which should work. | |
Re: You should set your environment variable PYTHONSTARTUP to your file. See [url]http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP[/url] | |
Re: This source code seems to contain other solutions [url]http://code.google.com/p/timeout-urllib2/source/browse/trunk/timeout_urllib2.py[/url]. Also the urllib module in python 3.0 (and may be 2.6?) seems to accept a timeout parameter for urlopen. | |
Re: If you want to define a "small" object, you can always use __slots__, for example you could define [code=python] class my_int(object): __slots__ = ["value", "initial"] def __init__(self, i=0): self.value = self.initial = int(i) def __int__(self): return self.value def reset(self): self.value = self.initial # etc [/code] | |
Re: Use [icode]os.rename(src, dst)[/icode]. For example [code=python] import os os.rename("foo.py", "bar.py") [/code] See [url]http://docs.python.org/library/os.html#os.rename[/url]. | |
Consider the following script [code=python] #!/usr/bin/env python # foo.py import sys print sys.argv [/code] When I run this in a terminal with arguments, here is the output [code] $ ./foo.py -h hello -m "this is a string" ['./foo.py', '-h', 'hello', '-m', 'this is a string'] [/code] My question is: is … | |
Re: I think you could use the standard module difflib. | |
Re: I suggest this [code=python] from binascii import hexlify L = ["00", "01", "10", "11"] LL = [u+v for u in L for v in L] s = "0123456789abcdef" D = dict((s[i], LL[i]) for i in range(16)) jpeg = open('encjpgfile', 'rb').read() bits = ''.join(D[x] for x in hexlify(jpeg)) print(bits) [/code] | |
Re: Well, first in both files, each line starts with a number which seems to identify the country, then the country name, then the rest. First write a function to parse a line [code=python] import re pattern = re.compile(r"(\d)+\s+(\w+)") def parseLine(line): "returns a triple (country_number, country_name, rest)" match = pattern.match(line) return … | |
Re: If you want to write non reversible python code, you could encrypt the python code and decrypt it at run time with a non reversible C++ encryption routine. | |
Re: You can try a formula like this one [code=python] from zlib import compress def score(stringA, stringB): a = len(compress(stringA)) b = len(compress(stringB)) c = len(compress(stringA + stringB)) return 1.0 -(0.0 +a +b -c )/max (a ,b ) [/code] It should return a number close to 0.0 if the 2 strings … | |
Re: Here is a script [code=python] class Device(object): def __init__(self, number): self.number = number self.items = {} def getDevices(logPath): source = (line.strip() for line in open(logPath)) device_list = [] prefix_dev = "Device #: " prefix_test = "Test: " try: while True: while True: line = source.next() if line.startswith(prefix_dev): device = Device(line[len(prefix_dev):].strip()) … | |
Re: A nice module to handle XML is lxml ([url]http://codespeak.net/lxml/[/url]). I use it to handle html data. I think it's easier to use than the standard library. Also it has a support for xml shema [url]http://codespeak.net/lxml/validation.html#xmlschema[/url] | |
Re: It's because [icode]os.system[/icode] waits that the subprocess is finished. You should not use [icode]os.system[/icode] anymore in python. Use the subprocess module [code=python] import subprocess child_process = subprocess.Popen("nautilus", shell=True) [/code] This won't wait for the subprocess. See the documentation of the subprocess module for more complex usage. | |
Re: I think the problem is that you misspelled the [icode]def receive[/icode], so that you defined a [icode]recieve[/icode] function. | |
Re: [QUOTE=Max721;823675]If you are removing elements from array B according to A code should look like this [code] int A[]={1,3,5}; int B[]={12,24,36,48,60,72}; int C[3]={0,0,0}; int length =sizeof(A)/sizeof(A[0]); for (unsigned int i=0;i<length;i++) { C[i]=B[A[i]-1]; printf("%d ",C[i]); } [/code][/QUOTE] It's true, but this is the python forum, not the C forum :) | |
Re: There is also [icode]line = line[:-1][/icode] to remove the last character. I think vegaseat meant the indentation of your python source code. It's better to indent your code with space characters instead of tab characters. You should configure your editor so that it prints 4 space characters when you hit … | |
Re: You can write a function to split the list according to an arbitrary criterion [code=python] def cut_list(thelist, criterion): """ cut_list(list, function) -> list of lists splits a list into sublists according to a given criterion. Here a criterion is a function of 2 arguments func(item1, item2) -> True if the … | |
Re: You could start looking in this recent thread, how information was grabbed from a web site [url]http://www.daniweb.com/forums/thread179633.html[/url] using the urllib2 module to read the web pages and the BeautifulSoup module (not in the standard library) to extract information from the pages. |
The End.