2,646 Posted Topics
Re: 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() … | |
Re: [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) … | |
Re: 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). … | |
Re: 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) … | |
Re: 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 ? | |
Re: 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. | |
Re: 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] | |
Re: 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""" … | |
Re: I seems to me that you add a datetime.timedelta of one hour to a datetime.datetime to get a new datetime.datetime. | |
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. | |
Re: [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. | |
Re: 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] . | |
Re: The normal procedure is to change directory to ..\temp\Polygon-2.0.4 in cygwin and type 'python setup.py install'. | |
Re: 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. | |
Re: Better use random.shuffle(), or read this first [url]http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2[/url] | |
Re: [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] | |
Re: Any python tutorial should answer the OP's question. | |
Re: [code=python] print(' '.join(''.join(z[0] for z in y) for y in x)) [/code] | |
Re: [code=python] print( [x[-1] for x in double_list] ) [/code] | |
Re: 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). | |
Re: Here is the correct way to write and use classes [url]http://learnpythonthehardway.org/book/ex42.html[/url] | |
Re: [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] | |
Re: 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 ? | |
Re: 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] … | |
Re: 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). | |
Re: see this snippet perhaps [url]http://www.daniweb.com/software-development/python/code/373120[/url] | |
Re: 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 … | |
Re: 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 … | |
Re: 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) … | |
Re: [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 ? | |
Re: 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 … | |
Re: [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]. | |
Re: 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 … | |
Re: 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 … | |
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 … | |
Re: 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 … | |
Re: 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)])) ... … | |
Re: 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 … | |
Re: 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] | |
Re: 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] | |
Re: 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 … | |
Re: [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 = … | |
Re: 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] | |
Re: [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 … | |
Re: 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] | |
Re: 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] | |
Re: 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] | |
Re: 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. | |
Re: 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 … | |
Re: 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 … |
The End.