2,646 Posted Topics

Member Avatar for Zebibyte

The correct way to do this is [code=python] elif talk_in in ("quit", "q", "exit", "x"): etc [/code]

Member Avatar for Gribouillis
0
131
Member Avatar for nunos

The logical and in python is the [icode]and[/icode] operator, not the [icode]&[/icode] which is bitwise and.

Member Avatar for nunos
0
411
Member Avatar for DustinS

A standard way to save states between executions is to store persistent objects on disk. Look if the pickle module can help you.

Member Avatar for Gribouillis
0
111
Member Avatar for wasala

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): …

Member Avatar for wasala
0
150
Member Avatar for Norbert X

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 …

Member Avatar for Norbert X
0
645
Member Avatar for frank.zappa

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 …

Member Avatar for frank.zappa
0
400
Member Avatar for gotm

[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.

Member Avatar for woooee
0
180
Member Avatar for daviddoria

[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 …

Member Avatar for vegaseat
0
2K
Member Avatar for comfixit

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]

Member Avatar for targ
0
286
Member Avatar for chardson

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.

Member Avatar for chardson
0
180
Member Avatar for JDCyrus

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) …

Member Avatar for woooee
0
5K
Member Avatar for leegeorg07

[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 ?

Member Avatar for jlm699
0
259
Member Avatar for planetPlosion

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]

Member Avatar for Gribouillis
0
82
Member Avatar for Undermine

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]

Member Avatar for Gribouillis
0
123
Member Avatar for ning2009

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 …

Member Avatar for ning2009
0
348
Member Avatar for srk619

Please, use [url=http://www.daniweb.com/forums/announcement114-3.html]code tags[/url]. Your program is unreadable.

Member Avatar for srk619
0
101
Member Avatar for srk619

And don't forget to read [url=http://www.daniweb.com/forums/announcement114-2.html]this announcement[/url] about homework.

Member Avatar for srk619
0
146
Member Avatar for srk619

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.

Member Avatar for srk619
0
2K
Member Avatar for ning2009

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]

Member Avatar for ning2009
0
107
Member Avatar for tillaart36

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 …

Member Avatar for tillaart36
0
247
Member Avatar for srk619

google is your friend [url]http://commons.wikimedia.org/wiki/File:Dragon_curve.png[/url]

Member Avatar for srk619
0
98
Member Avatar for Coolprogram
Member Avatar for woooee
0
143
Member Avatar for down with socks

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 = …

Member Avatar for down with socks
0
186
Member Avatar for dilipkk

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 = …

Member Avatar for Gribouillis
0
131
Member Avatar for harrykokil

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.

Member Avatar for Gribouillis
0
54
Member Avatar for Z8934

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 …

Member Avatar for Gribouillis
0
159
Member Avatar for sharat87

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].

Member Avatar for sharat87
0
4K
Member Avatar for shadwickman

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.

Member Avatar for shadwickman
0
116
Member Avatar for loren41

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]

Member Avatar for sneekula
0
258
Member Avatar for leegeorg07

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.

Member Avatar for leegeorg07
0
316
Member Avatar for FengG

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 …

Member Avatar for FengG
0
6K
Member Avatar for shailev

I found [url=http://code.google.com/p/pyftpdlib/]this link[/url], which should work.

Member Avatar for Gribouillis
0
57
Member Avatar for tehbrozor

You should set your environment variable PYTHONSTARTUP to your file. See [url]http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP[/url]

Member Avatar for tehbrozor
0
132
Member Avatar for dilipkk

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.

Member Avatar for dilipkk
0
4K
Member Avatar for ls129

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]

Member Avatar for Gribouillis
0
167
Member Avatar for lakhan.p

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].

Member Avatar for Gribouillis
0
71
Member Avatar for Gribouillis

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 …

Member Avatar for Gribouillis
0
168
Member Avatar for JeyC
Member Avatar for alicem

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]

Member Avatar for jlm699
0
6K
Member Avatar for chebude

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 …

Member Avatar for chebude
0
137
Member Avatar for siddhant3s

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.

Member Avatar for sneekula
0
773
Member Avatar for blair.mayston

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 …

Member Avatar for Gribouillis
0
108
Member Avatar for sparso

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()) …

Member Avatar for Gribouillis
0
186
Member Avatar for neqinox

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]

Member Avatar for Gribouillis
0
25
Member Avatar for billySometimes

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.

Member Avatar for Gribouillis
0
92
Member Avatar for snowfish

I think the problem is that you misspelled the [icode]def receive[/icode], so that you defined a [icode]recieve[/icode] function.

Member Avatar for snowfish
0
388
Member Avatar for super zach

[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 :)

Member Avatar for Max721
0
323
Member Avatar for mahela007

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 …

Member Avatar for Gribouillis
0
118
Member Avatar for patelmitul

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 …

Member Avatar for Gribouillis
0
378
Member Avatar for Rooking

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.

Member Avatar for Gribouillis
0
100

The End.