2,646 Posted Topics

Member Avatar for danholding

Here is a good way to do this. The key points are[LIST] [*]use generators [*]use list comprehensions [*]use [icode]sorted()[/icode] and it's 'key' argument [/LIST] [code=python] # python 2 and 3 import os # write a generator to decouple the code which creates the data # from the code which uses …

Member Avatar for TrustyTony
0
240
Member Avatar for vlad44

The main reason is that a 20 lines python program does more job than a 500 lines C++ program.

Member Avatar for vlad44
0
133
Member Avatar for c_shaft05

[QUOTE=kjock002;1128497]hi im actually doing the same thing for a lab in my programming class but im having such a hard time to make the table for celcius to fahrenheit. this is what i have so far and i need some help. #convert.py # A program to convert Celsius temps to …

Member Avatar for Duskic
0
434
Member Avatar for Simplified

It seems to be an impossible behaviour. To speak about something concrete, I ran the following code [code=python] # python 2 and 3 from __future__ import print_function def main(): valid = str("4CE1FFC64101843801") with open("stamps", "w") as stamps: stamps.write(valid) with open("stamps", "r") as stamps: check = stamps.read() print("valid: ", valid) print("check: …

Member Avatar for Simplified
0
108
Member Avatar for iamdabobo

You could write [code=python] def evaluator(funct, name='funct'): code = compile(funct, name, 'eval') def f(x): return eval(code, locals()) f.__name__ = name return f def integ(funct,a,b): return gauss(a, b, evaluator(funct)) print integ("3*x++5", 0, 1) [/code] because the expression is evaluated in a dictionary where there is a variable named x (the locals() …

Member Avatar for Gribouillis
0
2K
Member Avatar for cwarn23

You could try to convert the C code from the files shamodule.c, sha256module.c and sha512module.c in the python source distribution, which provide the sha algorithms for the hashlib module.

Member Avatar for cwarn23
0
173
Member Avatar for knan
Member Avatar for Thropian

First I think it can be shortened to [code=python] def view(N,W,E,S): t = (N, W, S, E) st = ("north", "west", "south", "east") ft = (fhall, lfhall, frhall, frlhall) d = st.index(info_dict["direction"]) if t[d] != 1: pic = fwall wall = "yes" else: x, y = t[(d+1) % 4], t[(d+3) …

Member Avatar for Gribouillis
0
90
Member Avatar for haojam

You could normalize the unique terms using a regular expression: [code=python] import re item_pattern = re.compile(r"[a-zA-Z][a-z]*|[^\s]") def tuple_key(composite_term): return tuple(w.lower() for w in item_pattern.findall(composite_term)) def normalize(term): return ' '.join(tuple_key(term.strip())) print normalize("Characteristics [StrainOrLine]") """my output --> characteristics [ strain or line ] """ [/code]

Member Avatar for haojam
0
690
Member Avatar for longlongsilver

Lines 18 and 19 should not be indented, and should use a call to ask_number(). Also there should be a loop somewhere.

Member Avatar for longlongsilver
0
923
Member Avatar for TrustyTony
Member Avatar for TrustyTony
1
874
Member Avatar for sneek

If you want to get a C string out of a python object, if the object is a python string you should use [code=c] char * s = PyString_AsString(pyobj); [/code] and then use s as a read only C string. If you don't know if the object is a string, …

Member Avatar for Gribouillis
0
2K
Member Avatar for knan

Start with this documentation page [url]http://docs.python.org/tutorial/floatingpoint.html[/url]. A problem is that python's 0.1 is not the mathematical 0.1 because 0.1 can not be represented exactly as a machine binary number.

Member Avatar for knan
0
202
Member Avatar for HoneyBadger

In the function [icode]in_common()[/icode] when the if fails, there is no return statement, so it returns None. Also in most situations you don't need [icode]if expression == True[/icode]. Simply write [icode]if expression:[/icode].

Member Avatar for richieking
0
101
Member Avatar for Banjoplucker

Why don't you write [code=python] for each in wp_head: print "Word Perfect header %s found @ offset %d" % ( each.group(), total_data_read + each.start()) [/code] ? Another issue to consider is that a match could occur between 2 blocks, for example \xFF\x57 at the end of a 4096 bytes block …

Member Avatar for Banjoplucker
0
109
Member Avatar for tottletj

Use [code=python] array = [[float(x) for x in line.strip().split()] for line in open("file.txt")] [/code]

Member Avatar for Gribouillis
1
105
Member Avatar for n3red

I know how to do it using the pari library [code=python] >>> from pari import factor >>> x = 252 >>> g = factor(x, x) >>> zip(*(eval(str(g[i])[:-1]) for i in (0,1))) [(2, 2), (3, 2), (7, 1)] [/code]

Member Avatar for TrustyTony
0
493
Member Avatar for wolvo

You could save the following module as uservars.py [code=python] # module uservars class UserVars(object): __slots__ = ('LIMITS','Maxrock','Maxstar') def __getattr__(self, attr): if not attr in self.__slots__: raise AttributeError(attr) value = raw_input("Enter variable %s: " % attr) setattr(self, attr, value) return value uservars = UserVars() [/code] Then in every other file, you …

Member Avatar for Gribouillis
0
139
Member Avatar for WildBamaBoy

I suggest [icode]def round32(x): return (x+16) & ~31[/icode]. As tonyjv said, we much choose if 16 should be rounded to 0 or 32. This rounds to 32. Otherwise add 15 instead of 16.

Member Avatar for Gribouillis
0
2K
Member Avatar for keltik

Yes but is had to do with class design. A few remarks:[LIST] [*]A subclass' __init__ method must usually call the parent class' __init__. [*]PlayerHand should not be a subclass of CardDeck. You should create a common superclass, say CardList and subclass both PlayerHand and CardDeck from CardList [*]It's a bad …

Member Avatar for Gribouillis
0
80
Member Avatar for kuchi

Use string order [code=python] >>> "20091128" < "20101118" True [/code] This will work for all dates with 8 characters. edit: to avoid the Y10K syndrome, choose woooee's solution :)

Member Avatar for Gribouillis
0
82
Member Avatar for bwbyron

You should first read this [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3[/url] and this [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url] .

Member Avatar for TrustyTony
0
211
Member Avatar for maofree

Why do you need to run it with python 3 ? Doesn't your linux system have a python 2 version ?

Member Avatar for maofree
0
390
Member Avatar for ekkanh

Use the wait() method on a Threading.Event object or a Threading.Condition object, with a timeout.

Member Avatar for richieking
0
405
Member Avatar for gunbuster363

I suggest that you start contributing to the porting of other gui toolkits to python 3 !

Member Avatar for richieking
0
223
Member Avatar for Gribouillis

This snippet defines a function to merge sorted iterables containing similar items into a single iterable. Items are supposed to be sorted in ascending order. Only one item per iterable is stored at a time.

Member Avatar for Gribouillis
0
598
Member Avatar for longlongsilver
Member Avatar for c2q

Write a recursive function [code=python] # python 2 and 3 def splitmany(s, seps=""): if seps: u, seps = seps[0], seps[1:] for word in s.split(u): for item in splitmany(word, seps): yield item else: yield s if __name__ == "__main__": print(list(splitmany('hello. world! hello.', "!."))) """my output --> ['hello', ' world', ' hello', …

Member Avatar for ultimatebuster
0
624
Member Avatar for singlem1905

Your question is cryptic. Could you give full examples of input and expected output, and the output you get from your efforts, and possibly your code ? Also read these annoucements [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3[/url] and [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url]

Member Avatar for TrustyTony
0
78
Member Avatar for qdiscoverer

Here is how you should write this [code=python] class ECollector: #error msg collector #this class should be used as 'global' def __init__(self): self.msgs = [] def addmsg(self,msg): self.msgs.append(msg) def clear(self): self.msgs = [] class test(ECollector): def __init__(self): ECollector.__init__(self) self.dcodes = [] def new(self): self.addmsg("test!") [/code] You are mistaking classes for …

Member Avatar for Gribouillis
0
335
Member Avatar for king_koder

Assuming N > 0, when you fire the last time, the monster must have C1 or C2 heads. Assuming you fired x times with gun A and y times with gun B before this last shot, then you have the equation N + x*(G1-C1) + y*(G2-C2) = C1 or C2. …

Member Avatar for slate
0
507
Member Avatar for Tcll

You can't append 3 values to a list [code=python] TypeError: append() takes exactly one argument (3 given) [/code] Further, what is this vec() function ?

Member Avatar for Tcll
0
814
Member Avatar for Tommymac501
Member Avatar for pythonlearning

Define a score function [code=python] def score(item): return int(item[0]) z = {'11': [0, 1], '3': [1, -2, 3], '4':[2, 3], '2':[3, -4, 5], '0':[4]} sorted_z = sorted(z.iteritems(), key=score) print "z=", sorted_z for i in range(len(sorted_z)): print sorted_z[i][0], " ".join(str(x) for x in sorted_z[i][1]) [/code]

Member Avatar for pythonlearning
0
149
Member Avatar for xtra333

You must test wether the tree is a single value or not [code=python] def printexp(tree): left, right = tree.getLeft(), tree.getRight() sRoot = str(tree.getRootValue()) if left or right: assert left and right return "(%s %s %s)" % (printexp(left), sRoot, printexp(right)) else: return sRoot [/code]

Member Avatar for TrustyTony
0
309
Member Avatar for Gribouillis

This snippet defines 3 functions to create in a few seconds an image of a graph containing arbitrary python objects. It uses the module pygraphviz (available at [url]http://pypi.python.org/pypi/pygraphviz/[/url]). See the example use case at the end of the module.

Member Avatar for woooee
1
1K
Member Avatar for TrustyTony

And here is the code to create an image of the data, using the snippet [url]http://www.daniweb.com/code/snippet323792.html[/url] [code=python] data = ["Apollo 13, Kevin Bacon, Tom Hanks, Gary Sinise", "Hollow Man, Elisabeth Shue, Kevin Bacon, Josh Brolin", "A Few Good Men, Tom Cruise, Demi Moore, Jack Nicholson, Kevin Bacon", "One Crazy Summer, …

Member Avatar for TrustyTony
0
1K
Member Avatar for JasonQiao

Here is a pattern which seems to work [code=python] from __future__ import print_function import re pat = re.compile( r"^(?P<X>\d+)(?:(?: (?P<Y>\d+)/(?P<Z>\d+))|[.](?P<T>\d*))?$" ) def test_pat(data): print("TEST_PAT", repr(data)) match = pat.match(data) if not match: print("no match") return for symbol in "XYZT": print("%s: %s," % (symbol, repr(match.group(symbol))), end = " ") print("") test_pat("3.35") test_pat("12 …

Member Avatar for Gribouillis
0
307
Member Avatar for planetPlosion

You can use eval [code=python] thelist = eval(open("file.txt").read().strip()) [/code]

Member Avatar for Gribouillis
0
113
Member Avatar for Smed

Use list comprehensions [code=python] >>> L = [ list(range(1+k, 4+k)) for k in range(0,9,3)] >>> L [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> LL = [x[:2] for x in L] + [[x[0], x[2]] for x in L] >>> LL [[1, 2], [4, 5], [7, 8], [1, 3], …

Member Avatar for Gribouillis
0
113
Member Avatar for Swedenrock
Member Avatar for Gribouillis
0
163
Member Avatar for novice20
Member Avatar for novice20
0
1K
Member Avatar for ekkanh

This should return a list [icode][('filename1.txt', '<content>'), ('filename2.txt', '<content>'), ..][/icode] [code=python] def thefunction(): filenames = list(x.strip() for x in list(open("name.txt", "rb")) if x.strip()) return [(n, open(n, "rb").read()) for n in filenames] [/code]

Member Avatar for Gribouillis
0
105
Member Avatar for novice20

See also this excellent tutorial [url]http://www.alexonlinux.com/pythons-optparse-for-human-beings[/url]

Member Avatar for Gribouillis
0
63
Member Avatar for king_koder

[QUOTE=slate;1377983]You are right. But cannot solve every problem in one strike :). The [U]whole[/U] solution to this euler problem is significant shorter. [URL="http://snipplr.com/view/35007/project-euler--problem-11/"]Spoiler[/URL][/QUOTE] I have an even shorter whole solution [code=python] from functools import reduce from operator import mul s=''' 08 02 22 97 38 15 00 40 00 75 …

Member Avatar for king_koder
0
404
Member Avatar for HoneyBadger
Member Avatar for marboleon

Quote from the wx.PaintDC doc: [b]If you have an EVT_PAINT handler, you must create a wx.PaintDC object within it even if you don't actually use it.[/b]. So you should perhaps try [code=python] def OnPaint(self, event): dc = wx.PaintDC(self) sendbf() [/code]

Member Avatar for TrustyTony
0
181
Member Avatar for testie

[QUOTE=testie;1379517]Oh, I forgot to mention that I can't copy over another list. I have to do all of it with that 1 list. Sorry guys.[/QUOTE] Then start with the end of the list [code=python] def del_odd(l): for i in range(len(l)-1, -1, -1): if l[i] % 2 != 0: del l[i] …

Member Avatar for Gribouillis
0
145
Member Avatar for TrustyTony

You can easily modify the code above so that the polynomials get changed on mouse click: [code=python] import itertools import random import wx import wx.lib.fancytext as fancytext class FancyText(wx.Panel): """display fancytext on a panel""" def __init__(self, parent): wx.Panel.__init__(self, parent, wx.ID_ANY) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_LEFT_UP, self.OnClick) self.xml_str = xml_str() def OnPaint(self, evt): …

Member Avatar for Gribouillis
1
764
Member Avatar for ljjfb

[QUOTE=ljjfb;1376119]Dear all experts, I tried several options on this issue, such as: [CODE] import subprocess, os, signal, time proc1 = subprocess.Popen("gnome-terminal", shell=True) print proc1.pid time.sleep(1.0) proc1.kill() # or os.kill(proc1.pid, signal.SIGKILL) [/CODE] The method I used can not kill the child process "proc1". While, if I erase the time.sleep(1.0), it seems …

Member Avatar for ljjfb
0
16K

The End.