2,646 Posted Topics

Member Avatar for TrustyTony

There is also a solution using reduce() and itertools: [code=python] # python 2 import itertools as itt def add_pairs((a, b), (c, d)): return (a + c, b + d) iterable = xrange(10,20) total, size = reduce(add_pairs, itt.izip(iterable, itt.repeat(1))) print float(total) / size # prints 14.5 [/code] also, your function number() …

Member Avatar for Gribouillis
0
609
Member Avatar for mjohnson

[QUOTE=mjohnson;1677495][CODE]IOError: [Errno 2] No such file or directory:[/CODE][/QUOTE] This error means that the filename does not exist in the file system. This can be tested using os.path.isfile() [code=python] import os filename = raw_input("enter a path to a file: ") if not os.path.isfile(filename): print "There is no file %s." % repr(filename) …

Member Avatar for mjohnson
0
496
Member Avatar for sofia85

You could define 3 functions which take 2 arguments, a file opened for reading and a file opened for writing. Then you could use StringIO objects instead of temporary files on the disk. StringIO are memory files. They can be used like opened files (for reading or writing or appending). …

Member Avatar for Gribouillis
0
194
Member Avatar for fatalaccidents

You can compute the column widths and then generate a template for the format() method: [code=python] cells = [ [ 1, 5, 3, 1], [ 10, 23, 3, 23 ], [ 1, 122, 3, 233] ] scells = [[str(x) for x in line] for line in cells] columns = zip(*scells) …

Member Avatar for fatalaccidents
0
172
Member Avatar for abhik1368

Where are your program and effort to solve the problem ? Also what is a 'sort of csv file' ? Is it a csv file or not ?

Member Avatar for Gribouillis
0
138
Member Avatar for DarkFeather

Yes, [icode]mylist[2] += increment[/icode] for example increments the third item in mylist. Lists are mutable objects in python, which means that every item in the list can be replaced by any other value.

Member Avatar for DarkFeather
0
46
Member Avatar for felix001

I wrote a post on this once, using the format() method, see here [url]http://www.daniweb.com/software-development/python/code/232375/1025743#post1025743[/url]. Otherwise, there is an activestate recipe here [url]http://code.activestate.com/recipes/267662/[/url]

Member Avatar for felix001
0
326
Member Avatar for madtowneast

It does not seem difficult: your file has a simple structure: it's a series of blocks of text separated by blank lines. You read each block one after the other [code=python] from itertools import groupby def read_blocks(filename): """read a file as a sequence of blocks of rstripped non blank lines""" …

Member Avatar for madtowneast
0
156
Member Avatar for magnum_vf

I seems to me that you add a datetime.timedelta of one hour to a datetime.datetime to get a new datetime.datetime.

Member Avatar for magnum_vf
0
6K
Member Avatar for Gribouillis

This snippet composes functions of the form [icode]func(infile, outfile)[/icode] which read an input file and transform its content to write an output file. A function [icode]compose((f, g, h,...))[/icode] is defined which returns a new such file transformation function which successively applies f, g, h, using in-memory temporary files.

0
158
Member Avatar for hisan

[QUOTE=ret801;1677739]you might find the syntax you need here. [url]http://docs.python.org/library/thread.html[/url] you could make a for loop to make the 50 threads and make a nested for loop for each thread to call that function[/QUOTE] Don't revive old threads. Hisan probably managed creating his n threads a long time ago.

Member Avatar for Gribouillis
0
256
Member Avatar for Creatinas

Perhaps you could start by reading Doug Hellmann's python module of the week on the threading and multiprocessing modules: [url]http://www.doughellmann.com/PyMOTW/threading/index.html[/url] and [url]http://www.doughellmann.com/PyMOTW/multiprocessing/basics.html[/url] .

Member Avatar for Gribouillis
0
176
Member Avatar for dannyDaniweb

The normal procedure is to change directory to ..\temp\Polygon-2.0.4 in cygwin and type 'python setup.py install'.

Member Avatar for dannyDaniweb
0
366
Member Avatar for eikonal

I think the 'with open(...)' at line 13 should be indented at the same level as 'for i ...' from line 10. In the same way, you don't need the header file once it has been read, so line 7 could have the same indentation as line 5.

Member Avatar for Gribouillis
0
170
Member Avatar for oberlin1988

Better use random.shuffle(), or read this first [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url]

Member Avatar for Gribouillis
0
92
Member Avatar for vegaseat

[QUOTE=Baladya4;1675771]Can anyone provide an explanation for the "[c for c in phrase.lower() if c.isalpha()]" I understand that .lower() makes them lowercased and .isalpha makes sure they are alphabetical, however, I don't understand the syntax[/QUOTE] Learn about list comprehension syntax in the official documentation [url]http://docs.python.org/tutorial/datastructures.html#list-comprehensions[/url]

Member Avatar for Gribouillis
0
1K
Member Avatar for beck4456
Member Avatar for effBlam
Member Avatar for Gribouillis
0
94
Member Avatar for effBlam
Member Avatar for Gribouillis
0
92
Member Avatar for nered

Use [code=python] for x in range(len(maxHList)): ... [/code] and forget about x=0, x+=1, or use [code=python] for x in range(-1, len(maxHList)): ... [/code] depending on the desired result (sum 2 distances or 3 distances).

Member Avatar for Gribouillis
0
96
Member Avatar for geekman89

Here is the correct way to write and use classes [url]http://learnpythonthehardway.org/book/ex42.html[/url]

Member Avatar for geekman89
0
148
Member Avatar for sofia85

[QUOTE=pyTony;1674100]How about [code]sorted(set(open('f1')))[/code][/QUOTE] Or even better [code=python] with open('f2', 'w') as f2: with open('f1') as f1: f2.writelines(sorted(set(f1))) [/code]

Member Avatar for sofia85
0
144
Member Avatar for giancan

The question is what do you mean by 'well distributed' ? Consider a collection of 1000 real numbers. When will you say that they are well distributed on the real line ?

Member Avatar for Gribouillis
0
293
Member Avatar for MegaMan15

You can use a regular expression (the re module) to scan the text [code=python] import re text = """ %[girls_name] had a little %[animal], little %[animal], little %[animal], %[girls_name] had a little %[animal] its fleece was %[color] as snow. It followed her to %[place] one day, %[place] one day, %[place] …

Member Avatar for Gribouillis
0
115
Member Avatar for paraclete

You can use a second argument to split [code=python] >>> "1900 120 Date Night".split(" ", 2) ['1900', '120', 'Date Night'] [/code] Otherwise, use a regular expression (the re module).

Member Avatar for Gribouillis
0
145
Member Avatar for SK6114

see this snippet perhaps [url]http://www.daniweb.com/software-development/python/code/373120[/url]

Member Avatar for Gribouillis
0
117
Member Avatar for ljvasil

I think the problem is that you are using the same variable name 'row' for the inner loop. There also seems to be an indentation issue. Use [code=python] while row: ci = row.getValue(oid) fi = row.getValue("GRIDCODE") arcpy.AddMessage("The current GridCode value of this polygon is " + str(fi)) sql = oid …

Member Avatar for Gribouillis
0
428
Member Avatar for csterling

Don't open the files for writing, it will erase the files content !!! In fact you don't need to open the files at all. I suggest that you first create a dictionary newname --> oldname, this allows to detect the potential name collisions before renaming anything. Here is a possible …

Member Avatar for TrustyTony
0
2K
Member Avatar for SK6114

Here is your code with the correct indentation [code=python] def trap1 (f,a,b,delta , maxtraps=512): n=8 inew= trap0(f,a,b,n) iold=- inew while ( fabs(inew - iold)>delta * fabs( inew )): iold= inew n=2*n if n> maxtraps: print " Cannot reach requested accuracy with", \ maxtraps , " trapezia" return inew= trap0 (f,a,b,n) …

Member Avatar for TrustyTony
0
750
Member Avatar for giancan

[QUOTE=giancan;1668152]Nobody helps me? Even if I change the int to float, I still have problems, because now results with 10 zeros. I did a round(number,2) but it doesn't change that much. Any help?[/QUOTE] Can you post your code and attach your file and describe the expected result precisely ?

Member Avatar for giancan
0
141
Member Avatar for sainitin

If the second file is not too long, I suggest to load it and build a dictionary of pairs (key, value) with its content. It will be much faster than rereading the file for every entry in file 1 [code=python] def makedict(filename): pairs = list() with open(filename) as f: for …

Member Avatar for Gribouillis
0
166
Member Avatar for JoshuaBurleson

[QUOTE=pyguy62;1664241]also I've tried the same with [CODE]def search(self,val,event): pop_up(val)[/CODE]to make sure it wasn't just an issue of it being clicked on and having an extra event, as happens when binding '<Return>' to something.[/QUOTE] I suggest [icode]search(self, val=None)[/icode].

Member Avatar for JoshuaBurleson
0
192
Member Avatar for Tcll

I don't think you can translate C++ into python if you don't understand C++. Your program does not seem too difficult to translate for someone who knows both C++ and python. The good way to translate is to understand precisely what the C++ code does and to achieve the same …

Member Avatar for JoshuaBurleson
0
2K
Member Avatar for M.S.

In versions of python >= 2.3, there is a function random.sample() which does exactly what you need. [code=python] >>> L = range(100) >>> import random >>> random.sample(L, 3) [32, 93, 51] [/code] So, I think it would be a good solution to reuse the source code to write your own …

Member Avatar for M.S.
0
6K
Member Avatar for Gribouillis

Sometimes, you just want to run a system command from python and capture its output. Currently, the standard way to do this is to call the subprocess.Popen with convenient arguments and use the communicate method. After writing such code a few times, I wrote this little Command class to ease …

Member Avatar for deonis
4
3K
Member Avatar for Tsepang

You could start writing the sequence of actions and loops that the computer should do, like "create a deck", "shuffle the deck", "get input", "if input is Enter", etc. Write a flow chart on a sheet of paper. (Also what will your program do if the user enters "Ebter" or …

Member Avatar for Lee28
0
970
Member Avatar for TrustyTony

The -0.0 exists in the ieee 754 representation, it's zero with the sign bit set [code=python] >>> from binascii import hexlify >>> import struct >>> def ieee754(x): ... p = struct.pack("d", x) ... s = bin(int(b"1" + hexlify(p), 16))[3:] ... return " ".join(reversed([s[i:i+8] for i in xrange(0, len(s), 8)])) ... …

Member Avatar for Gribouillis
0
223
Member Avatar for Skrell

The method sort() sorts the list in place and returns None [code=python] >>> list1 = ['Herring','used','to','be','abundant','in','the','AtlAntic','Ocean','then','herring','got','overfished'] >>> list1.sort(key=lambda s : s.count('a')) >>> print list1 ['Herring', 'used', 'to', 'be', 'in', 'the', 'AtlAntic', 'then', 'herring', 'got', 'overfished', 'Ocean', 'abundant'] [/code] The function sorted() creates a new sorted list and does not modify …

Member Avatar for JoshuaBurleson
0
112
Member Avatar for CalculusG

There was a thread with exactly the same question recently, see here [url]http://www.daniweb.com/software-development/python/threads/378039/page2[/url]. Is this homework ? Read this too [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url]

Member Avatar for TrustyTony
0
209
Member Avatar for ihatehippies

The normal solution is to use a 'with' statement [code=python] from contextlib import contextmanager @contextmanager def threadmgr_running(*args, **kwd): threadmgr = ThreadManager(*args, **kwd) threadmgr.start() # or whatever try: yield threadmgr finally: threadmgr.waiting = False # in code with threadmgr_running(...) as threadmgr: etc # the threadmgr terminates automatically after this block [/code]

Member Avatar for ihatehippies
0
177
Member Avatar for Danielle87

I think the solution is to write more functions: [code=python] import random import re import time import sys data = [ "1. Principle of Segmentation: \n a) Divide an object into independent parts \n - Replace a large truck by a truck and trailer. \n - Use a work breakdown …

Member Avatar for Danielle87
0
356
Member Avatar for abders

[QUOTE=abders;1647167]I just finished a program, it worked perfectly, then I changed a bit of it, and now it won't work at all, even if I change it back. [CODE]self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD).grid(row = 3, column = 0, columnspan = 2, sticky = …

Member Avatar for abders
0
210
Member Avatar for hughesadam_87

The easiest solution is to have both Class A and Button_Manager inherit a common superclass which holds their common methods [code=python] class Common(object): def data_mod1(self): ... class A(Common): ... class Button_Manager(Common): ... [/code]

Member Avatar for TrustyTony
0
2K
Member Avatar for Reverend Jim

[QUOTE=Reverend Jim;1645504]Sorry about the earlier post. I realized what the problem was and I wanted to think about it for a while. Here is the question. How do I "negate" the effect of a "[" or "]" in a file name when I am doing globbing. For example, if my …

Member Avatar for Reverend Jim
0
116
Member Avatar for JoshuaBurleson

Google is your friend: [url]http://blogs.translucentcode.org/oisin/2003/09/04/tkinter_password_entry/[/url] or [url]http://effbot.org/tkinterbook/entry.htm[/url]

Member Avatar for Gribouillis
0
351
Member Avatar for JoshuaBurleson

If your address book is a console application, I suggest displaying a menu to choose from like [code=text] 'Bob' matches 4 contacts: 1. Bob Lastname 2. Bob Namelast 3. Bob 4. Bob enter your choice: [/code]

Member Avatar for Gribouillis
0
231
Member Avatar for philipshoe

There are many possible algorithms. If you can build a list with the digits, the built-in function [i]sum()[/i] could be a solution [code=python] >>> mylist = [4, 7, 5, 8] >>> sum(mylist) 24 [/code]

Member Avatar for TrustyTony
0
181
Member Avatar for TrustyTony

Interesting, however the get_op() method won't work if python is run in optimized mode (python -O) because this mode removes assert statements. Assert statements should not influence the program's flow of control, except for debugging purposes.

Member Avatar for TrustyTony
0
195
Member Avatar for poker158149

In python 3, after [icode]result = input(prompt)[/icode], result is a string in the python sense (an instance of the datatype 'str'). Examples of strings are [code=python] "" # the empty string " " # a string of white space "3.14159" # a string with the representation of a number "hello …

Member Avatar for poker158149
0
15K
Member Avatar for momartin

Use this snippet, it works well [url]http://www.daniweb.com/software-development/python/code/257449[/url] . Example (with a linux command) [code=python] >>> com = Command("ls -l").run() >>> if com.failed: ... print "ERROR" ... print com.error ... else: ... print com.output ... total 20 drwxr-xr-x 2 eric eric 4096 2011-09-02 14:35 cons drwxr-xr-x 10 eric eric 4096 2011-09-08 …

Member Avatar for Gribouillis
0
1K

The End.