title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Reversing a regular expression in Python
492,716
<p>I want to reverse a regular expression. I.e. given a regular expression, I want to produce <em>any</em> string that will match that regex.</p> <p>I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)</p> <p>I'm using Python, so I'd like a Python library.</p> <p>To reiterate, I only want <em>one</em> string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.</p> <p>I'm willing for this library to only work on a certain subset of regex.</p>
33
2009-01-29T18:05:22Z
492,728
<p>Unless your regex is extremely simple (i.e. no stars or pluses), there will be infinitely many strings which match it. If your regex only involves concatenation and alternation, then you can expand each alternation into all of its possibilities, e.g. <code>(foo|bar)(baz|quux)</code> can be expanded into the list <code>['foobaz', 'fooquux', 'barbaz', 'barquux']</code>.</p>
5
2009-01-29T18:08:43Z
[ "python", "regex" ]
Reversing a regular expression in Python
492,716
<p>I want to reverse a regular expression. I.e. given a regular expression, I want to produce <em>any</em> string that will match that regex.</p> <p>I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)</p> <p>I'm using Python, so I'd like a Python library.</p> <p>To reiterate, I only want <em>one</em> string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.</p> <p>I'm willing for this library to only work on a certain subset of regex.</p>
33
2009-01-29T18:05:22Z
492,733
<p>I haven't seen a Python module to do this, but I did see a (partial) implementation in Perl: <a href="http://search.cpan.org/~bowmanbs/Regexp-Genex-0.07/lib/Regexp/Genex.pm" rel="nofollow"><code>Regexp::Genex</code></a>. From the module description, it sounds like the implementation relies on internal details of Perl's regular expression engine, so it may not be useful even from a theoretical point of view (I haven't investigated the implementation, just going by the comments in the documentation).</p> <p>I think doing what you propose in general is a hard problem and may require the use of nondeterministic programming techniques. A start would be to parse the regular expression and build a parse tree, then traverse the tree and build sample string(s) as you go. Challenging bits will probably be things like backreferences and avoiding infinite loops in your implementation.</p>
2
2009-01-29T18:09:52Z
[ "python", "regex" ]
Reversing a regular expression in Python
492,716
<p>I want to reverse a regular expression. I.e. given a regular expression, I want to produce <em>any</em> string that will match that regex.</p> <p>I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)</p> <p>I'm using Python, so I'd like a Python library.</p> <p>To reiterate, I only want <em>one</em> string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.</p> <p>I'm willing for this library to only work on a certain subset of regex.</p>
33
2009-01-29T18:05:22Z
496,603
<p>I don't know of any module to do this. If you don't find anything like this in the Cookbook or PyPI, you could try rolling your own, using the (undocumented) re.sre_parse module. This might help getting you started:</p> <pre><code>In [1]: import re In [2]: a = re.sre_parse.parse("[abc]+[def]*\d?z") In [3]: a Out[3]: [('max_repeat', (1, 65535, [('in', [('literal', 97), ('literal', 98), ('literal', 99)])])), ('max_repeat', (0, 65535, [('in', [('literal', 100), ('literal', 101), ('literal', 102)])])), ('max_repeat', (0, 1, [('in', [('category', 'category_digit')])])), ('literal', 122)] In [4]: eval(str(a)) Out[4]: [('max_repeat', (1, 65535, [('in', [('literal', 97), ('literal', 98), ('literal', 99)])])), ('max_repeat', (0, 65535, [('in', [('literal', 100), ('literal', 101), ('literal', 102)])])), ('max_repeat', (0, 1, [('in', [('category', 'category_digit')])])), ('literal', 122)] In [5]: a.dump() max_repeat 1 65535 in literal 97 literal 98 literal 99 max_repeat 0 65535 in literal 100 literal 101 literal 102 max_repeat 0 1 in category category_digit literal 122 </code></pre>
10
2009-01-30T18:27:24Z
[ "python", "regex" ]
Reversing a regular expression in Python
492,716
<p>I want to reverse a regular expression. I.e. given a regular expression, I want to produce <em>any</em> string that will match that regex.</p> <p>I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)</p> <p>I'm using Python, so I'd like a Python library.</p> <p>To reiterate, I only want <em>one</em> string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.</p> <p>I'm willing for this library to only work on a certain subset of regex.</p>
33
2009-01-29T18:05:22Z
502,074
<p>Although I don't see much sense in this, here goes:</p> <pre><code>import re import string def traverse(tree): retval = '' for node in tree: if node[0] == 'any': retval += 'x' elif node[0] == 'at': pass elif node[0] in ['min_repeat', 'max_repeat']: retval += traverse(node[1][2]) * node[1][0] elif node[0] == 'in': if node[1][0][0] == 'negate': letters = list(string.ascii_letters) for part in node[1][1:]: if part[0] == 'literal': letters.remove(chr(part[1])) else: for letter in range(part[1][0], part[1][1]+1): letters.remove(chr(letter)) retval += letters[0] else: if node[1][0][0] == 'range': retval += chr(node[1][0][1][0]) else: retval += chr(node[1][0][1]) elif node[0] == 'not_literal': if node[1] == 120: retval += 'y' else: retval += 'x' elif node[0] == 'branch': retval += traverse(node[1][1][0]) elif node[0] == 'subpattern': retval += traverse(node[1][1]) elif node[0] == 'literal': retval += chr(node[1]) return retval print traverse(re.sre_parse.parse(regex).data) </code></pre> <p>I took everything from the <a href="http://docs.python.org/library/re.html#regular-expression-syntax">Regular Expression Syntax</a> up to groups -- this seems like a reasonable subset -- and I ignored some details, like line endings. Error handling, etc. is left as an exercise to the reader.</p> <p>Of the 12 special characters in a regex, we can ignore 6 completely (2 even with the atom they apply to), 4.5 lead to a trivial replacement and 1.5 make us actually think.</p> <p>What comes out of this is not too terribly interesting, I think.</p>
15
2009-02-02T02:59:15Z
[ "python", "regex" ]
Reversing a regular expression in Python
492,716
<p>I want to reverse a regular expression. I.e. given a regular expression, I want to produce <em>any</em> string that will match that regex.</p> <p>I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)</p> <p>I'm using Python, so I'd like a Python library.</p> <p>To reiterate, I only want <em>one</em> string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.</p> <p>I'm willing for this library to only work on a certain subset of regex.</p>
33
2009-01-29T18:05:22Z
509,879
<p>While the other answers use the re engine to parse out the elements I have whipped up my own that parses the re and returns a minimal pattern that would match. (Note it doesn't handle [^ads], fancy grouping constructs, start/end of line special characters). I can supply the unit tests if you really like :)</p> <pre><code>import re class REParser(object): """Parses an RE an gives the least greedy value that would match it""" def parse(self, parseInput): re.compile(parseInput) #try to parse to see if it is a valid RE retval = "" stack = list(parseInput) lastelement = "" while stack: element = stack.pop(0) #Read from front if element == "\\": element = stack.pop(0) element = element.replace("d", "0").replace("D", "a").replace("w", "a").replace("W", " ") elif element in ["?", "*"]: lastelement = "" element = "" elif element == ".": element = "a" elif element == "+": element = "" elif element == "{": arg = self._consumeTo(stack, "}") arg = arg[:-1] #dump the } arg = arg.split(",")[0] #dump the possible , lastelement = lastelement * int(arg) element = "" elif element == "[": element = self._consumeTo(stack, "]")[0] # just use the first char in set if element == "]": #this is the odd case of []&lt;something&gt;] self._consumeTo(stack, "]") # throw rest away and use ] as first element elif element == "|": break # you get to an | an you have all you need to match elif element == "(": arg = self._consumeTo(stack, ")") element = self.parse( arg[:-1] ) retval += lastelement lastelement = element retval += lastelement #Complete the string with the last char return retval def _consumeTo(self, stackToConsume, endElement ): retval = "" while not retval.endswith(endElement): retval += stackToConsume.pop(0) return retval </code></pre>
4
2009-02-04T02:36:11Z
[ "python", "regex" ]
Reversing a regular expression in Python
492,716
<p>I want to reverse a regular expression. I.e. given a regular expression, I want to produce <em>any</em> string that will match that regex.</p> <p>I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)</p> <p>I'm using Python, so I'd like a Python library.</p> <p>To reiterate, I only want <em>one</em> string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.</p> <p>I'm willing for this library to only work on a certain subset of regex.</p>
33
2009-01-29T18:05:22Z
5,006,339
<p>Check out the <a href="http://utilitymill.com/utility/Regex_inverter" rel="nofollow">regex inverter at UtilityMill</a>. (Source code is viewable, based on <a href="http://pyparsing.wikispaces.com/file/view/invRegex.py" rel="nofollow">this example</a> from the pyparsing wiki.)</p>
4
2011-02-15T16:25:00Z
[ "python", "regex" ]
Reversing a regular expression in Python
492,716
<p>I want to reverse a regular expression. I.e. given a regular expression, I want to produce <em>any</em> string that will match that regex.</p> <p>I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)</p> <p>I'm using Python, so I'd like a Python library.</p> <p>To reiterate, I only want <em>one</em> string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.</p> <p>I'm willing for this library to only work on a certain subset of regex.</p>
33
2009-01-29T18:05:22Z
9,118,086
<p>Somebody else had a similar (duplicate?) question <a href="http://stackoverflow.com/questions/4627464/generate-a-string-that-matches-a-regex-in-python">here</a>, and I'd like to offer a little helper library for <a href="https://bitbucket.org/leapfrogdevelopment/rstr/">generating random strings with Python</a> that I've been working on.</p> <p>It includes a method, <code>xeger()</code> that allows you to create a string from a regex:</p> <pre><code>&gt;&gt;&gt; import rstr &gt;&gt;&gt; rstr.xeger(r'[A-Z]\d[A-Z] \d[A-Z]\d') u'M5R 2W4' </code></pre> <p>Right now, it works with most basic regular expressions, but I'm sure it could be improved.</p>
16
2012-02-02T18:45:41Z
[ "python", "regex" ]
Reversing a regular expression in Python
492,716
<p>I want to reverse a regular expression. I.e. given a regular expression, I want to produce <em>any</em> string that will match that regex.</p> <p>I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)</p> <p>I'm using Python, so I'd like a Python library.</p> <p>To reiterate, I only want <em>one</em> string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.</p> <p>I'm willing for this library to only work on a certain subset of regex.</p>
33
2009-01-29T18:05:22Z
17,595,038
<p>I have recently done automatic regex reversal in C++: <a href="http://www.benhanson.net/lexertl/blog.html#rev_regex1" rel="nofollow">http://www.benhanson.net/lexertl/blog.html#rev_regex1</a></p> <p>To get a Python version it would be quite easy to write a code generator to output Python code for lexertl. I'm not that up on Python, but if you'd like to help with syntax, I'm happy to create a file to do that.</p>
1
2013-07-11T13:43:06Z
[ "python", "regex" ]
python: restarting a loop
492,860
<p>i have:</p> <pre><code>for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop </code></pre> <p>But that doesn't seem to work. Is there a way to restart that loop? </p> <p>Thanks</p>
9
2009-01-29T18:37:51Z
492,864
<p>Changing the index variable <code>i</code> from within the loop is unlikely to do what you expect. You may need to use a <code>while</code> loop instead, and control the incrementing of the loop variable yourself. Each time around the <code>for</code> loop, <code>i</code> is reassigned with the next value from <code>range()</code>. So something like:</p> <pre><code>i = 2 while i &lt; n: if(something): do something else: do something else i = 2 # restart the loop continue i += 1 </code></pre> <p>In my example, the <a href="http://python.org/doc/2.5/ref/continue.html"><code>continue</code></a> statement jumps back up to the top of the loop, skipping the <code>i += 1</code> statement for that iteration. Otherwise, <code>i</code> is incremented as you would expect (same as the <code>for</code> loop).</p>
9
2009-01-29T18:38:57Z
[ "python", "loops" ]
python: restarting a loop
492,860
<p>i have:</p> <pre><code>for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop </code></pre> <p>But that doesn't seem to work. Is there a way to restart that loop? </p> <p>Thanks</p>
9
2009-01-29T18:37:51Z
492,877
<p>You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.</p> <p>perhaps a:</p> <pre><code>i=2 while i &lt; n: if something: do something i += 1 else: do something else i = 2 #restart the loop </code></pre>
17
2009-01-29T18:42:22Z
[ "python", "loops" ]
python: restarting a loop
492,860
<p>i have:</p> <pre><code>for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop </code></pre> <p>But that doesn't seem to work. Is there a way to restart that loop? </p> <p>Thanks</p>
9
2009-01-29T18:37:51Z
21,047,506
<p>Just wanted to post an alternative which might be more genearally usable. Most of the existing solutions use a loop index to avoid this. But you don't have to use an index - the key here is that unlike a for loop, where the loop variable is hidden, the loop variable is exposed. </p> <p>You can do very similar things with iterators/generators:</p> <pre><code>x = [1,2,3,4,5,6] xi = iter(x) ival = xi.next() while not exit_condition(ival): # Do some ival stuff if ival == 4: xi = iter(x) ival = xi.next() </code></pre> <p>It's not as clean, but still retains the ability to write to the loop iterator itself. </p> <p><em>Usually</em>, when you think you want to do this, your algorithm is wrong, and you should rewrite it more cleanly. Probably what you really want to do is use a generator/coroutine instead. But it is at least possible. </p>
0
2014-01-10T15:00:48Z
[ "python", "loops" ]
python: restarting a loop
492,860
<p>i have:</p> <pre><code>for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop </code></pre> <p>But that doesn't seem to work. Is there a way to restart that loop? </p> <p>Thanks</p>
9
2009-01-29T18:37:51Z
21,047,978
<p>Here is an example using a generator's <a href="http://docs.python.org/2/reference/expressions.html#generator.send" rel="nofollow"><code>send()</code> method</a>:</p> <pre><code>def restartable(seq): while True: for item in seq: restart = yield item if restart: break else: raise StopIteration </code></pre> <p>Example Usage:</p> <pre><code>x = [1, 2, 3, 4, 5] total = 0 r = restartable(x) for item in r: if item == 5 and total &lt; 100: total += r.send(True) else: total += item </code></pre>
2
2014-01-10T15:22:05Z
[ "python", "loops" ]
python: restarting a loop
492,860
<p>i have:</p> <pre><code>for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop </code></pre> <p>But that doesn't seem to work. Is there a way to restart that loop? </p> <p>Thanks</p>
9
2009-01-29T18:37:51Z
35,438,847
<pre><code>a = ['1', '2', '3'] ls = [] count = False while ls != a : print(a[count]) if a[count] != a[-1] : count = count + 1 else : count = False </code></pre> <p>Restart while loop.</p>
0
2016-02-16T17:12:35Z
[ "python", "loops" ]
I don't understand slicing with negative bounds in Python. How is this supposed to work?
493,046
<p>I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:</p> <pre><code>&gt;&gt;&gt; s = 'spam' &gt;&gt;&gt; s[:-1] 'spa' </code></pre> <p>Why does slicing with no beginning bound and a <code>'-1'</code> return every element except the last one? Is calling <code>s[0:-1]</code> logically the same as calling <code>s[:-1]</code>? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.</p>
6
2009-01-29T19:31:48Z
493,057
<p>Yes, calling <code>s[0:-1]</code> is exactly the same as calling <code>s[:-1]</code>.</p> <p>Using a negative number as an index in python returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side).</p> <p>so if you have a list as so:</p> <pre><code>myList = ['a', 'b', 'c', 'd', 'e'] print myList[-1] # prints 'e' </code></pre> <p>the print statement will print "e".</p> <p>Once you understand that (which you may already, it's not entirely clear if that's one of the things you're confused about or not) we can start talking about slicing.</p> <p>I'm going to assume you understand the basics of a slice along the lines of <code>myList[2:4]</code> (which will return <code>['c', 'd']</code>) and jump straight into the slicing notation where one side is left blank.</p> <p>As you suspected in your post, <code>myList[:index]</code> is exactly the same as <code>myList[0:index]</code>. </p> <p>This is also works the other way around, by the way... <code>myList[index:]</code> is the same as <code>myList[index:len(myList)]</code> and will return a list of all the elements from the list starting at <code>index</code> and going till the end (e.g. <code>print myList[2:]</code> will print <code>['c', 'd', 'e']</code>).</p> <p>As a third note, you can even do <code>print myList[:]</code> where <em>no</em> index is indicated, which will basically return a copy of the entire list (equivalent to <code>myList[0:len(myList)]</code>, returns ['a', 'b', 'c', 'd', 'e']). This might be useful if you think myList is going to change at some point but you want to keep a copy of it in its current state.</p> <p>If you're not already doing it I find just messing around in a Python interpreter a whole bunch a big help towards understanding these things. I recommend <a href="http://ipython.scipy.org/moin/">IPython</a>.</p>
18
2009-01-29T19:34:38Z
[ "python", "slice" ]
I don't understand slicing with negative bounds in Python. How is this supposed to work?
493,046
<p>I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:</p> <pre><code>&gt;&gt;&gt; s = 'spam' &gt;&gt;&gt; s[:-1] 'spa' </code></pre> <p>Why does slicing with no beginning bound and a <code>'-1'</code> return every element except the last one? Is calling <code>s[0:-1]</code> logically the same as calling <code>s[:-1]</code>? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.</p>
6
2009-01-29T19:31:48Z
493,061
<p>Yes, calling <code>s[0:-1]</code> is logically the same thing as <code>s[:-1]</code> since slicing is best defined as:</p> <pre><code>[beginning_index:ending_index] </code></pre> <p>Python allows you to omit 0 as this allows your code to more terse.</p>
1
2009-01-29T19:35:38Z
[ "python", "slice" ]
I don't understand slicing with negative bounds in Python. How is this supposed to work?
493,046
<p>I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:</p> <pre><code>&gt;&gt;&gt; s = 'spam' &gt;&gt;&gt; s[:-1] 'spa' </code></pre> <p>Why does slicing with no beginning bound and a <code>'-1'</code> return every element except the last one? Is calling <code>s[0:-1]</code> logically the same as calling <code>s[:-1]</code>? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.</p>
6
2009-01-29T19:31:48Z
493,079
<p>Negative indices are counted from the end, so s[:-1] is equivalent to s[:len(s)-1] and s[-1] is the last element, for example.</p>
2
2009-01-29T19:40:49Z
[ "python", "slice" ]
I don't understand slicing with negative bounds in Python. How is this supposed to work?
493,046
<p>I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:</p> <pre><code>&gt;&gt;&gt; s = 'spam' &gt;&gt;&gt; s[:-1] 'spa' </code></pre> <p>Why does slicing with no beginning bound and a <code>'-1'</code> return every element except the last one? Is calling <code>s[0:-1]</code> logically the same as calling <code>s[:-1]</code>? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.</p>
6
2009-01-29T19:31:48Z
493,083
<p>The crucial point is that python indices should be thought of as pointers to the spaces between the entries in a list, rather than to the elements themselves. Hence, 0 points to the beginning, 1 to between the first and second, ... and n to between the nth and (n+1)st.</p> <p>Thus l[1:2] gives you a list containing just element l[1] since it gives you everything between the two pointers.</p> <p>Similarly, negative indices point in between elements, but this time counting from the back, so -1 points between the last element and the next-to-last, so [0:-1] refers to a block of items not including that last one.</p> <p>As syntactic sugar, you can leave off 0 from the beginning or, in effect, the end, so l[n:] refers to everything from l[n] to the end (if n>=len(l) then it returns the empty list).</p>
4
2009-01-29T19:42:35Z
[ "python", "slice" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
493,250
<p>Here's the trivial case approach:</p> <pre><code>&gt;&gt;&gt; number = {'one':1, ... 'two':2, ... 'three':3,} &gt;&gt;&gt; &gt;&gt;&gt; number['two'] 2 </code></pre> <p>Or are you looking for something that can handle <em>"twelve thousand, one hundred seventy-two"</em>?</p>
4
2009-01-29T20:25:24Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
493,264
<p>This could be easily be hardcoded into a dictionary if there's a limited amount of numbers you'd like to parse. </p> <p>For slightly more complex cases, you'll probably want to generate this dictionary automatically, based on the relatively simple numbers grammar. Something along the lines of this (of course, generalized...)</p> <pre><code>for i in range(10): myDict[30 + i] = "thirty-" + singleDigitsDict[i] </code></pre> <p>If you need something more extensive, then it looks like you'll need natural language processing tools. <a href="http://www.acm.org/crossroads/xrds13-4/natural_language.html" rel="nofollow">This article</a> might be a good starting point.</p>
3
2009-01-29T20:28:09Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
493,652
<p>Some earlier posts might be helpful, even though they deal more with turning text to numbers. <a href="http://stackoverflow.com/questions/468241/python-convert-alphabetically-spelled-out-numbers-to-numerics">http://stackoverflow.com/questions/468241/python-convert-alphabetically-spelled-out-numbers-to-numerics</a></p> <p>Also a great code snippet from Greg Hewgill at <a href="http://github.com/ghewgill/text2num/tree/master">http://github.com/ghewgill/text2num/tree/master</a></p> <p>My first post : )</p>
5
2009-01-29T22:02:35Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
493,788
<p>The majority of this code is to set up the numwords dict, which is only done on the first call.</p> <pre><code>def text2int(textnum, numwords={}): if not numwords: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["hundred", "thousand", "million", "billion", "trillion"] numwords["and"] = (1, 0) for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) current = result = 0 for word in textnum.split(): if word not in numwords: raise Exception("Illegal word: " + word) scale, increment = numwords[word] current = current * scale + increment if scale &gt; 100: result += current current = 0 return result + current print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven") #7100031337 </code></pre>
56
2009-01-29T22:32:54Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
598,322
<p>Thanks for the code snippet... saved me a lot of time! </p> <p>I needed to handle a couple extra parsing cases, such as ordinal words ("first", "second"), hyphenated words ("one-hundred"), and hyphenated ordinal words like ("fifty-seventh"), so I added a couple lines:</p> <pre><code>def text2int(textnum, numwords={}): if not numwords: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["hundred", "thousand", "million", "billion", "trillion"] numwords["and"] = (1, 0) for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12} ordinal_endings = [('ieth', 'y'), ('th', '')] textnum = textnum.replace('-', ' ') current = result = 0 for word in textnum.split(): if word in ordinal_words: scale, increment = (1, ordinal_words[word]) else: for ending, replacement in ordinal_endings: if word.endswith(ending): word = "%s%s" % (word[:-len(ending)], replacement) if word not in numwords: raise Exception("Illegal word: " + word) scale, increment = numwords[word] current = current * scale + increment if scale &gt; 100: result += current current = 0 return result + current` </code></pre>
6
2009-02-28T17:10:08Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
2,685,607
<p>Made change so that text2int(scale) will return correct conversion. Eg, text2int("hundred") => 100. </p> <pre><code>import re numwords = {} def text2int(textnum): if not numwords: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["hundred", "thousand", "million", "billion", "trillion", 'quadrillion', 'quintillion', 'sexillion', 'septillion', 'octillion', 'nonillion', 'decillion' ] numwords["and"] = (1, 0) for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12} ordinal_endings = [('ieth', 'y'), ('th', '')] current = result = 0 tokens = re.split(r"[\s-]+", textnum) for word in tokens: if word in ordinal_words: scale, increment = (1, ordinal_words[word]) else: for ending, replacement in ordinal_endings: if word.endswith(ending): word = "%s%s" % (word[:-len(ending)], replacement) if word not in numwords: raise Exception("Illegal word: " + word) scale, increment = numwords[word] if scale &gt; 1: current = max(1, current) current = current * scale + increment if scale &gt; 100: result += current current = 0 return result + current </code></pre>
1
2010-04-21T18:37:04Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
16,171,816
<p>This is the c# implementation of the code in 1st answer:</p> <pre><code>public static double ConvertTextToNumber(string text) { string[] units = new string[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", }; string[] tens = new string[] {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; string[] scales = new string[] { "hundred", "thousand", "million", "billion", "trillion" }; Dictionary&lt;string, ScaleIncrementPair&gt; numWord = new Dictionary&lt;string, ScaleIncrementPair&gt;(); numWord.Add("and", new ScaleIncrementPair(1, 0)); for (int i = 0; i &lt; units.Length; i++) { numWord.Add(units[i], new ScaleIncrementPair(1, i)); } for (int i = 1; i &lt; tens.Length; i++) { numWord.Add(tens[i], new ScaleIncrementPair(1, i * 10)); } for (int i = 0; i &lt; scales.Length; i++) { if(i == 0) numWord.Add(scales[i], new ScaleIncrementPair(100, 0)); else numWord.Add(scales[i], new ScaleIncrementPair(Math.Pow(10, (i*3)), 0)); } double current = 0; double result = 0; foreach (var word in text.Split(new char[] { ' ', '-', '—'})) { ScaleIncrementPair scaleIncrement = numWord[word]; current = current * scaleIncrement.scale + scaleIncrement.increment; if (scaleIncrement.scale &gt; 100) { result += current; current = 0; } } return result + current; } public struct ScaleIncrementPair { public double scale; public int increment; public ScaleIncrementPair(double s, int i) { scale = s; increment = i; } } </code></pre>
3
2013-04-23T14:21:10Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
21,669,075
<p>A quick solution is to use the <a href="https://pypi.python.org/pypi/inflect" rel="nofollow">inflect.py</a> to generate a dictionary for translation. </p> <p>inflect.py has a <code>number_to_words()</code> function, that will turn a number (e.g. <code>2</code>) to it's word form (e.g. <code>'two'</code>). Unfortunately, its reverse (which would allow you to avoid the translation dictionary route) isn't offered. All the same, you can use that function to build the translation dictionary:</p> <pre><code>&gt;&gt;&gt; import inflect &gt;&gt;&gt; p = inflect.engine() &gt;&gt;&gt; word_to_number_mapping = {} &gt;&gt;&gt; &gt;&gt;&gt; for i in range(1, 100): ... word_form = p.number_to_words(i) # 1 -&gt; 'one' ... word_to_number_mapping[word_form] = i ... &gt;&gt;&gt; print word_to_number_mapping['one'] 1 &gt;&gt;&gt; print word_to_number_mapping['eleven'] 11 &gt;&gt;&gt; print word_to_number_mapping['forty-three'] 43 </code></pre> <p>If you're willing to commit some time, it might be possible to examine inflect.py's inner-workings of the <code>number_to_words()</code> function and build your own code to do this dynamically (I haven't tried to do this).</p>
0
2014-02-10T04:27:40Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
28,887,097
<p>There's a <a href="https://github.com/dimidd/numbers_in_words" rel="nofollow">ruby gem</a> by Marc Burns that does it. I recently forked it to add support for years. You can call <a href="http://www.decalage.info/python/ruby_bridge" rel="nofollow">ruby code from python</a>.</p> <pre><code> require 'numbers_in_words' require 'numbers_in_words/duck_punch' nums = ["fifteen sixteen", "eighty five sixteen", "nineteen ninety six", "one hundred and seventy nine", "thirteen hundred", "nine thousand two hundred and ninety seven"] nums.each {|n| p n; p n.in_numbers} </code></pre> <p>results:<br> <code>"fifteen sixteen" 1615 "eighty five sixteen" 8516 "nineteen ninety six" 1996 "one hundred and seventy nine" 179 "thirteen hundred" 1300 "nine thousand two hundred and ninety seven" 9297</code></p>
1
2015-03-05T20:27:39Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
34,569,447
<p>I have just released a python module to PyPI called <a href="https://pypi.python.org/pypi/word2number" rel="nofollow">word2number</a> for the exact purpose. <a href="https://github.com/akshaynagpal/w2n" rel="nofollow">https://github.com/akshaynagpal/w2n</a></p> <p>Install it using: </p> <pre><code>pip install word2number </code></pre> <p><strong><em>make sure your pip is updated to the latest version.</em></strong></p> <p>Usage:</p> <pre><code>from word2number import w2n print w2n.word_to_num("two million three thousand nine hundred and eighty four") 2003984 </code></pre>
-1
2016-01-02T18:48:01Z
[ "python", "string", "text", "integer", "numbers" ]
Is there a way to convert number words to Integers?
493,174
<p>I need to convert <code>one</code> into <code>1</code>, <code>two</code> into <code>2</code> and so on.</p> <p>Is there a way to do this with a library or a class or anything?</p>
24
2009-01-29T20:07:43Z
38,760,564
<p>If anyone is interested, I hacked up a version that maintains the rest of the string (though it may have bugs, haven't tested it too much).</p> <pre><code>def text2int (textnum, numwords={}): if not numwords: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["hundred", "thousand", "million", "billion", "trillion"] numwords["and"] = (1, 0) for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12} ordinal_endings = [('ieth', 'y'), ('th', '')] textnum = textnum.replace('-', ' ') current = result = 0 curstring = "" onnumber = False for word in textnum.split(): if word in ordinal_words: scale, increment = (1, ordinal_words[word]) current = current * scale + increment if scale &gt; 100: result += current current = 0 onnumber = True else: for ending, replacement in ordinal_endings: if word.endswith(ending): word = "%s%s" % (word[:-len(ending)], replacement) if word not in numwords: if onnumber: curstring += repr(result + current) + " " curstring += word + " " result = current = 0 onnumber = False else: scale, increment = numwords[word] current = current * scale + increment if scale &gt; 100: result += current current = 0 onnumber = True if onnumber: curstring += repr(result + current) return curstring </code></pre> <p>Results of text2int("I want fifty five hot dogs for two hundred dollars.") I want 55 hot dogs for 200 dollars.</p> <p>There could be issues if you have, say, "$200". But, this was really rough.</p>
0
2016-08-04T07:04:13Z
[ "python", "string", "text", "integer", "numbers" ]
In Django, how do you retrieve data from extra fields on many-to-many relationships without an explicit query for it?
493,304
<p>Given a situation in Django 1.0 where you have <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany">extra data on a Many-to-Many relationship</a>:</p> <pre><code>class Player(models.Model): name = models.CharField(max_length=80) class Team(models.Model): name = models.CharField(max_length=40) players = models.ManyToManyField(Player, through='TeamPlayer', related_name='teams') class TeamPlayer(models.Model): player = models.ForeignKey(Player) team = models.ForeignKey(Team) captain = models.BooleanField() </code></pre> <p>The many-to-many relationship allows you to access the related data using attributes (the "players" attribute on the Team object or using the "teams" attribute on the Player object by way of its related name). When one of the objects is placed into a context for a template (e.g. a Team placed into a Context for rendering a template that generates the Team's roster), the related objects can be accessed (i.e. the players on the teams), but how can the extra data (e.g. 'captain') be accessed along with the related objects from the object in context (e.g.the Team) without adding additional data into the context?</p> <p>I know it is possible to query directly against the intermediary table to get the extra data. For example:</p> <pre><code>TeamPlayer.objects.get(player=790, team=168).captain </code></pre> <p>Or:</p> <pre><code>for x in TeamPlayer.objects.filter(team=168): if x.captain: print "%s (Captain)" % (x.player.name) else: print x.player.name </code></pre> <p>Doing this directly on the intermediary table, however requires me to place additional data in a template's context (the result of the query on TeamPlayer) which I am trying to avoid if such a thing is possible.</p>
15
2009-01-29T20:38:21Z
493,454
<p>So, 15 minutes after asking the question, and I found my own answer. </p> <p>Using <code>dir(Team)</code>, I can see another generated attribute named <code>teamplayer_set</code> (it also exists on Player). </p> <pre><code>t = Team.objects.get(pk=168) for x in t.teamplayer_set.all(): if x.captain: print "%s (Captain)" % (x.player.name) else: print x.player.name </code></pre> <p>Not sure how I would customize that generated related_name, but at least I know I can get to the data from the template without adding additional query results into the context.</p>
9
2009-01-29T21:13:53Z
[ "python", "django", "manytomanyfield" ]
Python: For each list element apply a function across the list
493,367
<p>Given <code>[1,2,3,4,5]</code>, how can I do something like </p> <pre><code>1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 </code></pre> <p>I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return <code>(1,5)</code>.</p> <p>So basically I would like to do something like</p> <p>for each element <code>i</code> in the list map some function across all elements in the list, taking <code>i</code> and <code>j</code> as parameters store the result in a master list, find the minimum value in the master list, and return the arguments <code>i</code>, <code>j</code>used to calculate this minimum value.</p> <p>In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.</p>
23
2009-01-29T20:53:15Z
493,423
<p>You can do this using <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehensions</a> and <a href="http://docs.python.org/library/functions.html">min()</a> (Python 3.0 code):</p> <pre><code>&gt;&gt;&gt; nums = [1,2,3,4,5] &gt;&gt;&gt; [(x,y) for x in nums for y in nums] [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)] &gt;&gt;&gt; min(_, key=lambda pair: pair[0]/pair[1]) (1, 5) </code></pre> <p>Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do <code>from __future__ import division</code> so that 1/5 correctly equals 0.2 instead of 0.</p>
40
2009-01-29T21:07:47Z
[ "python", "algorithm", "list", "list-comprehension" ]
Python: For each list element apply a function across the list
493,367
<p>Given <code>[1,2,3,4,5]</code>, how can I do something like </p> <pre><code>1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 </code></pre> <p>I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return <code>(1,5)</code>.</p> <p>So basically I would like to do something like</p> <p>for each element <code>i</code> in the list map some function across all elements in the list, taking <code>i</code> and <code>j</code> as parameters store the result in a master list, find the minimum value in the master list, and return the arguments <code>i</code>, <code>j</code>used to calculate this minimum value.</p> <p>In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.</p>
23
2009-01-29T20:53:15Z
493,429
<p>Some readable python:</p> <pre><code>def JoeCalimar(l): masterList = [] for i in l: for j in l: masterList.append(1.*i/j) pos = masterList.index(min(masterList)) a = pos/len(masterList) b = pos%len(masterList) return (l[a],l[b]) </code></pre> <p>Let me know if something is not clear.</p>
3
2009-01-29T21:08:51Z
[ "python", "algorithm", "list", "list-comprehension" ]
Python: For each list element apply a function across the list
493,367
<p>Given <code>[1,2,3,4,5]</code>, how can I do something like </p> <pre><code>1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 </code></pre> <p>I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return <code>(1,5)</code>.</p> <p>So basically I would like to do something like</p> <p>for each element <code>i</code> in the list map some function across all elements in the list, taking <code>i</code> and <code>j</code> as parameters store the result in a master list, find the minimum value in the master list, and return the arguments <code>i</code>, <code>j</code>used to calculate this minimum value.</p> <p>In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.</p>
23
2009-01-29T20:53:15Z
493,473
<p>If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list...</p> <pre><code>l = [1,2,3,4,5] def f(i,j): return i+j # Prints min value of f(i,j) along with i and j print min( (f(i,j),i,j) for i in l for j in l) </code></pre>
9
2009-01-29T21:17:20Z
[ "python", "algorithm", "list", "list-comprehension" ]
Python: For each list element apply a function across the list
493,367
<p>Given <code>[1,2,3,4,5]</code>, how can I do something like </p> <pre><code>1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 </code></pre> <p>I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return <code>(1,5)</code>.</p> <p>So basically I would like to do something like</p> <p>for each element <code>i</code> in the list map some function across all elements in the list, taking <code>i</code> and <code>j</code> as parameters store the result in a master list, find the minimum value in the master list, and return the arguments <code>i</code>, <code>j</code>used to calculate this minimum value.</p> <p>In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.</p>
23
2009-01-29T20:53:15Z
493,898
<p>Doing it the mathy way...</p> <pre><code>nums = [1, 2, 3, 4, 5] min_combo = (min(nums), max(nums)) </code></pre> <p>Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.</p>
2
2009-01-29T23:07:14Z
[ "python", "algorithm", "list", "list-comprehension" ]
Python: For each list element apply a function across the list
493,367
<p>Given <code>[1,2,3,4,5]</code>, how can I do something like </p> <pre><code>1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 </code></pre> <p>I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return <code>(1,5)</code>.</p> <p>So basically I would like to do something like</p> <p>for each element <code>i</code> in the list map some function across all elements in the list, taking <code>i</code> and <code>j</code> as parameters store the result in a master list, find the minimum value in the master list, and return the arguments <code>i</code>, <code>j</code>used to calculate this minimum value.</p> <p>In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.</p>
23
2009-01-29T20:53:15Z
494,247
<p>If you don't mind importing the numpy package, it has a lot of convenient functionality built in. It's likely to be much more efficient to use their data structures than lists of lists, etc.</p> <pre><code>from __future__ import division import numpy data = numpy.asarray([1,2,3,4,5]) dists = data.reshape((1,5)) / data.reshape((5,1)) print dists which = dists.argmin() (r,c) = (which // 5, which % 5) # assumes C ordering # pick whichever is most appropriate for you... minval = dists[r,c] minval = dists.min() minval = dists.ravel()[which] </code></pre>
3
2009-01-30T01:59:58Z
[ "python", "algorithm", "list", "list-comprehension" ]
Python: For each list element apply a function across the list
493,367
<p>Given <code>[1,2,3,4,5]</code>, how can I do something like </p> <pre><code>1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 </code></pre> <p>I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return <code>(1,5)</code>.</p> <p>So basically I would like to do something like</p> <p>for each element <code>i</code> in the list map some function across all elements in the list, taking <code>i</code> and <code>j</code> as parameters store the result in a master list, find the minimum value in the master list, and return the arguments <code>i</code>, <code>j</code>used to calculate this minimum value.</p> <p>In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.</p>
23
2009-01-29T20:53:15Z
496,563
<p>If working with Python ≥2.6 (including 3.x), you can:</p> <pre><code>from __future__ import division import operator, itertools def getmin(alist): return min( (operator.div(*pair), pair) for pair in itertools.product(alist, repeat=2) )[1] getmin([1, 2, 3, 4, 5]) </code></pre> <p>EDIT: Now that I think of it and if I remember my mathematics correctly, this should also give the answer assuming that all numbers are non-negative:</p> <pre><code>def getmin(alist): return min(alist), max(alist) </code></pre>
1
2009-01-30T18:14:40Z
[ "python", "algorithm", "list", "list-comprehension" ]
Python: For each list element apply a function across the list
493,367
<p>Given <code>[1,2,3,4,5]</code>, how can I do something like </p> <pre><code>1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 </code></pre> <p>I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return <code>(1,5)</code>.</p> <p>So basically I would like to do something like</p> <p>for each element <code>i</code> in the list map some function across all elements in the list, taking <code>i</code> and <code>j</code> as parameters store the result in a master list, find the minimum value in the master list, and return the arguments <code>i</code>, <code>j</code>used to calculate this minimum value.</p> <p>In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.</p>
23
2009-01-29T20:53:15Z
1,784,441
<pre><code>&gt;&gt;&gt; nums = [1, 2, 3, 4, 5] &gt;&gt;&gt; min(map((lambda t: ((float(t[0])/t[1]), t)), ((x, y) for x in nums for y in nums)))[1] (1, 5) </code></pre>
0
2009-11-23T16:50:45Z
[ "python", "algorithm", "list", "list-comprehension" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
493,399
<h2>General way</h2> <pre><code>import sys sys.stdout.write('.') </code></pre> <p>You may also need to call</p> <pre><code>sys.stdout.flush() </code></pre> <p>to ensure <code>stdout</code> is flushed immediately.</p> <h2>Python 2.6+</h2> <p>From Python 2.6 you can import the <code>print</code> function from Python 3:</p> <pre><code>from __future__ import print_function </code></pre> <p>This allows you to use the Python 3 solution below.</p> <h2>Python 3</h2> <p>In Python 3, the <code>print</code> statement has been changed into a function. In Python 3, you can instead do:</p> <pre><code>print('.', end="") </code></pre> <p>This also works in Python 2, provided that you've used <code>from __future__ import print_function</code>.</p> <p>If you are having trouble with buffering, you can flush the output by adding <code>flush=True</code> keyword argument:</p> <pre><code>print('.', end="", flush=True) </code></pre>
1,118
2009-01-29T21:01:43Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
493,422
<p>The new (as of Python 3.0) print function has an optional end parameter that let's you modify the ending character. There's also sep for separator.</p>
14
2009-01-29T21:07:36Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
493,500
<p><em>Note: The title of this question used to be something like "How to printf in python?"</em></p> <p>Since people may come here looking for it based on the title, Python also supports printf-style substitution:</p> <pre><code>&gt;&gt;&gt; strings = [ "one", "two", "three" ] &gt;&gt;&gt; &gt;&gt;&gt; for i in xrange(3): ... print "Item %d: %s" % (i, strings[i]) ... Item 0: one Item 1: two Item 2: three </code></pre> <p>And, you can handily multiply string values:</p> <pre><code>&gt;&gt;&gt; print "." * 10 .......... </code></pre>
148
2009-01-29T21:24:58Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
4,348,063
<p>This is not the answer to the question in the title, but it's the answer on how to print on the same line:</p> <pre><code>import sys for i in xrange(0,10): sys.stdout.write(".") sys.stdout.flush() </code></pre>
31
2010-12-03T17:16:00Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
4,907,563
<p>You can do it with <code>end</code> argument of print. In python3 range() returns iterator and xrange() doesn't exist.</p> <pre><code>for i in range(10): print('.', end='') </code></pre>
4
2011-02-05T15:05:41Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
5,071,123
<p>Use the python3-style print function for python2.6+ <em>(will also break any existing keyworded print statements in the same file.)</em></p> <pre><code># for python2 to use the print() function, removing the print keyword from __future__ import print_function for x in xrange(10): print('.', end='') </code></pre> <p>To not ruin all your python2 print keywords, create a separate <code>printf.py</code> file</p> <pre><code># printf.py from __future__ import print_function def printf(str, *args): print(str % args, end='') </code></pre> <p>Then, use it in your file</p> <pre><code>from printf import printf for x in xrange(10): printf('.') print 'done' #..........done </code></pre> <p>More examples showing printf style</p> <pre><code>printf('hello %s', 'world') printf('%i %f', 10, 3.14) #hello world10 3.140000 </code></pre>
67
2011-02-21T20:50:30Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
11,076,668
<p>i recently had the same problem..</p> <p>i solved it by doing:</p> <pre><code>import sys, os # reopen stdout with "newline=None". # in this mode, # input: accepts any newline character, outputs as '\n' # output: '\n' converts to os.linesep sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None) for i in range(1,10): print(i) </code></pre> <p>this works on both unix and windows ... have not tested it on macosx ...</p> <p>hth</p>
2
2012-06-18T03:39:20Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
11,685,717
<p>It should be as simple as described at this link by Guido Van Rossum:</p> <p>Re: How does one print without a c/r ?</p> <p><a href="http://www.python.org/search/hypermail/python-1992/0115.html">http://www.python.org/search/hypermail/python-1992/0115.html</a></p> <blockquote> <p>Is it possible to print something but not automatically have a carriage return appended to it ?</p> </blockquote> <p>Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless "print" that adds the final newline:</p> <pre><code>&gt;&gt;&gt; for i in range(10): ... print i, ... else: ... print ... 0 1 2 3 4 5 6 7 8 9 &gt;&gt;&gt; </code></pre>
166
2012-07-27T10:09:57Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
17,494,240
<p>You can do the same in python3 as follows :</p> <pre><code>#!usr/bin/python i = 0 while i&lt;10 : print('.',end='') i = i+1 </code></pre> <p>and execute it with <code>python filename.py</code> or <code>python3 filename.py</code></p>
1
2013-07-05T17:37:06Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
24,685,004
<p>You can just add <code>,</code> in the end of <code>print</code> function so it won't print on new line.</p>
13
2014-07-10T19:45:40Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
26,444,106
<pre><code>for i in xrange(0,10): print '\b.' </code></pre> <p>This worked in both 2.7.8 &amp; 2.5.2 (Canopy and OSX terminal, respectively) -- no module imports or time travel required.</p>
0
2014-10-18T20:13:54Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
28,778,131
<p>@lenooh satisfied my query. I discovered this article while searching for 'python suppress newline'. I'm using IDLE3 on Raspberry Pi to develop Python 3.2 for PuTTY. I wanted to create a progress bar on the PuTTY command line. I didn't want the page scrolling away. I wanted a horizontal line to re-assure the user from freaking out that the program hasn't cruncxed to a halt nor been sent to lunch on a merry infinite loop - as a plea to 'leave me be, I'm doing fine, but this may take some time.' interactive message - like a progress bar in text.</p> <p>The <code>print('Skimming for', search_string, '\b! .001', end='')</code> initializes the message by preparing for the next screen-write, which will print three backspaces as ⌫⌫⌫ rubout and then a period, wiping off '001' and extending the line of periods. After <code>search_string</code> parrots user input, the <code>\b!</code> trims the exclamation point of my <code>search_string</code> text to back over the space which <code>print()</code> otherwise forces, properly placing the punctuation. That's followed by a space and the first 'dot' of the 'progress bar' which I'm simulating. Unnecessarily, the message is also then primed with the page number (formatted to a length of three with leading zeros) to take notice from the user that progress is being processed and which will also reflect the count of periods we will later build out to the right.</p> <pre><code>import sys page=1 search_string=input('Search for?',) print('Skimming for', search_string, '\b! .001', end='') sys.stdout.flush() # the print function with an end='' won't print unless forced while page: # some stuff… # search, scrub, and build bulk output list[], count items, # set done flag True page=page+1 #done flag set in 'some_stuff' sys.stdout.write('\b\b\b.'+format(page, '03')) #&lt;-- here's the progress bar meat sys.stdout.flush() if done: #( flag alternative to break, exit or quit) print('\nSorting', item_count, 'items') page=0 # exits the 'while page' loop list.sort() for item_count in range(0, items) print(list[item_count]) #print footers here if not (len(list)==items): print('#error_handler') </code></pre> <p>The progress bar meat is in the <code>sys.stdout.write('\b\b\b.'+format(page, '03'))</code> line. First, to erase to the left, it backs up the cursor over the three numeric characters with the '\b\b\b' as ⌫⌫⌫ rubout and drops a new period to add to the progress bar length. Then it writes three digits of the page it has progressed to so far. Because <code>sys.stdout.write()</code> waits for a full buffer or the output channel to close, the <code>sys.stdout.flush()</code> forces the immediate write. <code>sys.stdout.flush()</code> is built into the end of <code>print()</code> which is bypassed with <code>print(txt, end='' )</code>. Then the code loops through its mundane time intensive operations while it prints nothing more until it returns here to wipe three digits back, add a period and write three digits again, incremented.</p> <p>The three digits wiped and rewritten is by no means necessary - it's just a flourish which exemplifies <code>sys.stdout.write()</code> versus <code>print()</code>. You could just as easily prime with a period and forget the three fancy backslash-b ⌫ backspaces (of course not writing formatted page counts as well) by just printing the period bar longer by one each time through - without spaces or newlines using just the <code>sys.stdout.write('.'); sys.stdout.flush()</code> pair.</p> <p>Please note that the Raspberry Pi IDLE3 Python shell does not honor the backspace as ⌫ rubout but instead prints a space, creating an apparent list of fractions instead.</p> <p>—(o=8> wiz</p>
0
2015-02-28T04:35:09Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
29,696,909
<p>My understanding is that the comma suppressed the space The 3 dots are relics of the interpreter</p> <blockquote> <blockquote> <blockquote> <p>for i in range(0,10): print".\n", ... . . . . . . . . . .</p> </blockquote> </blockquote> </blockquote>
-5
2015-04-17T10:37:33Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
30,881,087
<p>Using functools.partial to create a new function called printf</p> <pre><code>&gt;&gt;&gt; import functools &gt;&gt;&gt; printf = functools.partial(print, end="") &gt;&gt;&gt; printf("Hello world\n") Hello world </code></pre> <p>Easy way to wrap a function with default parameters.</p>
7
2015-06-17T01:55:02Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
31,569,705
<p>python <strong>2.6+</strong>:</p> <pre><code>from __future__ import print_function # needs to be first statement in file print('.', end='') </code></pre> <p>python <strong>3</strong>:</p> <pre><code>print('.', end='') </code></pre> <p>python &lt;= <strong>2.5</strong>:</p> <pre><code>import sys sys.stdout.write('.') </code></pre> <p>if extra space is OK after each print, in python 2</p> <pre><code>print '.', </code></pre> <p><strong>misleading</strong> in python 2 - <strong>avoid</strong>:</p> <pre><code>print('.'), # avoid this if you want to remain sane # this makes it look like print is a function but it is not # this is the `,` creating a tuple and the parentheses enclose an expression # to see the problem, try: print('.', 'x'), # this will print `('.', 'x') ` </code></pre>
2
2015-07-22T17:09:59Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
31,590,081
<p>you want to print something in for loop right;but you don't want it print in new line every time.. for example:</p> <pre><code> for i in range (0,5): print "hi" OUTPUT: hi hi hi hi hi </code></pre> <hr> <p>but you want it to print like this: hi hi hi hi hi hi right???? just add a comma after print "hi"</p> <p>Example:</p> <p><code>for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi </code></p>
4
2015-07-23T14:18:14Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
33,870,664
<p>You can try:</p> <pre><code>import sys import time # Keeps the initial message in buffer. sys.stdout.write("\rfoobar bar black sheep") sys.stdout.flush() # Wait 2 seconds time.sleep(2) # Replace the message with a new one. sys.stdout.write("\r"+'hahahahaaa ') sys.stdout.flush() # Finalize the new message by printing a return carriage. sys.stdout.write('\n') </code></pre>
4
2015-11-23T12:03:31Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
33,901,457
<p>Many of these answers seem a little complicated. In Python 3.X you simply do this,</p> <pre><code>print(&lt;expr&gt;, &lt;expr&gt;, ..., &lt;expr&gt;, end=" ") </code></pre> <p>The default value of end is "\n". We are simply changing it to a space or you can also use end="".</p>
1
2015-11-24T18:46:28Z
[ "python", "newline" ]
How to print in Python without newline or space?
493,386
<p>The question is in the title.</p> <p>I'd like to do in <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> what I do in this example in <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main() { int i; for (i=0; i&lt;10; i++) printf("."); return 0; } </code></pre> <p>Output:</p> <pre><code>.......... </code></pre> <p>In Python:</p> <pre><code>&gt;&gt;&gt; for i in xrange(0,10): print '.' . . . . . . . . . . &gt;&gt;&gt; for i in xrange(0,10): print '.', . . . . . . . . . . </code></pre> <p>In Python <code>print</code> will add a <code>\n</code> or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the <code>stdout</code> (I don't know if it's worded correctly).</p>
781
2009-01-29T20:58:25Z
38,286,476
<p>In Python 3, printing is a function. When you call</p> <pre><code>print ('hello world') </code></pre> <p>Python translates it to</p> <pre><code>print ('hello world', end = '\n') </code></pre> <p>You can change end to whatever you want.</p> <pre><code>print ('hello world', end = '') print ('hello world', end = ' ') </code></pre>
2
2016-07-09T21:22:30Z
[ "python", "newline" ]
What's the best way(error proof / foolproof) to parse a file using python with following format?
493,484
<pre><code>######################################## # some comment # other comment ######################################## block1 { value=data some_value=some other kind of data othervalue=032423432 } block2 { value=data some_value=some other kind of data othervalue=032423432 } </code></pre>
3
2009-01-29T21:19:31Z
493,546
<p>Well, the data looks pretty regular. So you could do something like this (untested):</p> <pre><code>class Block(object): def __init__(self, name): self.name = name infile = open(...) # insert filename here current = None blocks = [] for line in infile: if line.lstrip().startswith('#'): continue elif line.rstrip().endswith('{'): current = Block(line.split()[0]) elif '=' in line: attr, value = line.strip().split('=') try: value = int(value) except ValueError: pass setattr(current, attr, value) elif line.rstrip().endswith('}'): blocks.append(current) </code></pre> <p>The result will be a list of Block instances, where <code>block.name</code> will be the name (<code>'block1'</code>, <code>'block2'</code>, etc.) and other attributes correspond to the keys in your data. So, <code>blocks[0].value</code> will be 'data', etc. Note that this only handles strings and integers as values.</p> <p>(there is an obvious bug here if your keys can ever include 'name'. You might like to change <code>self.name</code> to <code>self._name</code> or something if this can happen)</p> <p>HTH!</p>
4
2009-01-29T21:34:23Z
[ "python", "text-parsing" ]
What's the best way(error proof / foolproof) to parse a file using python with following format?
493,484
<pre><code>######################################## # some comment # other comment ######################################## block1 { value=data some_value=some other kind of data othervalue=032423432 } block2 { value=data some_value=some other kind of data othervalue=032423432 } </code></pre>
3
2009-01-29T21:19:31Z
493,709
<p>You might look into something like <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing.</a></p>
2
2009-01-29T22:15:12Z
[ "python", "text-parsing" ]
What's the best way(error proof / foolproof) to parse a file using python with following format?
493,484
<pre><code>######################################## # some comment # other comment ######################################## block1 { value=data some_value=some other kind of data othervalue=032423432 } block2 { value=data some_value=some other kind of data othervalue=032423432 } </code></pre>
3
2009-01-29T21:19:31Z
493,744
<p>If you do not really mean parsing, but rather text processing and the input data is really that regular, then go with John's solution. If you really need some parsing (like there are some a little more complex rules to the data that you are getting), then depending on the amount of data that you need to parse, I'd go either with pyparsing or <a href="http://simpleparse.sourceforge.net/" rel="nofollow">simpleparse</a>. I've tried both of them, but actually pyparsing was too slow for me. </p>
3
2009-01-29T22:24:17Z
[ "python", "text-parsing" ]
What's the best way(error proof / foolproof) to parse a file using python with following format?
493,484
<pre><code>######################################## # some comment # other comment ######################################## block1 { value=data some_value=some other kind of data othervalue=032423432 } block2 { value=data some_value=some other kind of data othervalue=032423432 } </code></pre>
3
2009-01-29T21:19:31Z
1,654,802
<p>The best way would be to use an existing format such as JSON.</p> <p>Here's an example parser for your format:</p> <pre><code>from lepl import (AnyBut, Digit, Drop, Eos, Integer, Letter, NON_GREEDY, Regexp, Space, Separator, Word) # EBNF # name = ( letter | "_" ) , { letter | "_" | digit } ; name = Word(Letter() | '_', Letter() | '_' | Digit()) # words = word , space+ , word , { space+ , word } ; # two or more space-separated words (non-greedy to allow comment at the end) words = Word()[2::NON_GREEDY, ~Space()[1:]] &gt; list # value = integer | word | words ; value = (Integer() &gt;&gt; int) | Word() | words # comment = "#" , { all characters - "\n" } , ( "\n" | EOF ) ; comment = '#' &amp; AnyBut('\n')[:] &amp; ('\n' | Eos()) with Separator(~Regexp(r'\s*')): # statement = name , "=" , value ; statement = name &amp; Drop('=') &amp; value &gt; tuple # suite = "{" , { comment | statement } , "}" ; suite = Drop('{') &amp; (~comment | statement)[:] &amp; Drop('}') &gt; dict # block = name , suite ; block = name &amp; suite &gt; tuple # config = { comment | block } ; config = (~comment | block)[:] &amp; Eos() &gt; dict from pprint import pprint pprint(config.parse(open('input.cfg').read())) </code></pre> <p>Output:</p> <pre><code>[{'block1': {'othervalue': 32423432, 'some_value': ['some', 'other', 'kind', 'of', 'data'], 'value': 'data'}, 'block2': {'othervalue': 32423432, 'some_value': ['some', 'other', 'kind', 'of', 'data'], 'value': 'data'}}] </code></pre>
6
2009-10-31T16:05:47Z
[ "python", "text-parsing" ]
What's the best way(error proof / foolproof) to parse a file using python with following format?
493,484
<pre><code>######################################## # some comment # other comment ######################################## block1 { value=data some_value=some other kind of data othervalue=032423432 } block2 { value=data some_value=some other kind of data othervalue=032423432 } </code></pre>
3
2009-01-29T21:19:31Z
26,204,082
<p><a href="http://pythonhosted.org/grako/" rel="nofollow">Grako (for grammar compiler)</a> allows to separate the input format specification (grammar) from its interpretation (semantics). Here's grammar for your input format in Grako's variety of <a href="http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form" rel="nofollow">EBNF</a>:</p> <pre><code>(* a file contains zero or more blocks *) file = {block} $; (* a named block has at least one assignment statement *) block = name '{' {assignment}+ '}'; assignment = name '=' value NEWLINE; name = /[a-z][a-z0-9_]*/; value = integer | string; NEWLINE = /\n/; integer = /[0-9]+/; (* string value is everything until the next newline *) string = /[^\n]+/; </code></pre> <p>To install <code>grako</code>, run <code>pip install grako</code>. To generate the <a href="http://en.wikipedia.org/wiki/Parsing_expression_grammar" rel="nofollow">PEG</a> parser from the grammar:</p> <pre><code>$ grako -o config_parser.py Config.ebnf </code></pre> <p>To convert stdin into json using the generated <code>config_parser</code> module:</p> <pre><code>#!/usr/bin/env python import json import string import sys from config_parser import ConfigParser class Semantics(object): def file(self, ast): # file = {block} $ # all blocks should have unique names within the file return dict(ast) def block(self, ast): # block = name '{' {assignment}+ '}' # all assignment statements should use unique names return ast[0], dict(ast[2]) def assignment(self, ast): # assignment = name '=' value NEWLINE # value = integer | string return ast[0], ast[2] # name, value def integer(self, ast): return int(ast) def string(self, ast): return ast.strip() # remove leading/trailing whitespace parser = ConfigParser(whitespace='\t\n\v\f\r ', eol_comments_re="#.*?$") ast = parser.parse(sys.stdin.read(), rule_name='file', semantics=Semantics()) json.dump(ast, sys.stdout, indent=2, sort_keys=True) </code></pre> <h3>Output</h3> <pre><code>{ "block1": { "othervalue": 32423432, "some_value": "some other kind of data", "value": "data" }, "block2": { "othervalue": 32423432, "some_value": "some other kind of data", "value": "data" } } </code></pre>
1
2014-10-05T15:23:40Z
[ "python", "text-parsing" ]
Outputting to a text file
493,816
<p>How to print the following code to a .txt file</p> <pre><code>y = '10.1.1.' # /24 network, for x in range(255): x += 1 print y + str(x) # not happy that it's in string, but how to print it into a.txt </code></pre> <p>There's copy paste, but would rather try something more interesting. </p>
2
2009-01-29T22:44:05Z
493,822
<pre><code>f = open('myfile.txt', 'w') for x in range(255): ip = "10.1.1.%s\n" % str(x) f.write(ip) f.close() </code></pre>
6
2009-01-29T22:46:38Z
[ "python", "text" ]
Outputting to a text file
493,816
<p>How to print the following code to a .txt file</p> <pre><code>y = '10.1.1.' # /24 network, for x in range(255): x += 1 print y + str(x) # not happy that it's in string, but how to print it into a.txt </code></pre> <p>There's copy paste, but would rather try something more interesting. </p>
2
2009-01-29T22:44:05Z
493,823
<p>scriptname.py >> output.txt</p>
3
2009-01-29T22:46:56Z
[ "python", "text" ]
Outputting to a text file
493,816
<p>How to print the following code to a .txt file</p> <pre><code>y = '10.1.1.' # /24 network, for x in range(255): x += 1 print y + str(x) # not happy that it's in string, but how to print it into a.txt </code></pre> <p>There's copy paste, but would rather try something more interesting. </p>
2
2009-01-29T22:44:05Z
493,943
<p>What is the <code>x += 1</code> for? It seems to be a workaround for <code>range(255)</code> being 0 based - which gives the sequence 0,1,2...254.</p> <p><code>range(1,256)</code> will better give you what you want.</p> <p>An alternative to other answers:</p> <pre><code>NETWORK = '10.1.1' f = open('outfile.txt', 'w') try: for machine in range(1,256): print &gt;&gt; f, "%s.%s" % (NETWORK, machine) finally: f.close() </code></pre>
1
2009-01-29T23:26:55Z
[ "python", "text" ]
Outputting to a text file
493,816
<p>How to print the following code to a .txt file</p> <pre><code>y = '10.1.1.' # /24 network, for x in range(255): x += 1 print y + str(x) # not happy that it's in string, but how to print it into a.txt </code></pre> <p>There's copy paste, but would rather try something more interesting. </p>
2
2009-01-29T22:44:05Z
497,857
<p>In Python 3, you can use the print function's keyword argument called file. "a" means "append."</p> <pre><code>f = open("network.txt", "a") for i in range(1, 256): print("10.1.1." + str(i), file=f) f.close() </code></pre>
0
2009-01-31T00:38:51Z
[ "python", "text" ]
Python join, why is it string.join(list) instead of list.join(string)?
493,819
<p>This has always confused me. It seems like this would be nicer:</p> <pre><code>my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" </code></pre> <p>Than this:</p> <pre><code>my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" </code></pre> <p>Is there a specific reason it does it like this?</p>
919
2009-01-29T22:45:13Z
493,831
<p>Because the <code>join()</code> method is in the string class, instead of the list class?</p> <p>I agree it looks funny.</p> <p>See <a href="http://www.faqs.org/docs/diveintopython/odbchelper_join.html">http://www.faqs.org/docs/diveintopython/odbchelper_join.html</a>:</p> <blockquote> <p><strong>Historical note.</strong> When I first learned Python, I expected join to be a method of a list, which would take the delimiter as an argument. Lots of people feel the same way, and there’s a story behind the join method. Prior to Python 1.6, strings didn’t have all these useful methods. There was a separate string module which contained all the string functions; each function took a string as its first argument. The functions were deemed important enough to put onto the strings themselves, which made sense for functions like lower, upper, and split. But many hard-core Python programmers objected to the new join method, arguing that it should be a method of the list instead, or that it shouldn’t move at all but simply stay a part of the old string module (which still has lots of useful stuff in it). I use the new join method exclusively, but you will see code written either way, and if it really bothers you, you can use the old string.join function instead.</p> </blockquote>
170
2009-01-29T22:48:38Z
[ "python", "string", "list", "join" ]
Python join, why is it string.join(list) instead of list.join(string)?
493,819
<p>This has always confused me. It seems like this would be nicer:</p> <pre><code>my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" </code></pre> <p>Than this:</p> <pre><code>my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" </code></pre> <p>Is there a specific reason it does it like this?</p>
919
2009-01-29T22:45:13Z
493,842
<p>It's because any iterable can be joined, not just lists, but the result and the "joiner" are always strings.</p> <p>E.G:</p> <pre><code>import urllib2 print '\n############\n'.join( urllib2.urlopen('http://data.stackexchange.com/users/7095')) </code></pre>
672
2009-01-29T22:51:18Z
[ "python", "string", "list", "join" ]
Python join, why is it string.join(list) instead of list.join(string)?
493,819
<p>This has always confused me. It seems like this would be nicer:</p> <pre><code>my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" </code></pre> <p>Than this:</p> <pre><code>my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" </code></pre> <p>Is there a specific reason it does it like this?</p>
919
2009-01-29T22:45:13Z
493,843
<p>Primarily because the result of a <code>someString.join()</code> is a string.</p> <p>The sequence (list or tuple or whatever) doesn't appear in the result, just a string. Because the result is a string, it makes sense as a method of a string.</p>
10
2009-01-29T22:51:45Z
[ "python", "string", "list", "join" ]
Python join, why is it string.join(list) instead of list.join(string)?
493,819
<p>This has always confused me. It seems like this would be nicer:</p> <pre><code>my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" </code></pre> <p>Than this:</p> <pre><code>my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" </code></pre> <p>Is there a specific reason it does it like this?</p>
919
2009-01-29T22:45:13Z
493,884
<p>I agree that it's counterintuitive at first, but there's a good reason. Join can't be a method of a list because:</p> <ul> <li>it must work for different iterables too (tuples, generators, etc.) </li> <li>it must have different behavior between different types of strings.</li> </ul> <p>There are actually two join methods (Python 3.0):</p> <pre><code>&gt;&gt;&gt; b"".join &lt;built-in method join of bytes object at 0x00A46800&gt; &gt;&gt;&gt; "".join &lt;built-in method join of str object at 0x00A28D40&gt; </code></pre> <p>If join was a method of a list, then it would have to inspect its arguments to decide which one of them to call. And you can't join byte and str together, so the way they have it now makes sense. </p>
40
2009-01-29T23:03:45Z
[ "python", "string", "list", "join" ]
Python join, why is it string.join(list) instead of list.join(string)?
493,819
<p>This has always confused me. It seems like this would be nicer:</p> <pre><code>my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" </code></pre> <p>Than this:</p> <pre><code>my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" </code></pre> <p>Is there a specific reason it does it like this?</p>
919
2009-01-29T22:45:13Z
494,320
<p>Think of it as the natural orthogonal operation to split.</p> <p>I understand why it is applicable to anything iterable and so can't easily be implemented <em>just</em> on list.</p> <p>For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added to the interface but it is just a convention and so there's no central way to add it to the set of things which are iterable.</p>
15
2009-01-30T02:43:51Z
[ "python", "string", "list", "join" ]
Python join, why is it string.join(list) instead of list.join(string)?
493,819
<p>This has always confused me. It seems like this would be nicer:</p> <pre><code>my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" </code></pre> <p>Than this:</p> <pre><code>my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" </code></pre> <p>Is there a specific reason it does it like this?</p>
919
2009-01-29T22:45:13Z
12,662,361
<p>This was discussed in the <a href="http://mail.python.org/pipermail/python-dev/1999-June/095366.html">String methods... finally</a> thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and <code>str.join</code> was included in Python 1.6 (which supported Unicode) was released in Sep 2000. Python 2.0 (supported <code>str</code> methods including <code>join</code>) was released in Oct 2000.</p> <ul> <li>There were four options proposed in this thread: <ul> <li><code>str.join(seq)</code></li> <li><code>seq.join(str)</code></li> <li><code>seq.reduce(str)</code></li> <li><code>join</code> as a built-in function</li> </ul></li> <li>Guido wanted to support not only <code>list</code>s, <code>tuple</code>s, but all sequences/iterables.</li> <li><code>seq.reduce(str)</code> is difficult for new-comers.</li> <li><code>seq.join(str)</code> introduces unexpected dependency from sequences to str/unicode.</li> <li><code>join()</code> as a built-in function would support only specific data types. So using a built in namespace is not good. If <code>join()</code> supports many datatypes, creating optimized implementation would be difficult, if implemented using the <code>__add__</code> method then it's O(n<sup>2</sup>).</li> <li>The separater string (<code>sep</code>) should not be omitted. Explicit is better than implicit.</li> </ul> <p><em>There are no other reasons offered in this thread.</em></p> <p>Here are some additional thoughts (my own, and my friend's):</p> <ul> <li>Unicode support was coming, but it was not final. At that time <code>UTF-8</code> was the most likely about to replace <code>UCS2/4</code>. To calculate total buffer length of <code>UTF-8</code> strings it needs to know character coding rule.</li> <li>At that time, Python had already decided on a common sequence interface rule where a user could create a sequence-like (iterable) class. But Python didn't support extending built-in types until 2.2. At that time it was difficult to provide basic iterable class (which is mentioned in another comment). </li> </ul> <p>Guido's decision is recorded in a <a href="http://mail.python.org/pipermail/python-dev/1999-June/095436.html">historical mail</a>, deciding on <code>str.join(seq)</code>:</p> <blockquote> <p>Funny, but it does seem right! Barry, go for it...<br> --Guido van Rossum</p> </blockquote>
117
2012-09-30T15:21:16Z
[ "python", "string", "list", "join" ]
Python join, why is it string.join(list) instead of list.join(string)?
493,819
<p>This has always confused me. It seems like this would be nicer:</p> <pre><code>my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" </code></pre> <p>Than this:</p> <pre><code>my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" </code></pre> <p>Is there a specific reason it does it like this?</p>
919
2009-01-29T22:45:13Z
29,617,379
<blockquote> <h1>Why is it <code>string.join(list)</code> instead of <code>list.join(string)</code>?</h1> </blockquote> <p>This is because <code>join</code> is a "string" method! It creates a string from any iterable. If we stuck the method on lists, what about when we have iterables that aren't lists? </p> <p>What if you have a tuple of strings? If this were a <code>list</code> method, you would have to cast every such iterator of strings as a <code>list</code> before you could join the elements into a single string! For example:</p> <pre><code>some_strings = ('foo', 'bar', 'baz') </code></pre> <p>Let's roll our own list join method:</p> <pre><code>class OurList(list): def join(self, s): return s.join(self) </code></pre> <p>And to use it, note that we have to first create a list from each iterable to join the strings in that iterable, wasting both memory and processing power:</p> <pre><code>&gt;&gt;&gt; l = OurList(some_strings) # step 1, create our list &gt;&gt;&gt; l.join(', ') # step 2, use our list join method! 'foo, bar, baz' </code></pre> <p>So we see we have to add an extra step to use our list method, instead of just using the builtin string method:</p> <pre><code>&gt;&gt;&gt; ' | '.join(some_strings) # a single step! 'foo | bar | baz' </code></pre> <h2>Performance Caveat for Generators</h2> <p>The algorithm Python uses to create the final string with <code>str.join</code> actually has to pass over the iterable twice, so if you provide it a generator expression, it has to materialize it into a list first before it can create the final string. </p> <p>Thus, while passing around generators is usually better than list comprehensions, <code>str.join</code> is an exception:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; min(timeit.repeat(lambda: ''.join(str(i) for i in range(10) if i))) 3.839168446022086 &gt;&gt;&gt; min(timeit.repeat(lambda: ''.join([str(i) for i in range(10) if i]))) 3.339879313018173 </code></pre> <p>Nevertheless, the <code>str.join</code> operation is still semantically a "string" operation, so it still makes sense to have it on the <code>str</code> object than on miscellaneous iterables.</p>
14
2015-04-14T00:45:18Z
[ "python", "string", "list", "join" ]
Which Python module is suitable for data manipulation in a list?
493,853
<p>I have a sequence of x, y and z -coordinates, which I need to manipulate. They are in one list of three tuples, like {(x1, y1, z1), (x2, y2, z2), ...}.</p> <p>I need addition, multiplication and logarithm to manipulate my data.</p> <p>I would like to study a module, which is as powerful as Awk -language.</p>
3
2009-01-29T22:54:02Z
494,034
<p>I'm not sure exactly what you're after. You can do a lot with list comprehensions. For example, if you want to turn a list:</p> <pre><code>coords = [(x1, y1, z1), (x2, y2, z2), (x3, y3, z3)] # etc </code></pre> <p>into a tuple <code>(x1+x2+x3, y1+y2+y3, z1+z2+z3)</code>, then you can do:</p> <pre><code>sums = (sum(a[0] for a in coords), sum(a[1] for a in coords), sum(a[2] for a in coords)) </code></pre> <p>In fact, an experienced python programmer might write that as:</p> <pre><code>sums = map(sum, zip(*coords)) </code></pre> <p>though that can look a bit like magic to a beginner.</p> <p>If you want to multiply across coordinates, then the idea is similar. The only problem is python has no builtin multiplication equivalent to <code>sum</code>. We can build our own:</p> <pre><code>import operator def prod(lst): return reduce(operator.mul, lst) </code></pre> <p>Then you can multiply your tuples coordinate-wise as:</p> <pre><code>prods = map(prod, zip(*coords)) </code></pre> <p>If you want to do something more complex with multiplication (inner product?) that will require a little more work (though it won't be very difficult).</p> <p>I'm not sure what you want to take the logarithm of. But you can find the log function in the math module:</p> <pre><code>from math import log </code></pre> <p>Hope this helps.</p>
6
2009-01-30T00:10:42Z
[ "python", "module" ]
Which Python module is suitable for data manipulation in a list?
493,853
<p>I have a sequence of x, y and z -coordinates, which I need to manipulate. They are in one list of three tuples, like {(x1, y1, z1), (x2, y2, z2), ...}.</p> <p>I need addition, multiplication and logarithm to manipulate my data.</p> <p>I would like to study a module, which is as powerful as Awk -language.</p>
3
2009-01-29T22:54:02Z
494,078
<p>In Python 3 the <code>reduce</code> function is gone. You can do:</p> <pre><code>def prod(lst): return [x*y*z for x, y, z in list(zip(*lst))] coords = [(2, 4, 8), (3, 6, 5), (7, 5, 2)] print(prod(coords)) &gt;&gt;&gt; [42, 120, 80] </code></pre>
1
2009-01-30T00:38:38Z
[ "python", "module" ]
Which Python module is suitable for data manipulation in a list?
493,853
<p>I have a sequence of x, y and z -coordinates, which I need to manipulate. They are in one list of three tuples, like {(x1, y1, z1), (x2, y2, z2), ...}.</p> <p>I need addition, multiplication and logarithm to manipulate my data.</p> <p>I would like to study a module, which is as powerful as Awk -language.</p>
3
2009-01-29T22:54:02Z
495,215
<p>If you need many array manipulation, then numpy is the best choice in python</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; data = numpy.array([(2, 4, 8), (3, 6, 5), (7, 5, 2)]) &gt;&gt;&gt; data array([[2, 4, 8], [3, 6, 5], [7, 5, 2]]) &gt;&gt;&gt; data.sum() # product of all elements 42 &gt;&gt;&gt; data.sum(axis=1) # sum of elements in rows array([14, 14, 14]) &gt;&gt;&gt; data.sum(axis=0) # sum of elements in columns array([12, 15, 15]) &gt;&gt;&gt; numpy.product(data, axis=1) # product of elements in rows array([64, 90, 70]) &gt;&gt;&gt; numpy.product(data, axis=0) # product of elements in columns array([ 42, 120, 80]) &gt;&gt;&gt; numpy.product(data) # product of all elements 403200 </code></pre> <p>or element wise operation with arrays</p> <pre><code>&gt;&gt;&gt; x,y,z = map(numpy.array,[(2, 4, 8), (3, 6, 5), (7, 5, 2)]) &gt;&gt;&gt; x array([2, 4, 8]) &gt;&gt;&gt; y array([3, 6, 5]) &gt;&gt;&gt; z array([7, 5, 2]) &gt;&gt;&gt; x*y array([ 6, 24, 40]) &gt;&gt;&gt; x*y*z array([ 42, 120, 80]) &gt;&gt;&gt; x+y+z array([12, 15, 15]) </code></pre> <p>element wise mathematical operations, e.g.</p> <pre><code>&gt;&gt;&gt; numpy.log(data) array([[ 0.69314718, 1.38629436, 2.07944154], [ 1.09861229, 1.79175947, 1.60943791], [ 1.94591015, 1.60943791, 0.69314718]]) &gt;&gt;&gt; numpy.exp(x) array([ 7.3890561 , 54.59815003, 2980.95798704]) </code></pre>
5
2009-01-30T11:28:15Z
[ "python", "module" ]
Which Python module is suitable for data manipulation in a list?
493,853
<p>I have a sequence of x, y and z -coordinates, which I need to manipulate. They are in one list of three tuples, like {(x1, y1, z1), (x2, y2, z2), ...}.</p> <p>I need addition, multiplication and logarithm to manipulate my data.</p> <p>I would like to study a module, which is as powerful as Awk -language.</p>
3
2009-01-29T22:54:02Z
495,247
<p>You don't need a separate library or module to do this. Python has list comprehensions built into the language, which lets you manipulate lists and perform caculations. You could use the numpy module to do the same thing if you want to do lots of scientific calculations, or if you want to do lots of heavy number crunching.</p>
1
2009-01-30T11:42:37Z
[ "python", "module" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
493,991
<p>I was going to say closures but found <a href="http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&amp;article_id=61016" rel="nofollow">this thread</a>... (not that I understand how it would work in a "static" language)</p> <p>Related concepts are <a href="http://en.wikipedia.org/wiki/First-class_function" rel="nofollow">functions-as-first-class-objects</a> and <a href="http://en.wikipedia.org/wiki/Higher-order_function" rel="nofollow">higher-order procedures</a>. (e.g. a function that takes a function as input and/or returns a function as output)</p> <p>edit: (for the nitpickers here) I'll echo a comment I made on @David Locke's post. Dynamically-interpreted languages make it possible to use an existing software program/project in conjunction with a small function or class created at the spur-of-the-moment to explore something interactively. Probably the best example is function graphing. If I wrote a function-graphing object with a <code>graph(f,xmin,xmax)</code> function, I could use it to explore functions like x<sup>2</sup> or sin(x) or whatever. I do this in MATLAB all the time; it's interpreted and has anonymous functions (<code>@(x) x^2</code>) that can be constructed at the interpreter prompt to pass into higher-order functions (graphing functions, derivative operators, root finders, etc).</p>
0
2009-01-29T23:51:36Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
493,993
<p>With a dynamic language it's much easier to have a command line interpreter so you can test things on the command line and don't have to worry about a compile step to see if they work.</p>
0
2009-01-29T23:52:10Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
494,001
<p><a href="http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html" rel="nofollow">Here's Steve Yegge</a> on the subject.</p> <p>Guido van Rossum also linked to that talk in <a href="http://neopythonic.blogspot.com/2008/11/scala.html" rel="nofollow">his take of Scala</a>.</p>
3
2009-01-29T23:54:36Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
494,009
<p>In dynamic languages you can use values in ways that you know are correct. In a statically typed language you can only use values in ways the compiler knows are correct. You need all of the things you mentioned to regain flexibility that's taken away by the type system (I'm not bashing static type systems, the flexibility is often taken away for good reasons). This is a lot of complexity that you don't have to deal with in a dynamic language if you want to use values in ways the language designer didn't anticipate (for example, putting values of different types in a hash table).</p> <p>So it's not that you can't do these things in a statically typed language (if you have runtime reflection), it's just more complicated.</p>
1
2009-01-29T23:59:50Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
494,055
<p>In theory, there's nothing that dynamic languages can do and static languages can't. Smart people put a lot of work into making <em>very good</em> dynamic languages, leading to a perception at the moment that dynamic languages are ahead while static ones need to catch up.</p> <p>In time, this will swing the other way. Already various static languages have:</p> <ul> <li><p>Generics, which make static types less stupid by letting it select the right type when objects are passed around, saving the programmer from having to cast it themselves</p></li> <li><p>Type inference, which saves having to waste time on writing the stuff that should be obvious</p></li> <li><p>Closures, which among <em>many</em> other things help to separate mechanism from intention, letting you pull together complicated algorithms from mostly existing ingredients.</p></li> <li><p>Implicit conversions, which lets you simulate "monkey patching" without the risks it usually involves.</p></li> <li><p>Code loading and easy programmatic access to the compiler, so users and third parties can script your program. Use with caution!</p></li> <li><p>Syntaxes that are more conducive to the creation of Domain Specific Languages within them.</p></li> </ul> <p>...and no doubt more to come. The dynamic movement has spawned some interesting developments in static language design, and we all benefit from the competition. I only hope more of these features make it to the mainstream.</p> <p>There's one place where I don't see the dominant dynamic language being replaced, and that's Javascript in the browser. There's just too much of an existing market to replace, so the emphasis seems to be towards making Javascript itself better instead.</p>
15
2009-01-30T00:23:01Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
494,062
<p>I actually wrote a blog post on this: <a href="http://jasonmbaker.wordpress.com/2008/12/11/duck-typing-vs-interfaces/" rel="nofollow">linky</a>. But that post basically can be summed up like this:</p> <p>You'd be surprised at how much of a load off your mind it is to not have to name at compile time what type your variable is. Thus, python tends to be a very productive language.</p> <p>On the other hand, even with good unit tests, you'd also be surprised at what kinds of stupid mistakes you're allowing yourself to make.</p>
1
2009-01-30T00:27:21Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
494,117
<blockquote> <p>"I'm curious what the benefits are of dynamic languages even when you have those."</p> </blockquote> <p>Compared to D programming language:</p> <ul> <li><p>Python is a more compact language. It allows you to express as much as D but it uses many fewer different concepts to achieve it -- <em>less is more</em>.</p></li> <li><p>Python has a powerful standard library -- <em>batteries included</em>.</p></li> </ul> <p>I don't know whether D has interactive prompts but in Python an interactive shell such as <a href="http://ipython.scipy.org/moin/Documentation" rel="nofollow">ipython</a> is an integrated part of development process.</p>
2
2009-01-30T01:00:21Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
494,118
<p>I find dynamic languages like Perl and to a lesser extent Python allow me to write quick and dirty scripts for things I need to do. The run cycle is much shorter in dynamic languages and often less code needs to be written then in a statically typed language which increases my productivity. This unfortunately comes at the cost of maintainability but that is a fault of the way I write programs in dynamic languages not in the languages them selves.</p>
0
2009-01-30T01:01:42Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
494,121
<p>Compiled languages tend to be used when efficiency and type safety are the priorities. Otherwise I can't think of any reason why anyone wouldn't be using ruby :)</p>
-2
2009-01-30T01:01:51Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
494,423
<p>One big advantage of dynamic <em>typing</em> when using objects is that you don't need to use class hierarchies anymore when you want several classes to have the same interface - that's more or less what is called duck typing. Bad inheritance is very difficult to fix afterwards - this makes refactoring often harder than it is in a language like python.</p>
1
2009-01-30T03:49:42Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
495,293
<p>The point is that in a dynamic language you can implement the same functionality much quicker than in a statically typed one. Therefore the productivity is typically much higher.</p> <p>Things like templates or polymorphism in principle give you lots of flexibility, but you have to write a large amount of code to make it work. In a dynamic language this flexibility almost comes for free.</p> <p>So I think you look at the difference in the wrong way, productivity really is the main point here (just like garbage collection improves productivity, but otherwise does not really allow you to do new things).</p>
1
2009-01-30T12:02:25Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
496,932
<p>Example in Python:</p> <pre><code>def lengths(sequence): try: return sum(len(item) for item in sequence) except TypeError: return "Wolf among the sheep!" &gt;&gt;&gt; lengths(["a", "b", "c", (1, 2, 3)]) 6 &gt;&gt;&gt; lengths( ("1", "2", 3) ) 'Wolf among the sheep!' </code></pre> <p>How long do you think this took me to write, and how many compile-run-debug cycles?</p> <p>If you think my example is trivial, I can reply by saying that dynamic languages make trivial many programming tasks.</p>
2
2009-01-30T19:45:27Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
Uses for Dynamic Languages
493,973
<p>My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. </p> <p>The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, <strong>even with templates, polymorphism, static type inference, and maybe runtime reflection?</strong></p>
8
2009-01-29T23:42:47Z
667,275
<p>Take a look at this <a href="http://en.wikipedia.org/wiki/ECMAScript%5Ffor%5FXML" rel="nofollow">e4x</a> example in JavaScript:</p> <pre><code>var sales = &lt;sales vendor="John"&gt; &lt;item type="peas" price="4" quantity="6"/&gt; &lt;item type="carrot" price="3" quantity="10"/&gt; &lt;item type="chips" price="5" quantity="3"/&gt; &lt;/sales&gt;; alert( sales.item.(@type == "carrot").@quantity ); alert( sales.@vendor ); for each( var price in sales..@price ) { alert( price ); } </code></pre> <p>Especially, take a look at line:</p> <pre><code>alert( sales.item.(@type == "carrot").@quantity ); </code></pre> <p>In typical static languages, you don’t get to write sales.item, since you can not know that item is property of sales until runtime. This is not limited to e4x. You get to program in similar style when connecting when writing SOAP clients or any other underlying type you do not know until runtime. In a static language, you would typically need to run a tool that will generate stub classes or program in a very verbose way. Then, if something changes in a web service, you need to regenerate stubs all over again. Take a look at java DOM code: </p> <pre><code>import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class Foo { public Document createDocument() { Document document = DocumentHelper.createDocument(); Element root = document.addElement( "root" ); Element author1 = root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" ); Element author2 = root.addElement( "author" ) .addAttribute( "name", "Bob" ) .addAttribute( "location", "US" ) .addText( "Bob McWhirter" ); return document; } } </code></pre> <p>Definitely much more verbose than your dynamic code. And, of course, it is not statically typed. There is no way to check that you misspelled “author” as "autor" until runtime. All this verbosity is essentially there to let you capture something that is dynamic in nature in static style.</p> <p>I think this is one of the strong points of dynamic languages.</p>
0
2009-03-20T17:59:33Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
retrieving current URL from FireFox with python
493,978
<p>I want to know what is the current url of active tab in running firefox instance from python module. Does FireFox have any API for this and does python know to work with it?</p>
4
2009-01-29T23:44:47Z
494,063
<p>If on windows you can use win32com</p> <pre><code>import win32clipboard import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate('Some Application Title') </code></pre> <p>Then use shell.SendKeys to do a ctrl+l and a ctrl+c</p> <p>Then read the string in the clipboard.</p> <p>It's horkey though it will work, alternatly you can use something like AutoIt an compile the code to an exe that you can work with.</p> <p>Hope this helps.</p>
1
2009-01-30T00:27:25Z
[ "python", "firefox", "python-extensions" ]
retrieving current URL from FireFox with python
493,978
<p>I want to know what is the current url of active tab in running firefox instance from python module. Does FireFox have any API for this and does python know to work with it?</p>
4
2009-01-29T23:44:47Z
494,070
<p>I think i found <a href="https://developer.mozilla.org/en/PyXPCOM" rel="nofollow">something</a> that can help me.</p>
-1
2009-01-30T00:32:52Z
[ "python", "firefox", "python-extensions" ]
retrieving current URL from FireFox with python
493,978
<p>I want to know what is the current url of active tab in running firefox instance from python module. Does FireFox have any API for this and does python know to work with it?</p>
4
2009-01-29T23:44:47Z
494,287
<p>There is also a <a href="http://docs.python.org/library/webbrowser.html" rel="nofollow">webbrowser</a> module in python, but it seems to only allow you to open new windows/tabs.</p>
0
2009-01-30T02:22:56Z
[ "python", "firefox", "python-extensions" ]
retrieving current URL from FireFox with python
493,978
<p>I want to know what is the current url of active tab in running firefox instance from python module. Does FireFox have any API for this and does python know to work with it?</p>
4
2009-01-29T23:44:47Z
1,042,075
<p>The most convenient way maybe insatll a firefox extension to open up a tcp service, then you can exchange info with firefox.</p> <p><a href="http://wiki.github.com/bard/mozrepl" rel="nofollow">mozrepl</a> can set up a telnet service, you can call js-like command to get info.</p> <p>With telnetscript (http: //code.activestate.com/recipes/152043/), you can write:</p> <pre><code> import telnetscript script = """rve w content.location.href; ru repl> w repl.quit() cl """ conn = telnetscript.telnetscript( '127.0.0.1', {}, 4242 ) ret = conn.RunScript( script.split( '\n' )).split( '\n' ) print ret[-2][6:] </code></pre>
2
2009-06-25T03:46:56Z
[ "python", "firefox", "python-extensions" ]
CDN options for image resizing
493,981
<p>Background:</p> <p>I working on an application on Google App Engine. Its been going really well until I hit one of their limitations in file size -- 1MB. One of the components of my application resizes images, which have been uploaded by users. The files are directly uploaded to S3 (<a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434" rel="nofollow">http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434</a>) via POST. I was planning on using a CDN to delivered the resized images.</p> <p>Question:</p> <p>I was wondering if there was CDN that provided an API for resizing images through HTTP call. I found out that SimpleCDN once provided the service, but has sense removed it. I would like to tell the CDN to resize the image I am requesting from the URL.</p> <p>For example,</p> <p>original URL: <a href="http://cdn.example.com/images/large_picture.jpg" rel="nofollow">http://cdn.example.com/images/large_picture.jpg</a> resized image to 125x100: <a href="http://cdn.example.com/images/large_picture.jpg/125/100" rel="nofollow">http://cdn.example.com/images/large_picture.jpg/125/100</a></p> <p>Does anyone know of CDN that provides a functionality like this? Or have a suggestion to get around the 1MB limit on Google App Engine (not a hack, but alternative method of code).</p>
2
2009-01-29T23:45:54Z
627,748
<p>Looks like I have found a service that provides what I am indeed looking for. <a href="http://developer.nirvanix.com/files/folders/python/entry1253.aspx" rel="nofollow">Nirvanix</a> provides an image resize API and even has a nice library for Google App Engine to use with their API. Just thought I would share my findings.</p>
3
2009-03-09T19:52:56Z
[ "python", "google-app-engine", "rest", "image-manipulation", "cdn" ]
CDN options for image resizing
493,981
<p>Background:</p> <p>I working on an application on Google App Engine. Its been going really well until I hit one of their limitations in file size -- 1MB. One of the components of my application resizes images, which have been uploaded by users. The files are directly uploaded to S3 (<a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434" rel="nofollow">http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434</a>) via POST. I was planning on using a CDN to delivered the resized images.</p> <p>Question:</p> <p>I was wondering if there was CDN that provided an API for resizing images through HTTP call. I found out that SimpleCDN once provided the service, but has sense removed it. I would like to tell the CDN to resize the image I am requesting from the URL.</p> <p>For example,</p> <p>original URL: <a href="http://cdn.example.com/images/large_picture.jpg" rel="nofollow">http://cdn.example.com/images/large_picture.jpg</a> resized image to 125x100: <a href="http://cdn.example.com/images/large_picture.jpg/125/100" rel="nofollow">http://cdn.example.com/images/large_picture.jpg/125/100</a></p> <p>Does anyone know of CDN that provides a functionality like this? Or have a suggestion to get around the 1MB limit on Google App Engine (not a hack, but alternative method of code).</p>
2
2009-01-29T23:45:54Z
1,807,373
<p>SteadyOffload does it as well.</p>
3
2009-11-27T08:15:48Z
[ "python", "google-app-engine", "rest", "image-manipulation", "cdn" ]
How can I disable quoting in the Python 2.4 CSV reader?
494,054
<p>I am writing a Python utility that needs to parse a large, regularly-updated CSV file I don't control. The utility must run on a server with only Python 2.4 available. The CSV file does not quote field values at all, but the <a href="http://www.python.org/doc/2.4.3/lib/csv-fmt-params.html#csv-fmt-params" rel="nofollow">Python 2.4 version of the csv library</a> does not seem to give me any way to turn off quoting, it just allows me to set the quote character (<code>dialect.quotechar = '"'</code> or whatever). If I try setting the quote character to <code>None</code> or the empty string, I get an error.</p> <p>I can sort of work around this by setting <code>dialect.quotechar</code> to some "rare" character, but this is brittle, as there is no ASCII character I can absolutely guarantee will not show up in field values (except the delimiter, but if I set <code>dialect.quotechar = dialect.delimiter</code>, things go predictably haywire).</p> <p>In <a href="http://docs.python.org/library/csv.html" rel="nofollow">Python 2.5 and later</a>, if I set <code>dialect.quoting</code> to <code>csv.QUOTE_NONE</code>, the CSV reader respects that and does not interpret any character as a quote character. Is there any way to duplicate this behavior in Python 2.4?</p> <p><strong>UPDATE</strong>: Thanks Triptych and Mark Roddy for helping to narrow the problem down. Here's a simplest-case demonstration:</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; import StringIO &gt;&gt;&gt; data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ &gt;&gt;&gt; reader = csv.reader(StringIO.StringIO(data)) &gt;&gt;&gt; for i in reader: print i ... [] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? _csv.Error: newline inside string </code></pre> <p>The problem only occurs when there's a single double-quote character in the <em>final</em> column of a row. Unfortunately, this situation exists in my dataset. I've accepted Tanj's solution: manually assign a nonprinting character (<code>"\x07"</code> or <code>BEL</code>) as the quotechar. This is hacky, but it works, and I haven't yet seen another solution that does. Here's a demo of the solution in action:</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; import StringIO &gt;&gt;&gt; class MyDialect(csv.Dialect): ... quotechar = '\x07' ... delimiter = ',' ... lineterminator = '\n' ... doublequote = False ... skipinitialspace = False ... quoting = csv.QUOTE_NONE ... escapechar = '\\' ... &gt;&gt;&gt; dialect = MyDialect() &gt;&gt;&gt; data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ &gt;&gt;&gt; reader = csv.reader(StringIO.StringIO(data), dialect=dialect) &gt;&gt;&gt; for i in reader: print i ... [] ['1', '2', '3', '4', '"5'] ['1', '2', '3', '4', '5'] </code></pre> <p>In Python 2.5+ setting quoting to csv.QUOTE_NONE would be sufficient, and the value of <code>quotechar</code> would then be irrelevant. (I'm actually getting my initial dialect via a <code>csv.Sniffer</code> and then overriding the quotechar value, not by subclassing <code>csv.Dialect</code>, but I don't want that to be a distraction from the real issue; the above two sessions demonstrate that <code>Sniffer</code> isn't the problem.)</p>
10
2009-01-30T00:22:40Z
494,126
<p>I don't know if python would like/allow it but could you use a non-printable ascii code such as BEL or BS (backspace) These I would think to be extremely rare.</p>
12
2009-01-30T01:05:04Z
[ "python", "csv" ]
How can I disable quoting in the Python 2.4 CSV reader?
494,054
<p>I am writing a Python utility that needs to parse a large, regularly-updated CSV file I don't control. The utility must run on a server with only Python 2.4 available. The CSV file does not quote field values at all, but the <a href="http://www.python.org/doc/2.4.3/lib/csv-fmt-params.html#csv-fmt-params" rel="nofollow">Python 2.4 version of the csv library</a> does not seem to give me any way to turn off quoting, it just allows me to set the quote character (<code>dialect.quotechar = '"'</code> or whatever). If I try setting the quote character to <code>None</code> or the empty string, I get an error.</p> <p>I can sort of work around this by setting <code>dialect.quotechar</code> to some "rare" character, but this is brittle, as there is no ASCII character I can absolutely guarantee will not show up in field values (except the delimiter, but if I set <code>dialect.quotechar = dialect.delimiter</code>, things go predictably haywire).</p> <p>In <a href="http://docs.python.org/library/csv.html" rel="nofollow">Python 2.5 and later</a>, if I set <code>dialect.quoting</code> to <code>csv.QUOTE_NONE</code>, the CSV reader respects that and does not interpret any character as a quote character. Is there any way to duplicate this behavior in Python 2.4?</p> <p><strong>UPDATE</strong>: Thanks Triptych and Mark Roddy for helping to narrow the problem down. Here's a simplest-case demonstration:</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; import StringIO &gt;&gt;&gt; data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ &gt;&gt;&gt; reader = csv.reader(StringIO.StringIO(data)) &gt;&gt;&gt; for i in reader: print i ... [] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? _csv.Error: newline inside string </code></pre> <p>The problem only occurs when there's a single double-quote character in the <em>final</em> column of a row. Unfortunately, this situation exists in my dataset. I've accepted Tanj's solution: manually assign a nonprinting character (<code>"\x07"</code> or <code>BEL</code>) as the quotechar. This is hacky, but it works, and I haven't yet seen another solution that does. Here's a demo of the solution in action:</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; import StringIO &gt;&gt;&gt; class MyDialect(csv.Dialect): ... quotechar = '\x07' ... delimiter = ',' ... lineterminator = '\n' ... doublequote = False ... skipinitialspace = False ... quoting = csv.QUOTE_NONE ... escapechar = '\\' ... &gt;&gt;&gt; dialect = MyDialect() &gt;&gt;&gt; data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ &gt;&gt;&gt; reader = csv.reader(StringIO.StringIO(data), dialect=dialect) &gt;&gt;&gt; for i in reader: print i ... [] ['1', '2', '3', '4', '"5'] ['1', '2', '3', '4', '5'] </code></pre> <p>In Python 2.5+ setting quoting to csv.QUOTE_NONE would be sufficient, and the value of <code>quotechar</code> would then be irrelevant. (I'm actually getting my initial dialect via a <code>csv.Sniffer</code> and then overriding the quotechar value, not by subclassing <code>csv.Dialect</code>, but I don't want that to be a distraction from the real issue; the above two sessions demonstrate that <code>Sniffer</code> isn't the problem.)</p>
10
2009-01-30T00:22:40Z
494,177
<p>I tried a few examples using Python 2.4.3, and it seemed to be smart enough to detect that the fields were unquoted. </p> <p>I know you've already accepted a (slightly hacky) answer, but have you tried just leaving the <code>reader.dialect.quotechar</code> value alone? What happens if you do?</p> <p>Any chance we could get example input?</p>
3
2009-01-30T01:29:25Z
[ "python", "csv" ]
How can I disable quoting in the Python 2.4 CSV reader?
494,054
<p>I am writing a Python utility that needs to parse a large, regularly-updated CSV file I don't control. The utility must run on a server with only Python 2.4 available. The CSV file does not quote field values at all, but the <a href="http://www.python.org/doc/2.4.3/lib/csv-fmt-params.html#csv-fmt-params" rel="nofollow">Python 2.4 version of the csv library</a> does not seem to give me any way to turn off quoting, it just allows me to set the quote character (<code>dialect.quotechar = '"'</code> or whatever). If I try setting the quote character to <code>None</code> or the empty string, I get an error.</p> <p>I can sort of work around this by setting <code>dialect.quotechar</code> to some "rare" character, but this is brittle, as there is no ASCII character I can absolutely guarantee will not show up in field values (except the delimiter, but if I set <code>dialect.quotechar = dialect.delimiter</code>, things go predictably haywire).</p> <p>In <a href="http://docs.python.org/library/csv.html" rel="nofollow">Python 2.5 and later</a>, if I set <code>dialect.quoting</code> to <code>csv.QUOTE_NONE</code>, the CSV reader respects that and does not interpret any character as a quote character. Is there any way to duplicate this behavior in Python 2.4?</p> <p><strong>UPDATE</strong>: Thanks Triptych and Mark Roddy for helping to narrow the problem down. Here's a simplest-case demonstration:</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; import StringIO &gt;&gt;&gt; data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ &gt;&gt;&gt; reader = csv.reader(StringIO.StringIO(data)) &gt;&gt;&gt; for i in reader: print i ... [] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? _csv.Error: newline inside string </code></pre> <p>The problem only occurs when there's a single double-quote character in the <em>final</em> column of a row. Unfortunately, this situation exists in my dataset. I've accepted Tanj's solution: manually assign a nonprinting character (<code>"\x07"</code> or <code>BEL</code>) as the quotechar. This is hacky, but it works, and I haven't yet seen another solution that does. Here's a demo of the solution in action:</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; import StringIO &gt;&gt;&gt; class MyDialect(csv.Dialect): ... quotechar = '\x07' ... delimiter = ',' ... lineterminator = '\n' ... doublequote = False ... skipinitialspace = False ... quoting = csv.QUOTE_NONE ... escapechar = '\\' ... &gt;&gt;&gt; dialect = MyDialect() &gt;&gt;&gt; data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ &gt;&gt;&gt; reader = csv.reader(StringIO.StringIO(data), dialect=dialect) &gt;&gt;&gt; for i in reader: print i ... [] ['1', '2', '3', '4', '"5'] ['1', '2', '3', '4', '5'] </code></pre> <p>In Python 2.5+ setting quoting to csv.QUOTE_NONE would be sufficient, and the value of <code>quotechar</code> would then be irrelevant. (I'm actually getting my initial dialect via a <code>csv.Sniffer</code> and then overriding the quotechar value, not by subclassing <code>csv.Dialect</code>, but I don't want that to be a distraction from the real issue; the above two sessions demonstrate that <code>Sniffer</code> isn't the problem.)</p>
10
2009-01-30T00:22:40Z
496,952
<p>+1 for Triptych</p> <p>Confirmation that csv.reader automatically handles csv files with out quotes: </p> <pre><code>&gt;&gt;&gt; import StringIO &gt;&gt;&gt; import csv &gt;&gt;&gt; data=""" ... 1,2,3,4,5 ... 1,2,3,4,5 ... 1,2,3,4,5 ... """ &gt;&gt;&gt; reader=csv.reader(StringIO.StringIO(data)) &gt;&gt;&gt; for i in reader: ... print i ... [] ['1', '2', '3', '4', '5'] ['1', '2', '3', '4', '5'] ['1', '2', '3', '4', '5'] </code></pre>
0
2009-01-30T19:48:51Z
[ "python", "csv" ]
How to write the Fibonacci Sequence in Python
494,594
<p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 &amp; 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening.</p> <pre><code>startNumber = int(raw_input("Enter the start number here ")) endNumber = int(raw_input("Enter the end number here ")) def fib(n): if n &lt; 2: return n return fib(n-2) + fib(n-1) print map(fib, range(startNumber, endNumber)) </code></pre> <p>Someone pointed out in my Part II (which was closed for being a duplicate - <a href="http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii">http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii</a>) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome.</p> <hr> <p>I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?).</p> <p>What I have so far is no actual coding but rather:</p> <ul> <li>Write Fib sequence formula to infinite</li> <li>Display startNumber to endNumber only from Fib sequence.</li> </ul> <p>I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.</p>
68
2009-01-30T05:49:13Z
494,601
<p>Calculate the Fibonacci sequence from the beginning (presumably using a while loop), but don't output anything until the values are >= startNumber, and exit as soon as the values are greater than endNumber.</p> <p>Actual code isn't provided because this smells like homework, but it sounds from your wording that bounding the output is the part that you were uncertain about.</p>
0
2009-01-30T05:52:54Z
[ "python", "fibonacci", "sequences" ]
How to write the Fibonacci Sequence in Python
494,594
<p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 &amp; 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening.</p> <pre><code>startNumber = int(raw_input("Enter the start number here ")) endNumber = int(raw_input("Enter the end number here ")) def fib(n): if n &lt; 2: return n return fib(n-2) + fib(n-1) print map(fib, range(startNumber, endNumber)) </code></pre> <p>Someone pointed out in my Part II (which was closed for being a duplicate - <a href="http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii">http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii</a>) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome.</p> <hr> <p>I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?).</p> <p>What I have so far is no actual coding but rather:</p> <ul> <li>Write Fib sequence formula to infinite</li> <li>Display startNumber to endNumber only from Fib sequence.</li> </ul> <p>I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.</p>
68
2009-01-30T05:49:13Z
494,612
<p>Start from reading good Python book. One of such book is "How to Think Like a Computer Scientist", especially chapter 5 in your case.</p>
0
2009-01-30T05:59:36Z
[ "python", "fibonacci", "sequences" ]
How to write the Fibonacci Sequence in Python
494,594
<p>I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 &amp; 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening.</p> <pre><code>startNumber = int(raw_input("Enter the start number here ")) endNumber = int(raw_input("Enter the end number here ")) def fib(n): if n &lt; 2: return n return fib(n-2) + fib(n-1) print map(fib, range(startNumber, endNumber)) </code></pre> <p>Someone pointed out in my Part II (which was closed for being a duplicate - <a href="http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii">http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii</a>) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome.</p> <hr> <p>I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?).</p> <p>What I have so far is no actual coding but rather:</p> <ul> <li>Write Fib sequence formula to infinite</li> <li>Display startNumber to endNumber only from Fib sequence.</li> </ul> <p>I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.</p>
68
2009-01-30T05:49:13Z
494,636
<p>The idea behind the Fibonacci sequence is shown in the following Python code:</p> <pre><code>def fib(n): if n == 1: return 1 elif n == 0: return 0 else: return fib(n-1) + fib(n-2) </code></pre> <p>This means that fib is a function that can do one of three things. It defines fib(1) == 1, fib(0) == 0, and fib(n) to be:</p> <p>fib(n-1) + fib(n-2)</p> <p>Where n is an arbitrary integer. This means that fib(2) for example, expands out to the following arithmetic:</p> <pre><code>fib(2) = fib(1) + fib(0) fib(1) = 1 fib(0) = 0 # Therefore by substitution: fib(2) = 1 + 0 fib(2) = 1 </code></pre> <p>We can calculate fib(3) the same way with the arithmetic shown below:</p> <pre><code>fib(3) = fib(2) + fib(1) fib(2) = fib(1) + fib(0) fib(2) = 1 fib(1) = 1 fib(0) = 0 # Therefore by substitution: fib(3) = 1 + 1 + 0 </code></pre> <p>The important thing to realize here is that fib(3) can't be calculated without calculating fib(2), which is calculated by knowing the definitions of fib(1) and fib(0). Having a function call itself like the fibonacci function does is called recursion, and it's an important topic in programming.</p> <p>This sounds like a homework assignment so I'm not going to do the start/end part for you. Python is a wonderfully expressive language for this though, so this should make sense if you understand math, and will hopefully teach you about recursion. Good luck!</p> <p>Edit: One potential criticism of my code is that it doesn't use the super-handy Python function yield, which makes the fib(n) function a lot shorter. My example is a little bit more generic though, since not a lot of languages outside Python actually have yield. </p>
16
2009-01-30T06:15:45Z
[ "python", "fibonacci", "sequences" ]