2,646 Posted Topics
Re: I suggest [code=python] # python 2 class Bot(object): def mainloop(self): while True: raw_input("? ") print("yes") if __name__ == "__main__": bot = Bot() bot.mainloop() [/code] as a starting point. | |
Re: You can test the number of children elements and the type of an element [code=python] data = """<item> <title>mytitle</title> <link></link> </item>""" from xml.dom.minidom import parseString, Element def genSimpleData(element, tag): """yield the string data for all subelements with the given tag which have a single text node child""" for node in … | |
Re: You can use this [code=python] # python 2 A = "gtggcaacgtgc" B = "gtagcagcgcgc" C = "gcggcacagggt" D = "gtgacaacgtgc" def cromo(a, b): assert len(a) == len(b) return sum(a[i] != b[i] for i in xrange(len(a))) print cromo(A, B) [/code] Boolean values can be summed, with True=1 and False=0. | |
Re: [QUOTE=LogicallyInsane;1430193]Is there any way to replace certain parts in a string of text with different text? Like this: [code=python]# This is not a functioning code, the actual meaning is totally different from what I'm trying to depict text = 'This is a line of text' print text # shows "This … | |
Re: [QUOTE=Scorpiusix;1429678][CODE] class x(object): def __init__(self): self.x=1 class z(object): def __init__(self): self.z=1 class y(x,z): def __init__(self): super(y, self).__init__() [/CODE] And what is it doing "super" function in here?[/QUOTE] It calls x.__init__(): [code=python] class x(object): def __init__(self): print ("x.__init__()") self.x=1 class z(object): def __init__(self): print ("z.__init__()") self.z=1 class y(x,z): def __init__(self): super(y, … | |
Re: [QUOTE=felix001;1429381]Thanks. Though still being exteremly new to python it still all looks pretty daunting.......[/QUOTE] A very good library for xml is lxml. See here [url]http://codespeak.net/lxml/tutorial.html[/url] | |
Re: There is a good recipe here [url]http://code.activestate.com/recipes/577024-yet-another-enum-for-python/[/url] | |
Re: [QUOTE=leazell;1415081]Hello, Thank you for your comments! Upon testing I notice that 4 still returns - it is a prime number. This is not correct. The numbers 2,3,5,7,11,13 and 17 and 19 are prime, the ones I skip here are not. Can you help me come up with a solution to … | |
Re: It may be correct or not. It seems that you're solving Burger's equation with a viscosity term, but equations with a laplacian don't easily solve backwards, so there are many questions: is the time T large or small ? What is the first PDE which you're solving in the direct … | |
Re: Why not [code=python] for row in reader: for item in row: print item [/code] ? Also learn about code tags here [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3[/url]. | |
Re: [QUOTE=richieking;1423732]mmmmmm python is strange. its only on python that new has broken loose i think. Thanks guys ;)[/QUOTE] [COLOR="Blue"]new[/COLOR] is a module in the standard library. | |
Re: I suspect it should be VALUES instead of VALUE. | |
Re: [QUOTE=FAITH2011;1419273][B][COLOR="Red"][B]Hi folk, I fairly new to Python 2.7 and Python 3 and like to find out how I would get a print to appear in the middle of the output screen without putting in a load of spaces into a print statement. Please keep it simple for me. Thanks for … | |
Re: Functions are not executed until you call them. So, if you want to execute f1 with the output of f2 as argument, you write [code=python] result = f1(f2(value)) [/code] You should post the whole code, it would be easier to debug. | |
Re: Your logic is not good. Write an algorithm [code=text] def read_book(): create word frequency dictionary (only once, not in a loop) open the file for each line in the file: split the line into words for each word in the line: increment the word's frequency (we don't need a word … | |
Re: $? is a shell variable. Each time you call os.system, python creates a new shell. Anyway, os.system() is deprecated, use subprocess.Popen [code=python] import subprocess as sp process = sp.Popen("cd /foo; echo $?", shell=True, stdout=sp.PIPE, stderr=sp.PIPE) print process.communicate() """ my output --> ('1\n', '/bin/sh: line 0: cd: /foo: Aucun fichier ou … | |
Re: Did you try [icode]df -h | grep YOUR_PTH | tr -s " " | cut -d -f6[/icode] in a console to see if it works ? Also you could probably write [code=python] command = "df -h | grep %s | tr -s \" \" | cut -d -f6" % pth … | |
Re: [code=python] print "the total number of animals is", sum(animals.values()) [/code] | |
Re: [QUOTE=convoluted;1411858]I should also mention that this example is just for display purposes and cold be implemented without threading, but I will be using threading to read and write to a controller area network. One thread will be dedicated to polling for data and the other thread will be uses for … | |
Re: If you want to read and then rewrite the file, you must open the file twice. You could use [code=python] def save_scores(score): try: with open('scores.txt', 'r') as scorefile: # this will automatically close the file scores = scorefile.readlines() except IOError: scores = [] scores.append(score) tempo = sorted(int(line) for line in … | |
Re: Can you run python idle.py from a terminal ? It would give you the error message ... (I never used a mac) | |
Re: [QUOTE=Peter_TARAS;1410051]Hi, I try to read line by line from a file some data. Each line in that file has the following format: x = 78.36734693877551, z = 11.428571428571429 -> amplitude: 8.62847057093655E-6 | phase -1.5707968246742405\n I am trying to extract those four float numbers using regular expression. I came with the … | |
Re: Here is a working version [code=python] #!/usr/bin/python3 import sys BUFSIZE = 4096 def make_streams_binary(): sys.stdin = sys.stdin.detach() sys.stdout = sys.stdout.detach() def main(): make_streams_binary() while True: data = sys.stdin.read(BUFSIZE) if not data: break sys.stdout.write(data) if __name__ == "__main__": main() [/code] Test in a console [code=text] $ chmod +x streams.py $ streams.py … | |
Re: Install a ssh server on the remote machine (eg copssh for windows) and use the module paramiko. | |
Re: I think the book means [code=python] def Max(L): if len(L) <= 1: if not L: raise ValueError("Max() arg is an empty sequence") else: return L[0] else: m = Max(L[1:]) return m if m > L[0] else L[0] [/code] but don't use it in real code, use the the builtin max … | |
Re: Finditer returns a sequence of 'match objects' from which you can extract the phrase [code=python] for match in regex.finditer(page): phrase = match.group(0) print("A phrase was found at position", match.start()) print(repr(phrase)) [/code] But I'm afraid there is an error in your regular expression, because the result of findall() shows that your … | |
Re: Write [code=python] def make_grid(x, value="0"): return [[value] * x for i in range(x)] grid = make_grid(5) [/code] | |
Re: can you post the code of your functions ? It all depends on the way the functions must be called. | |
Re: I think you should reinvent the wheel. Depending on the structure of the different fields, the code can be very short, for example [code=python] import re name_re = re.compile(r'^\w+$') def IsItAName(s): return name_re.match(s) is not None [/code] Do you have a description of all possible inputs ? | |
Re: write [code=python] set1 = Set() set1.setElements(elements) [/code] | |
Re: [code=python] # python 3 print(*(y,) * x, sep=",") [/code] | |
Re: You should probably write [code=python] cursor.execute(*sql) [/code] because your variable [icode]sql[/icode] is a tuple containing the arguments to cursor.execute. Also learn about code tags here [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3[/url] | |
Re: Your question doesn't mean anything. You can open and close an image file like any other file. Use the builtin [icode]open[/icode] function. See [url]http://docs.python.org/py3k/library/functions.html?highlight=open#open[/url] | |
Re: One way to do this is to write [code=python] exec ";".join(b+"=None" for b in buttons) [/code] immediately after line 9. However, it's a bad programming style. You should better use a dict, a list or a class instance. | |
Re: You must add a member function __str__ to the class, which returns a string representing the instance, for example [code=python] class Kort(object): ... def __str__(self): return "Kort({s},{f},{n},{g})".format( s = self.color, f = self.form, n = self.number, g = self.grade) [/code] | |
Re: line 25 should be while number < 2 or number > 30. By the way, [b]help[/b] is a very poor thread title. Try to be more descriptive of the thread's content. | |
Re: [QUOTE=wazaa;1406560]Oh sorry, the code is: [CODE]containers = [0] inp = input("Enter a weight, 20 or less, or enter 0 to quit: ") def findContainers(containers,inp): for i in range(0,len(containers)): if inp + containers[i] <= 20: return i elif inp + containers[len(containers)-1] > 20: return -1 def Allocator(containers,inp): x = 0 while … | |
Re: I would suggest using a helper class like this one [code=python] import re class Reader(object): header_re = re.compile(r"\xFF\x57\x50\x43") check_index = 10 def __init__(self, ifile, bufsize = 4096): self.ifile = ifile self.start = 0 # absolute file position at the beginning of the buffer self.bufsize = bufsize self.buffer = "" @property … | |
This snippet generates the best rational approximations of a floating point number, using the method of continued fractions (tested with python 2.6 and 3.1). | |
Re: [QUOTE=hbluthi;1405899]I'm making a Card class and need to make sure that the suit is valid. When I call on the Card class and construct one setting the suit to 'Jordan' it actually ok's that suit and prints 'Ace of Jordan'. Instead it should become the default, of Spades. What am … | |
Re: I suggest this [code=python] from turtle import * def snowflake(lengthSide, levels): if levels == 0: forward(lengthSide) return lengthSide /= 3.0 snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) right(120) snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) if __name__ == "__main__": speed(0) length = 300.0 penup() backward(length/2.0) pendown() snowflake(length, 4) [/code] | |
Re: Isn't it for the java forum ? | |
Re: You can use a regular expression [code=python] import re sp_regex = re.compile(r"[ \t]+$", re.MULTILINE) filename = "test.txt" with open(filename) as f_in: content = f_in.read() with open(filename, "w") as f_out: f_out.write(sp_regex.sub('', content)) [/code] | |
Re: @-ordi- : did you test this code ? is it yours ? the algorithm looks like the worst possible algorithm :) | |
Re: [url]http://docs.python.org/py3k/tutorial/introduction.html#lists[/url] ---> [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url] | |
Re: [code=python] word_list = [] for w in book_line.split(" "): if w != "": word_list.append(w.lower()) print word_list [/code] Indentation is very important. | |
Re: Read this first [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url] | |
Re: [QUOTE=ultimatebuster;1400621]I think you misunderstood my question. I'm wondering how you can get a system to "wait" for events.[/QUOTE] A simple way to wait for events in a thread is to use a Condition object and its wait method [code=python] cond = Threading.Condition() def mainloop(): "This function is executed by the … | |
Re: You can write [code=python] with open("output.txt", "w") as fileout: fileout.write(stdout_value) [/code] |
The End.