2,646 Posted Topics

Member Avatar for Gribouillis

This snippet defines a function [icode]a2bits[/icode] which converts a characters string to a string of 0's and 1's showing its bitwise representation.

Member Avatar for Gribouillis
0
2K
Member Avatar for Krstevski

Your [icode]<a href="http://www.google.com/">Google</a>[/icode] is not a text node in your html document, but a [icode]<a>[/icode] node. You should probably write something like [code=python] from xml.dom.minidom import Document doc = Document() link = doc.createElement("a") link.attributes["href"] = "http://www.google.com/" google = doc.createTextNode("Google") link.appendChild(google) doc.appendChild(link) print doc.toxml() """ my output --> <?xml version="1.0" ?> …

Member Avatar for Gribouillis
0
446
Member Avatar for acehigher

Start with a script which prints the lines one by one [code=python] SOURCE_FILE = "myfile.srt" def main(): with open(SOURCE_FILE) as src_file: for line in src_file: print(repr(line)) if __name__ == "__main__": main() [/code]

Member Avatar for Gribouillis
0
103
Member Avatar for tcl76

The problem is that the int representation doesn't see the leading zeroes [code=python] >>> data1 = 0x0000001800000400000000000000000000000000000000000000000000000000fe00000000000000000000000000000000000000000000000000000000ffffff >>> data2 = 0x1800000400000000000000000000000000000000000000000000000000fe00000000000000000000000000000000000000000000000000000000ffffff >>> data1 == data2 True [/code] A solution is to add a leading "1" to your string and to remove the "1" when you convert back to a string.

Member Avatar for Gribouillis
0
5K
Member Avatar for tcl76

I managed to do it like this [code=python] def bintohex(s): t = ''.join(chr(int(s[i:i+8],2)) for i in xrange(0, len(s), 8)) return binascii.hexlify(t) [/code] All of this would be easier with python >= 2.6 because of the builtin [icode]bin[/icode] function. See this code snippet for example [url]http://www.daniweb.com/code/snippet221031.html[/url]. In python 2.6, you could …

Member Avatar for TrustyTony
0
3K
Member Avatar for yeleek

Use [icode]zip[/icode] [code=python] for i, a in zip(var1, var2): print i print a [/code] Items are printed until the shortest list is consumed.

Member Avatar for yeleek
0
101
Member Avatar for Parth tank

[QUOTE=Parth tank;1481975]which data type use in paythone[/QUOTE] Perhaps you are looking for this page [url]http://docs.python.org/library/stdtypes.html[/url] ?

Member Avatar for Gribouillis
0
52
Member Avatar for joeywheels

[QUOTE=joeywheels;1481681]Hi everyone! New here and to Python. I'm having trouble with my break statement executing and cannot figure out why. I'm learning to write to files and want the loop to break if the user hits enter. It's not working for some reason. I've even tried to get fancy (in …

Member Avatar for joeywheels
0
107
Member Avatar for wilko1995

Another explanation is to translate in pseudo code [code=text] how to move n disks from a to c using b as middle ? if n is 0: do nothing else: move n-1 disks from a to b using c as middle move the last disk from a to c move …

Member Avatar for TrustyTony
0
117
Member Avatar for paramaster

[QUOTE=paramaster;1479345]Hello daniweb community, i'm new to all this and i'm pretty happy that found this. Anyway i'm having sevral issues. Frist one is: my Python GUI (IDLE) won't open program. [CODE]def num(n): count=0 while count <= abs(n): count = count + 1 n= abs(n)/10 print count num(-23) [/CODE] This code …

Member Avatar for paramaster
0
190
Member Avatar for Ghostenshell

At line 8, you are not using the list returned by createRandnums(), and you are passsing h_nums to oss() at line 11 instead of the list. Also I can't see where the list is sorted. If the list is sorted, you should have a look in the [b]bisect[/b] module to …

Member Avatar for Gribouillis
0
97
Member Avatar for MacUsers

You could try [code=python] parser.add_option("-m", "--month", type="string", help="select month from 01|02|...|12", dest="mon") parser.add_option("-u", "--user", type="string", help="name of the user", dest="vos") options, arguments = parser.parse_args() if not options.vos and not options.mon: options.mon = strftime("%m") if options.mon: abbrMonth = tuple(month_abbr)[int(options.mon)] [/code]

Member Avatar for MacUsers
0
209
Member Avatar for Micko

[QUOTE=mithundas;1477091]how to import an existing python file and run it in an python shell....[/QUOTE] Start by reading this [url]http://docs.python.org/tutorial/modules.html[/url] . Also you can start a new thread if you have more questions.

Member Avatar for danholding
0
2K
Member Avatar for dragon_sagrado

Can't you just call [code=python] seno = seno_taylor(x+1, a) [/code] ?

Member Avatar for BearofNH
0
233
Member Avatar for Python_nooby

I think there is a method askopenfilname() which returns only a file name instead of an open file. Otherwise, file objects have an attribute 'name' which you could use.

Member Avatar for slate
0
885
Member Avatar for tcl76

A first hint from the IronPython faq [url]http://ironpython.codeplex.com/wikipage?title=FAQ[/url] : [code=text] How do I compile .py files to a DLL for linking into my C# or VB program? IronPython does not support building DLLs for a C# style of linking and calling into Python code. You can define interfaces in C#, …

Member Avatar for snippsat
0
214
Member Avatar for needsHelp!

[QUOTE=needsHelp!;1473326]Please help me with, creating an checker board!! this is all i got right now [CODE]from cs1graphics import * n = 8 paper = Canvas(400, 400) for y in range(n) : for x in range(n) : square = Square(100) square.moveTo(x*50, y*50) paper.add(square) [/CODE][/QUOTE] I tested your code and it works, …

Member Avatar for Gribouillis
0
103
Member Avatar for HelloPeople1

Here is a simple context to store the high scores in a csv file [code=python] from contextlib import contextmanager import csv @contextmanager def scorelist(filename): """Maintain a csv file with a list of scores""" try: with open(filename, "rb") as fin: reader = csv.reader(fin, delimiter=",") L = [ (row[0], int(row[1])) for row …

Member Avatar for woooee
0
262
Member Avatar for Ghostenshell

[code=python] >>> range(3,-1,-1) [3, 2, 1, 0] [/code] Also, consider using the collections.deque class for stacks and queues.

Member Avatar for Gribouillis
0
102
Member Avatar for yeticannotski

I suggest to call the following function to ensure the target directories exist [code=python] def make_target_dirs(target_paths): for dirname in set(os.path.dirname(p) for p in target_paths): if not os.path.isdir(dirname): os.makedirs(dirname) [/code] Edit: to attach a .py file, zip it first, then attach the zipped file.

Member Avatar for yeticannotski
0
3K
Member Avatar for tottletj

Use the format() method [code=python] # python >= 2.6 numbers = [ 123456.78, 3434.2 ] for x in numbers: print( "The number is {num:0>9.2f}".format(num=x) ) """ my output --> The number is 123456.78 The number is 003434.20 """ [/code] See this code snippet for more [url]http://www.daniweb.com/code/snippet232375.html[/url] :)

Member Avatar for Gribouillis
0
160
Member Avatar for GDICommander

This may help: [url]http://stackoverflow.com/questions/488449/can-a-python-script-persistently-change-a-windows-environment-variable-elegantl[/url] The answer with the use of the [b]setx.exe[/b] program looks interesting. If windows has a program to modify environment variables from the command line, a python script can easily call this program with the subprocess module. Another direction is to use ironpython instead of python, and …

Member Avatar for GDICommander
0
2K
Member Avatar for ub007

See the standard modules getopt and optparse [url]http://docs.python.org/lib/module-getopt.html[/url] and [url]http://docs.python.org/lib/module-optparse.html[/url]

Member Avatar for richieking
0
228
Member Avatar for CharlieNewey

Here is another way to code this [code=python] import math def fsum(f, g, pairs): return sum(f(x)*g(y) for (x,y) in pairs) def one(x): return 1.0 def ident(x): return x def square(x): return x*x def plog(x): return x * math.log(x) def fit(pairs): pairs = list(pairs) si, op, ii, ip, oi = [ …

Member Avatar for CharlieNewey
0
688
Member Avatar for Fluffybunny

Many people who mix java and python use jython (a java based python) instead of python, which allows them to access java classes directly from python. In other versions of python, you must use the subprocess module. I have a code snippet with a Command class here [url]http://www.daniweb.com/code/snippet257449.html[/url] You can …

Member Avatar for Gribouillis
0
111
Member Avatar for runge_kutta
Member Avatar for runge_kutta
0
2K
Member Avatar for Archenemie

> I realise i could import a module to do the same functions i wrote. > > The point was simply learning an efficient way to call methods between classes. > > The way i solved this was: class Callable: def __init__(self, function): self.__call__ = function class func: def addition(a, …

Member Avatar for Archenemie
0
180
Member Avatar for razax

After the first [icode]l.pop(0)[/icode], the list is [icode]["asd'das",'qw','213'][/icode], so the second item is 'qw'.

Member Avatar for razax
0
216
Member Avatar for MasterMic

You can use [icode]itertools.permutations[/icode] to rotate over all the numbers [code=python] import itertools for p in itertools.permutations(range(1, 5)): print(p) (1, 2, 3, 4) (1, 2, 4, 3) (1, 3, 2, 4) (1, 3, 4, 2) (1, 4, 2, 3) (1, 4, 3, 2) (2, 1, 3, 4) (2, 1, 4, …

Member Avatar for MasterMic
0
269
Member Avatar for rubik-pypol

I note that your module computes the roots of polynomials by bisection. This is a primitive way to find the roots and there are many other methods (see for example this article [url]http://en.wikipedia.org/wiki/Root-finding_algorithm[/url]). I hope you intend to strengthen pypol on this point. I once reviewed a few methods available …

Member Avatar for rubik-pypol
0
408
Member Avatar for funfullson

[QUOTE=funfullson;1402925]Friends, no one use an interface with this ability? So if you want to trace your codes step by step, How do u do it? Lets discuss stronger. Lets List all _or at least more important_ interfaces of python that use in different operation systems. for example a list of …

Member Avatar for funfullson
0
169
Member Avatar for novice20

To see if an object can be converted to something else, you must find its class and look in the object's class documentation, so try this first: [code=python] print(type(obj)) print(obj.__class__) [/code]

Member Avatar for LoveMyPadres
0
2K
Member Avatar for Boubakr

You can use time.time() [code=python] import time before = time.time() somme = raw_input('1 + 1 = ') diff = time.time() - before # time difference in seconds as a floating point number [/code]

Member Avatar for richieking
0
167
Member Avatar for Thropian
Member Avatar for Thropian
0
282
Member Avatar for woofers

Among the possible issues: 1/ The threading.Thread class has a special rule: [i]If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.[/i]. See [url]http://docs.python.org/library/threading.html#threading.Thread[/url] .This is a frequent source of errors, so you should move line …

Member Avatar for woofers
0
147
Member Avatar for woofers

Try this [code=python] D = dict() exec b in D [/code] Also learn about code tags here [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3[/url] :) Also note that network security rules prohibit using 'exec' on a piece of code received from a public network. This may potentially run arbitrary code on your computer.

Member Avatar for woofers
0
157
Member Avatar for ddndd

A list of old recipes. [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) subprocess.Popen("taskkill /F /T /PID %i"%handle.pid , shell=True) #also # Create a process that won't end on …

Member Avatar for Gribouillis
0
16K
Member Avatar for _neo_

I could not parse it with csv, but if your string looks like python code, you can use python's own tokenizer: [code=python] # python 2 and 3 import sys if sys.version_info < (3,): from cStringIO import StringIO else: from io import StringIO xrange = range from tokenize import generate_tokens a …

Member Avatar for Gribouillis
0
10K
Member Avatar for -ordi-

[QUOTE=-ordi-;1434001][CODE]from copy import deepcopy sis = file("teedtest.01.sis", "r") val = file("rp.val", "wt") N, K = map(int, sis.readline().strip().split()) alist = [] for i in range(0, K): t = [] for i in range(0, K): t.append(0) alist.append(t) for i in range(K): a, b, c = map(int, sis.readline().strip().split()) alist[a][b] = alist[b][a] = c …

Member Avatar for TrustyTony
0
182
Member Avatar for superhe

Your method [icode]_new_[/icode] should be named [icode]__init__[/icode] (note the double underscore on each side of the word init)

Member Avatar for richieking
0
285
Member Avatar for novice20
Member Avatar for foren

Try something like [code=python] from __future__ import print_function from os.path import join as pjoin DIR = pjoin("c:","Fummy_Tasks", "RECONSTR_ANALYSIS", "04052010", "test1_Strings") def stripped_lines(filename): with open(pjoin(DIR, filename), "rb") as fin: for line in fin: yield line.strip() def memdump(): return stripped_lines("test.txt") def evidence(): return stripped_lines("word1.txt") def main(outfile): cnt = 0 for line in …

Member Avatar for olaji
0
95
Member Avatar for linux

You could add a hierarchy of classes [code=python] class Hero: # contains methods common to all heroes ... class Lord(Hero): # contains methods specific to Lords ... class MainHero(Lord): # contains main hero specific methods ... phill = MainHero(...) [/code] Don't nest classes, it is more annoying than useful. Write …

Member Avatar for richieking
0
5K
Member Avatar for Blackberryy

[QUOTE=Blackberryy;1410683]Anybodyy? really need help with this[/QUOTE] Post you code for drawing a single rectangle, the rest will be easy.

Member Avatar for richieking
0
2K
Member Avatar for vbx_wx

Use [icode]index = bisect.bisect(list, num)[/icode]. The list must be sorted. Also, don't use 'list' as a variable name.

Member Avatar for -ordi-
0
117
Member Avatar for Harris00
Member Avatar for JJHT7439

Here is a working __str__ function [code=python] class NonEmptyEnv(object): __slots__ = ('letter','digit','rest') def __init__(self,letter,digit,rest): self.letter = letter self.digit = digit self.rest = rest def __str__(self): result = self.letter + "=" + str(self.digit) if isinstance(self.rest, NonEmptyEnv): result += ',' + str(self.rest) return result [/code] Otherwise, your solution is overly complicated. You …

Member Avatar for TrustyTony
0
334
Member Avatar for TheSassyDragon

I used a tracer module and got the following output [code=text] 0. GUIcards.runGame(): # call, line 280 in blackjack.py 1. GUIcards.game_over(): # call, line 135 in blackjack.py return False return None [/code] So what happened is that your first call to game_over() returned False at line 135 and the body …

Member Avatar for Gribouillis
0
115
Member Avatar for yond

Each call to a recursive function uses a new set of local variables. It means the the inner call to countSubStringMatchRecursive will use another count variable, and the count variable of the calling function is not changed. The simplest way to understand recursion is to think about it the way …

Member Avatar for TrustyTony
0
102
Member Avatar for novice20

Use a regular expression (module re) [code=python] import re digits_colon_re = re.compile(r"(?P<digits>\d+)\:") data = """ 4:14.4-17M,5:14.4-2e13M,6:14.4-4e9M,7:14.4-8e,22:28.4-35M,23:28.4-2e30M, 24:28.4-4e26M,25:28.4-8e18M,26:28.4-16e2M,27:28.4-18e,28:14.16-36M,29:14.16-2e32M, 30:14.16-4e28M,31:14.16-8e20M """.strip().replace("\n", "").split(",") print([int(match.group("digits")) for match in (digits_colon_re.search(s) for s in data)]) """ my output ---> [4, 5, 6, 7, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] """ [/code]

Member Avatar for novice20
0
109

The End.