2,646 Posted Topics
Re: 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 … | |
Re: The main reason is that a 20 lines python program does more job than a 500 lines C++ program. | |
Re: [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 … | |
Re: 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: … | |
Re: 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() … | |
Re: 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. | |
| |
Re: 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) … | |
Re: 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] | |
Re: Lines 18 and 19 should not be indented, and should use a call to ask_number(). Also there should be a loop somewhere. | |
Re: Notice that [code=python] >>> 111111111**2 == 12345678987654321 True [/code] | |
Re: 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, … | |
Re: 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. | |
Re: 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]. | |
Re: 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 … | |
![]() | Re: Use [code=python] array = [[float(x) for x in line.strip().split()] for line in open("file.txt")] [/code] |
Re: 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] | |
Re: 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 … | |
Re: 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. | |
Re: 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 … | |
Re: 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 :) | |
Re: 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] . | |
Re: Why do you need to run it with python 3 ? Doesn't your linux system have a python 2 version ? | |
Re: Use the wait() method on a Threading.Event object or a Threading.Condition object, with a timeout. | |
Re: I suggest that you start contributing to the porting of other gui toolkits to python 3 ! | |
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. | |
| |
Re: 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', … | |
Re: 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] | |
Re: 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 … | |
Re: 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. … | |
Re: 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 ? | |
Re: Use zip [code=python] pairs = zip(itemlist, recordlist) [/code] | |
Re: 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] | |
Re: 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] | |
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. | |
Re: 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, … | |
Re: 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 … | |
Re: You can use eval [code=python] thelist = eval(open("file.txt").read().strip()) [/code] | |
Re: 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], … | |
Re: [code=python] import random selection = random.sample(cards, 3) [/code] | |
Re: You should first check the server by using a standard ftp client like filezilla. | |
Re: 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] | |
Re: See also this excellent tutorial [url]http://www.alexonlinux.com/pythons-optparse-for-human-beings[/url] | |
Re: [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 … | |
Re: 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] | |
Re: [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] … | |
Re: 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): … | |
Re: [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 … |
The End.