2,646 Posted Topics

Member Avatar for vik.singh

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.

Member Avatar for richieking
0
83
Member Avatar for Krstevski

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 …

Member Avatar for Krstevski
0
7K
Member Avatar for vbx_wx

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.

Member Avatar for woooee
0
207
Member Avatar for LogicallyInsane

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

Member Avatar for vegaseat
0
119
Member Avatar for night_guard

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

Member Avatar for Gribouillis
0
183
Member Avatar for felix001

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

Member Avatar for griswolf
0
138
Member Avatar for novice20

There is a good recipe here [url]http://code.activestate.com/recipes/577024-yet-another-enum-for-python/[/url]

Member Avatar for novice20
0
126
Member Avatar for leazell

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

Member Avatar for Thisisnotanid
0
6K
Member Avatar for Simplicity.

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 …

Member Avatar for Simplicity.
0
246
Member Avatar for novice20

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

Member Avatar for richieking
0
266
Member Avatar for Brickmack

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

Member Avatar for richieking
0
271
Member Avatar for kiddo39
Member Avatar for FAITH2011

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

Member Avatar for FAITH2011
0
167
Member Avatar for Simplicity.

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.

Member Avatar for Simplicity.
0
142
Member Avatar for HoneyBadger

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 …

Member Avatar for seanbp
0
145
Member Avatar for novice20

$? 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 …

Member Avatar for novice20
0
132
Member Avatar for dark3lf

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 …

Member Avatar for dark3lf
2
196
Member Avatar for Boonzo

[code=python] print "the total number of animals is", sum(animals.values()) [/code]

Member Avatar for Gribouillis
0
114
Member Avatar for convoluted

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

Member Avatar for Gribouillis
0
259
Member Avatar for bwbyron

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 …

Member Avatar for bwbyron
0
201
Member Avatar for Gh0st93

Can you run python idle.py from a terminal ? It would give you the error message ... (I never used a mac)

Member Avatar for Gribouillis
0
872
Member Avatar for Peter_TARAS

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

Member Avatar for Gribouillis
0
179
Member Avatar for liran

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 …

Member Avatar for Gribouillis
0
2K
Member Avatar for novice20

Install a ssh server on the remote machine (eg copssh for windows) and use the module paramiko.

Member Avatar for novice20
0
3K
Member Avatar for jrp370

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 …

Member Avatar for Gribouillis
0
2K
Member Avatar for Safia Abdalla

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 …

Member Avatar for griswolf
0
12K
Member Avatar for coril

Write [code=python] def make_grid(x, value="0"): return [[value] * x for i in range(x)] grid = make_grid(5) [/code]

Member Avatar for Gribouillis
0
265
Member Avatar for furret

can you post the code of your functions ? It all depends on the way the functions must be called.

Member Avatar for Gribouillis
0
137
Member Avatar for nosehat

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 ?

Member Avatar for richieking
0
131
Member Avatar for corrwee
Member Avatar for SgtMe
0
248
Member Avatar for coril
Member Avatar for hisan

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]

Member Avatar for hisan
0
6K
Member Avatar for PhEnSciLaBu

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]

Member Avatar for PhEnSciLaBu
0
290
Member Avatar for SomeKittens

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.

Member Avatar for Gribouillis
0
272
Member Avatar for Swedenrock

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]

Member Avatar for TrustyTony
0
121
Member Avatar for dmurder
Re: help

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.

Member Avatar for TrustyTony
0
88
Member Avatar for wazaa

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

Member Avatar for wazaa
0
134
Member Avatar for Banjoplucker

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 …

Member Avatar for richieking
0
121
Member Avatar for Gribouillis

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

Member Avatar for Gribouillis
1
1K
Member Avatar for hbluthi

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

Member Avatar for hbluthi
0
659
Member Avatar for Oldguy1

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]

Member Avatar for ohernandezmit
0
3K
Member Avatar for tk-421
Member Avatar for Naynah
Member Avatar for polanski

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]

Member Avatar for richieking
0
161
Member Avatar for Hawkeye Python

@-ordi- : did you test this code ? is it yours ? the algorithm looks like the worst possible algorithm :)

Member Avatar for Gribouillis
0
3K
Member Avatar for Naynah

[url]http://docs.python.org/py3k/tutorial/introduction.html#lists[/url] ---> [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url]

Member Avatar for Naynah
0
164
Member Avatar for HoneyBadger

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

Member Avatar for HoneyBadger
0
3K
Member Avatar for tk-421

Read this first [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url]

Member Avatar for TrustyTony
0
13K
Member Avatar for ultimatebuster

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

Member Avatar for ultimatebuster
0
156
Member Avatar for ljjfb

You can write [code=python] with open("output.txt", "w") as fileout: fileout.write(stdout_value) [/code]

Member Avatar for richieking
0
191

The End.