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
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,821
<p>Go find out how to convert a recursive problem into an iterative one. Should be able to calculate from there.</p> <p>That's might be the principles that they're trying to get you to learn, especially if this is an Algorithms course.</p>
0
2009-01-30T07:45:25Z
[ "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
499,245
<p>There is lots of information about the Fibonacci Sequence on <a href="http://en.wikipedia.org/wiki/Fibonacci_number">wikipedia</a> and on <a href="http://mathworld.wolfram.com/FibonacciNumber.html">wolfram</a>. A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quickly if possible) what you need.</p> <h2>Write Fib sequence formula to infinite</h2> <p>In math, it's given in a recursive form:</p> <p><img src="http://upload.wikimedia.org/math/7/6/f/76f99713cf111eb035d908228c351710.png" alt="fibonacci from wikipedia"></p> <p>In programming, <strong>infinite</strong> doesn't exist. You can use a recursive form translating the math form directly in your language, for example in Python it becomes:</p> <pre><code>def F(n): if n == 0: return 0 elif n == 1: return 1 else: return F(n-1)+F(n-2) </code></pre> <p>Try it in your favourite language and see that this form requires <strong>a lot</strong> of time as n gets bigger. In fact, this is O(2<sup>n</sup>) in time.</p> <p>Go on on the sites I linked to you and will see this (on wolfram):</p> <p><img src="http://mathworld.wolfram.com/images/equations/FibonacciNumber/NumberedEquation6.gif" alt="alt text"></p> <p>This one is pretty easy to implement and very, very fast to compute, in Python:</p> <pre><code>from math import sqrt def F(n): return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)) </code></pre> <p>An other way to do it is following the definition (from <a href="http://en.wikipedia.org/wiki/Fibonacci_number">wikipedia</a>):</p> <blockquote> <p>The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself, yielding the sequence 0, 1, 1, 2, 3, 5, 8, etc.</p> </blockquote> <p>If your language supports iterators you may do something like:</p> <pre><code>def F(): a,b = 0,1 yield a yield b while True: a, b = b, a + b yield b </code></pre> <h2>Display startNumber to endNumber only from Fib sequence.</h2> <p>Once you know how to generate Fibonacci Numbers you just have to cycle trough the numbers and check if they verify the given conditions.</p> <p>Suppose now you wrote a f(n) that returns the n-th term of the Fibonacci Sequence (like the one with sqrt(5) )</p> <p>In most languages you can do something like:</p> <pre><code>def SubFib(startNumber, endNumber): n = 0 cur = f(n) while cur &lt;= endNumber: if startNumber &lt;= cur: print cur n += 1 cur = f(n) </code></pre> <p>In python I'd use the iterator form and go for:</p> <pre><code>def SubFib(startNumber, endNumber): for cur in F(): if cur &gt; endNumber: return if cur &gt;= startNumber: yield cur for i in SubFib(10, 200): print i </code></pre> <p>My hint is to <em>learn to read</em> what you need. Project Euler (google for it) will train you to do so :P Good luck and have fun!</p>
153
2009-01-31T18:01:14Z
[ "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
6,498,725
<pre><code>def fib(): a,b = 1,1 num=eval(input("Please input what Fib number you want to be calculated: ")) num_int=int(num-2) for i in range (num_int): a,b=b,a+b print(b) </code></pre>
2
2011-06-27T20:42:31Z
[ "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
7,872,648
<p>15 minutes into a tutorial I used when learning Python, it asked the reader to write a program that would calculate a Fibonacci sequence from 3 input numbers (first Fibonacci number, second number, and number at which to stop the sequence). The tutorial had only covered variables, if/thens, and loops up to that point. No functions yet. I came up with the following code:</p> <pre><code>sum = 0 endingnumber = 1 print "\n.:Fibonacci sequence:.\n" firstnumber = input("Enter the first number: ") secondnumber = input("Enter the second number: ") endingnumber = input("Enter the number to stop at: ") if secondnumber &lt; firstnumber: print "\nSecond number must be bigger than the first number!!!\n" else: while sum &lt;= endingnumber: print firstnumber if secondnumber &gt; endingnumber: break else: print secondnumber sum = firstnumber + secondnumber firstnumber = sum secondnumber = secondnumber + sum </code></pre> <p>As you can see, it's really inefficient, but it DOES work.</p>
0
2011-10-24T07:53:33Z
[ "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
15,950,618
<p>use recursion:</p> <pre><code>def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) x=input('which fibonnaci do you want?') print fib(x) </code></pre>
0
2013-04-11T13:53:43Z
[ "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
18,763,575
<p>Just going through <a href="http://projecteuler.net/problem=2" rel="nofollow">http://projecteuler.net/problem=2</a> this was my take on it</p> <pre><code># Even Fibonacci numbers # Problem 2 def get_fibonacci(size): numbers = [1,2] while size &gt; len(numbers): next_fibonacci = numbers[-1]+numbers[-2] numbers.append(next_fibonacci) print numbers get_fibonacci(20) </code></pre>
0
2013-09-12T11:53:24Z
[ "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
20,169,916
<pre><code>def fib(x, y, n): if n &lt; 1: return x, y, n else: return fib(y, x + y, n - 1) print fib(0, 1, 4) (3, 5, 0) # def fib(x, y, n): if n &gt; 1: for item in fib(y, x + y, n - 1): yield item yield x, y, n f = fib(0, 1, 12) f.next() (89, 144, 1) f.next()[0] 55 </code></pre>
0
2013-11-24T01:09:50Z
[ "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
21,399,636
<p>This was a practice assignment that I saw on Khan Academy's Sal on Python Programming: <a href="https://www.khanacademy.org/science/computer-science-subject/computer-science/v/exercise---write-a-fibonacci-function" rel="nofollow">https://www.khanacademy.org/science/computer-science-subject/computer-science/v/exercise---write-a-fibonacci-function</a></p> <p>He is probably not the first person to assign that as some work to do. But it is awesome figuring it out by yourself. I learned a lot figuring it out actually and it was a blast.</p> <p>I recommend that you figure it out by yourself before you try and copy someone else's code for homework.</p> <p>In the video above, Sal the instructor, shows shows the whole theory behind the Fibonacci number, and with that in mind you should be able to figure it out.</p> <p>It took me about 10 minutes and this is the code I made (I am learning Python starting 3 days ago and this is my first programming language to learn). I would not have been able to write the code if it was not for the video from the tutorial before: <a href="https://www.khanacademy.org/science/computer-science-subject/computer-science/v/comparing-iterative-and-recursive-factorial-functions" rel="nofollow">https://www.khanacademy.org/science/computer-science-subject/computer-science/v/comparing-iterative-and-recursive-factorial-functions</a> that one gives an example of Sal doing a recursive factorial equation and gives you the mind-set to solve this problem.</p> <p>Here is my code:</p> <pre><code>def fibonacci(num): if num &lt;= 1: #base case return num else: return fibonacci(num-1) + fibonacci(num-2) </code></pre> <p>You can see that if the number is 1 or 0 then you just return the number.</p> <p>I find this cleaner than saying if number is 1 return 1 and if number is 0 return 0. </p>
0
2014-01-28T07:44:16Z
[ "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
21,507,234
<p>These all look a bit more complicated than they need to be. My code is very simple and fast:</p> <pre><code>def fibonacci(x): List = [] f = 1 List.append(f) List.append(f) #because the fibonacci sequence has two 1's at first while f&lt;=x: f = List[-1] + List[-2] #says that f = the sum of the last two f's in the series List.append(f) else: List.remove(List[-1]) #because the code lists the fibonacci number one past x. Not necessary, but defines the code better for i in range(0, len(List)): print List[i] #prints it in series form instead of list form. Also not necessary </code></pre>
3
2014-02-02T04:59:00Z
[ "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
21,607,318
<p>Canonical Python code to print Fibonacci sequence:</p> <pre><code>a,b=1,1 while(True): print a, a,b=b,a+b # Could also use b=a+b;a=b-a </code></pre> <p>For the problem "Print the first Fibonacci number greater than 1000 digits long":</p> <pre><code>a,b=1,1 i=1 while(len(str(a))&lt;=1000): i=i+1 a,b=b,a+b print i,len(str(a)),a </code></pre>
3
2014-02-06T15:39:57Z
[ "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
21,620,473
<p>Another way of doing it:</p> <pre><code>a,n=[0,1],10 map(lambda i: reduce(lambda x,y: a.append(x+y),a[-2:]),range(n-2)) </code></pre> <p>Assigning list to 'a', assigning integer to 'n' Map and reduce are 2 of three most powerful functions in python. Here map is used just to iterate 'n-2' times. a[-2:] will get the last two elements of an array. a.append(x+y) will add the last two elements and will append to the array</p>
0
2014-02-07T06:05:27Z
[ "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
21,704,751
<p>Why not just simply do the following?</p> <pre><code>x = [1,1] for i in xrange(10): x.append(x[-1] + x[-2]) print ', '.join(str(y) for y in x) </code></pre>
5
2014-02-11T14:34:53Z
[ "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
22,258,711
<p>Maybe this will help</p> <pre><code>def fibo(n): result = [] a, b = 0, 1 while b &lt; n: result.append(b) a, b = b, b + a return result </code></pre>
0
2014-03-07T19:11:55Z
[ "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
24,846,766
<h1>Efficient Pythonic generator of the Fibonacci sequence</h1> <p>I found this question while trying to get the shortest Pythonic generation of this sequence (later realizing I had seen a similar one in a <a href="https://www.python.org/dev/peps/pep-0255/">Python Enhancement Proposal</a>), and I haven't noticed anyone else coming up with my specific solution (although the top answer gets close, but still less elegant), so here it is, with comments describing the first iteration, because I think that may help readers understand:</p> <pre><code>def fib(): a, b = 0, 1 while True: # First iteration: yield a # yield 0 to start with and then a, b = b, a + b # a will now be 1, and b will also be 1, (0 + 1) </code></pre> <p>and usage:</p> <pre><code>for index, fibonacci_number in enumerate(fib()): print('{i:3}: {f:3}'.format(i=index, f=fibonacci_number)) if index == 10: break </code></pre> <p>prints:</p> <pre><code> 0: 0 1: 1 2: 1 3: 2 4: 3 5: 5 6: 8 7: 13 8: 21 9: 34 10: 55 </code></pre> <p>(For attribution purposes, I recently noticed a <a href="https://docs.python.org/2/tutorial/modules.html">similar implementation</a> in the Python documentation on modules, even using the variables <code>a</code> and <code>b</code>, which I now recall having seen before writing this answer. But I think this answer demonstrates better usage of the language.)</p> <h1>Recursively defined implementation</h1> <p>The <a href="http://oeis.org/A000045">Online Encyclopedia of Integer Sequences</a> defines the Fibonacci Sequence recursively as </p> <blockquote> <p>F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1</p> </blockquote> <p>Succinctly defining this recursively in Python can be done as follows:</p> <pre><code>def rec_fib(n): '''inefficient recursive function as defined, returns Fibonacci number''' if n &gt; 1: return rec_fib(n-1) + rec_fib(n-2) return n </code></pre> <p>But this exact representation of the mathematical definition is incredibly inefficient for numbers much greater than 30, because each number being calculated must also calculate for every number below it. You can demonstrate how slow it is by using the following:</p> <pre><code>for i in range(40): print i, rec_fib(i) </code></pre> <h1>Memoized recursion for efficiency</h1> <p>It can be memoized to improve speed (this example takes advantage of the fact that a default keyword argument is the same object every time the function is called, but normally you wouldn't use a mutable default argument for exactly this reason):</p> <pre><code>def mem_fib(n, _cache={}): '''efficiently memoized recursive function, returns a Fibonacci number''' if n in _cache: return _cache[n] elif n &gt; 1: return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2)) return n </code></pre> <p>You'll find the memoized version is much faster, and will quickly exceed your maximum recursion depth before you can even think to get up for coffee. You can see how much faster it is visually by doing this:</p> <pre><code>for i in range(40): print i, mem_fib(i) </code></pre> <p>(It may seem like we can just do the below, but it actually doesn't let us take advantage of the cache, because it calls itself before setdefault is called.)</p> <pre><code>def mem_fib(n, _cache={}): '''don't do this''' if n &gt; 1: return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2)) return n </code></pre>
24
2014-07-20T02:24:24Z
[ "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
26,118,289
<p><strong>Time complexity :</strong> </p> <p>The caching feature reduces the normal way of calculating Fibonacci series from <strong>O(2^n)</strong> to <strong>O(n)</strong> by eliminating the repeats in the recursive tree of Fibonacci series :</p> <p><img src="http://i.stack.imgur.com/59Rpw.png" alt="enter image description here"></p> <p><strong>Code :</strong> </p> <pre><code>import sys table = [0]*1000 def FastFib(n): if n&lt;=1: return n else: if(table[n-1]==0): table[n-1] = FastFib(n-1) if(table[n-2]==0): table[n-2] = FastFib(n-2) table[n] = table[n-1] + table[n-2] return table[n] def main(): print('Enter a number : ') num = int(sys.stdin.readline()) print(FastFib(num)) if __name__=='__main__': main() </code></pre>
7
2014-09-30T10:14:59Z
[ "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
27,343,852
<p>Try this:</p> <pre><code>def nth_fib(n): if n == 0: return 1 elif n == 1: return 0 else: return nth_fib(n - 1) + nth_fib(n - 2) </code></pre>
0
2014-12-07T14:50:01Z
[ "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
28,461,205
<p>based on classic fibonacci sequence and just for the sake of the one-liners</p> <p>if you just need the number of the index, you can use the reduce (even if <em>reduce</em> it's not best suited for this it can be a good exercise)</p> <pre><code>def fibonacci(index): return reduce(lambda r,v: r.append(r[-1]+r[-2]) or (r.pop(0) and 0) or r , xrange(index), [0, 1])[1] </code></pre> <p>and to get the complete array just remove the <em>or (r.pop(0) and 0)</em></p> <pre><code>reduce(lambda r,v: r.append(r[-1]+r[-2]) or r , xrange(last_index), [0, 1]) </code></pre>
0
2015-02-11T18:01:18Z
[ "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
28,659,265
<p>How about this one? I guess it's not as fancy as the other suggestions because it demands the initial specification of the previous result to produce the expected output, but I feel is a very readable option, i.e., all it does is to provide the result and the previous result to the recursion.</p> <pre><code>#count the number of recursions num_rec = 0 def fibonacci(num, prev, num_rec, cycles): num_rec = num_rec + 1 if num == 0 and prev == 0: result = 0; num = 1; else: result = num + prev print(result) if num_rec == cycles: print("done") else: fibonacci(result, num, num_rec, cycles) #Run the fibonacci function 10 times fibonacci(0, 0, num_rec, 10) </code></pre> <p>Here's the output:</p> <pre><code>0 1 1 2 3 5 8 13 21 34 done </code></pre>
0
2015-02-22T14:58:04Z
[ "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
33,292,276
<p>Basically translated from Ruby:</p> <pre><code>def fib(n): a = 0 b = 1 for i in range(1,n+1): c = a + b print c a = b b = c </code></pre> <p>... </p>
1
2015-10-22T23:09:13Z
[ "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
33,459,246
<p>OK.. after being tired of referring all lengthy answers, now find the below sort &amp; sweet, pretty straight forward way for implementing Fibonacci in python. You can enhance it it the way you want by getting an argument or getting user input…or change the limits from 10000. As you need……</p> <pre><code>def fibonacci(): start = 0 i = 1 lt = [] lt.append(start) while start &lt; 10000: start += i lt.append(start) i = sum(lt[-2:]) lt.append(i) print "The Fibonaccii series: ", lt </code></pre> <p>This approach also performs good. Find the run analytics below</p> <pre><code>In [10]: %timeit fibonacci 10000000 loops, best of 3: 26.3 ns per loop </code></pre>
1
2015-11-01T04:35: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
33,679,701
<pre><code>def fib(lowerbound, upperbound): x = 0 y = 1 while x &lt;= upperbound: if (x &gt;= lowerbound): yield x x, y = y, x + y startNumber = 10 endNumber = 100 for fib_sequence in fib(startNumber, endNumber): print "And the next number is... %d!" % fib_sequence </code></pre>
1
2015-11-12T19:29:58Z
[ "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
34,328,275
<p>A more detailed explanation of how Memoization works for Fibonacci sequence.</p> <pre><code># Fibonacci sequence Memoization fib_cache = {0:0, 1:1} def fibonacci(n): if n &lt; 0: return -1 if fib_cache.has_key(n): print "Fibonacci sequence for %d = %d cached" % (n, fib_cache[n]) return fib_cache[n] else: fib_cache[n] = fibonacci(n - 1) + fibonacci(n - 2) return fib_cache[n] if __name__ == "__main__": print fibonacci(6) print fib_cache # fibonacci(7) reuses fibonacci(6) and fibonacci(5) print fibonacci(7) print fib_cache </code></pre>
0
2015-12-17T06:47:27Z
[ "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
34,541,746
<p>I was trying to avoid a recursive function to solve this problem, so I took an iterative approach. I was originally doing a memoized recursive function but kept hitting max recursive depth. I also had strict memory goals so you will see me keeping the array as small as I can during the looping process only keeping 2-3 values in the array at any time.</p> <pre><code>def fib(n): fibs = [1, 1] # my starting array for f in range(2, n): fibs.append(fibs[-1] + fibs[-2]) # appending the new fib number del fibs[0] # removing the oldest number return fibs[-1] # returning the newest fib print(fib(6000000)) </code></pre> <p>Getting the 6 millionth fibonacci number takes about 282 seconds on my machine while the 600k fibonacci takes only 2.8 seconds. I was unable to obtain such large fibonacci numbers with a recursive function, even a memoized one. </p>
0
2015-12-31T05:51:31Z
[ "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
35,983,856
<p>Fibonacci sequence is: <code>1, 1, 2, 3, 5, 8, ...</code>.</p> <p>That is <code>f(1) = 1</code>, <code>f(2) = 1</code>, <code>f(3) = 2</code>, <code>...</code>, <code>f(n) = f(n-1) + f(n-2)</code>. </p> <p>My favorite implementation (simplest and yet achieves a light speed in compare to other implementations) is this:</p> <pre><code>def fibonacci(n): a, b = 0, 1 for _ in range(1, n): a, b = b, a + b return b </code></pre> <p><strong>Test</strong></p> <pre><code>&gt;&gt;&gt; [fibonacci(i) for i in range(1, 10)] [1, 1, 2, 3, 5, 8, 13, 21, 34] </code></pre> <p><strong>Timing</strong></p> <pre><code>&gt;&gt;&gt; %%time &gt;&gt;&gt; fibonacci(100**3) CPU times: user 9.65 s, sys: 9.44 ms, total: 9.66 s Wall time: 9.66 s </code></pre> <p>Edit: <a href="http://www.pythontutor.com/visualize.html#code=def+fibonacci(n%29%3A%0A++++a,+b+%3D+0,+1%0A++++for+_+in+range(1,+n%29%3A%0A++++++++a,+b+%3D+b,+a+%2B+b%0A++++return+b%0A++++%0Afibonacci(10%29&amp;mode=display&amp;origin=opt-frontend.js&amp;cumulative=false&amp;heapPrimitives=false&amp;textReferences=false&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;curInstr=0" rel="nofollow">an example visualization</a> for this implementations. </p>
0
2016-03-14T09:33:26Z
[ "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
37,585,674
<p>This is quite efficient, using O(log n) basic arithmetic operations.</p> <pre><code>def fib(n): return pow(2 &lt;&lt; n, n + 1, (4 &lt;&lt; 2*n) - (2 &lt;&lt; n) - 1) % (2 &lt;&lt; n) </code></pre> <p>This one uses O(1) basic arithmetic operations, but the size of the intermediate results is large and so is not at all efficient.</p> <pre><code>def fib(n): return (4 &lt;&lt; n*(3+n)) // ((4 &lt;&lt; 2*n) - (2 &lt;&lt; n) - 1) &amp; ((2 &lt;&lt; n) - 1) </code></pre> <p>This one computes X^n in the polynomial ring Z[X] / (X^2 - X - 1) using exponentiation by squaring. The result of that calculation is the polynomial Fib(n)X + Fib(n-1), from which the nth Fibonacci number can be read.</p> <p>Again, this uses O(log n) arithmetic operations and is very efficient.</p> <pre><code>def mul(a, b): return a[0]*b[1]+a[1]*b[0]+a[0]*b[0], a[0]*b[0]+a[1]*b[1] def fib(n): x, r = (1, 0), (0, 1) while n: if n &amp; 1: r = mul(r, x) x = mul(x, x) n &gt;&gt;= 1 return r[0] </code></pre>
0
2016-06-02T07:47:03Z
[ "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
38,985,626
<p>I made a slightly interactive python Fibonacci Sequence, it asks how many times you want it to repeat, then it shows you the numbers of the Fibonacci Sequence. <strong><em>HERE IS THE CODE</em></strong>!!!</p> <pre><code> while True: number_1 = 1 number_2 = 1 how_many_times_do_you_want_this_done = input('How Many Times Do You Want This Done: ') counter = 1 while counter &lt; how_many_times_do_you_want_this_done: print([number_1]) print([number_2]) number_1 += number_2 number_2 += number_1 counter += 2 </code></pre>
0
2016-08-16T22:47:45Z
[ "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
39,214,599
<p>Recursion adds time. To eliminate loops, first <code>import math</code>. Then use <code>math.sqrt</code> and golden ratio in a function:</p> <pre><code>#!/usr/bin/env python3 import math def fib(n): gr = (1 + math.sqrt(5)) / 2 fib_first = (gr**n - (1 - gr)**n) / math.sqrt(5) return int(round(fib_first)) fib_final = fib(100) print(fib_final) </code></pre> <p>ref: <a href="http://mortada.net/fibonacci-numbers-in-python.html" rel="nofollow">Fibonacci Numbers in Python</a></p>
0
2016-08-29T20:23:11Z
[ "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
39,277,476
<p>this is an improvement to mathew henry's answer:</p> <pre><code>def fib(n): a = 0 b = 1 for i in range(1,n+1): c = a + b print b a = b b = c </code></pre> <p>the code should print b instead of printing c</p> <p>output: 1,1,2,3,5 ....</p>
1
2016-09-01T17:21:27Z
[ "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
39,613,079
<p><strong>there is a very easy method to realize taht!</strong> </p> <p>you can this code online freely by using <a href="http://www.learnpython.org/" rel="nofollow">http://www.learnpython.org/</a></p> <pre><code># Set the variable brian on line 3! def fib(n): """This is documentation string for function. It'll be available by fib.__doc__() Return a list containing the Fibonacci series up to n.""" result = [] a = 0 b = 1 while a &lt; n: result.append(a) # 0 1 1 2 3 5 8 (13) break tmp_var = b # 1 1 2 3 5 8 13 b = a + b # 1 2 3 5 8 13 21 a = tmp_var # 1 1 2 3 5 8 13 # print(a) return result print(fib(10)) # result should be this: [0, 1, 1, 2, 3, 5, 8] </code></pre>
0
2016-09-21T09:48:48Z
[ "python", "fibonacci", "sequences" ]
Create a cross-platform protocol helper that runs a python script
494,769
<p>I'd like to register a protocol handler, like "myapp:", across OS X, Linux, and Windows, so that when someone clicks a url like "myapp://some/params" in a web browser, a python script will be called and passed in those params.</p> <p>Obviously this would require something being installed on each machine to enable it, but just trying to figure out a way to make it work on all three platforms.</p>
6
2009-01-30T07:16:22Z
495,470
<p>Are you talking about a browser plug-in? If so, which browsers? </p> <p>Firefox? https://addons.mozilla.org/en-US/firefox/addon/6710</p> <p>Epiphany? <a href="http://pyconuk.org/talk_abstracts.html" rel="nofollow">http://pyconuk.org/talk_abstracts.html</a> has a reference to extending Epiphany with Python.</p> <p>Apparently, Microsoft is considering IronPython as an extension to IE. See <a href="http://ironpython-urls.blogspot.com/2008/06/try-python-python-in-browser-with.html" rel="nofollow">http://ironpython-urls.blogspot.com/2008/06/try-python-python-in-browser-with.html</a></p>
0
2009-01-30T13:20:41Z
[ "python", "url", "cross-platform" ]
refactor this dictionary-to-xml converter in python
494,881
<p>It's a small thing, really: I have this function that converts dict objects to xml.</p> <p>Here's the function:</p> <pre><code>def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for name, value in node.iteritems(): if isinstance(value, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(value, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) elif isinstance(value, list): for item in value: if isinstance(item, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(item, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(item)), name)) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(value)), name)) addDict(d, u"") lines.append(u"") return u"\n".join(lines) </code></pre> <p>For example, it converts this dictionary</p> <pre><code>{ 'site': { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } } </code></pre> <p>to:</p> <pre><code>&lt;site&gt; &lt;name&gt;stackoverflow&lt;/name&gt; &lt;blogger&gt;jeff&lt;/blogger&gt; &lt;blogger&gt;joel&lt;/blogger&gt; &lt;/site&gt; </code></pre> <p>It works, but the <code>addDict</code> function looks a little too repetitive. I'm sure there's a way to refactor it into 3 co-recursive functions named <code>addDict</code>, <code>addList</code> and <code>addElse</code>, but my brain is stuck. Any help?</p> <p>Also, any way to get rid of the <code>offset +</code> thing in every line would be nice.</p> <p><strong>NOTE</strong>: I chose these semantics because I'm trying to match the behavior of the <a href="http://www.json.org/javadoc/org/json/XML.html#toString(java.lang.Object)" rel="nofollow">json-to-xml converter</a> in <a href="http://www.json.org/java/index.html" rel="nofollow">org.json</a>, which I use in a different part of my project. If you got to this page just looking for a dictionary to xml converter, there are some <a href="#494905" rel="nofollow">really</a> good <a href="#495512" rel="nofollow">options</a> in some of the answers. (Especially <a href="http://foss.cpcc.edu/pyfo/" rel="nofollow">pyfo</a>).</p>
3
2009-01-30T08:33:12Z
494,890
<p>Here is my short sketch for a solution: have a general <code>addSomething()</code> function that dispatches based on the type of the value to <code>addDict()</code>, <code>addList()</code> or <code>addElse()</code>. Those functions recursively call <code>addSomething()</code> again.</p> <p>Basically you are factoring out the parts in the <code>if</code> clause and add a recursive call.</p>
0
2009-01-30T08:43:22Z
[ "python", "xml", "dry" ]
refactor this dictionary-to-xml converter in python
494,881
<p>It's a small thing, really: I have this function that converts dict objects to xml.</p> <p>Here's the function:</p> <pre><code>def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for name, value in node.iteritems(): if isinstance(value, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(value, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) elif isinstance(value, list): for item in value: if isinstance(item, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(item, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(item)), name)) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(value)), name)) addDict(d, u"") lines.append(u"") return u"\n".join(lines) </code></pre> <p>For example, it converts this dictionary</p> <pre><code>{ 'site': { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } } </code></pre> <p>to:</p> <pre><code>&lt;site&gt; &lt;name&gt;stackoverflow&lt;/name&gt; &lt;blogger&gt;jeff&lt;/blogger&gt; &lt;blogger&gt;joel&lt;/blogger&gt; &lt;/site&gt; </code></pre> <p>It works, but the <code>addDict</code> function looks a little too repetitive. I'm sure there's a way to refactor it into 3 co-recursive functions named <code>addDict</code>, <code>addList</code> and <code>addElse</code>, but my brain is stuck. Any help?</p> <p>Also, any way to get rid of the <code>offset +</code> thing in every line would be nice.</p> <p><strong>NOTE</strong>: I chose these semantics because I'm trying to match the behavior of the <a href="http://www.json.org/javadoc/org/json/XML.html#toString(java.lang.Object)" rel="nofollow">json-to-xml converter</a> in <a href="http://www.json.org/java/index.html" rel="nofollow">org.json</a>, which I use in a different part of my project. If you got to this page just looking for a dictionary to xml converter, there are some <a href="#494905" rel="nofollow">really</a> good <a href="#495512" rel="nofollow">options</a> in some of the answers. (Especially <a href="http://foss.cpcc.edu/pyfo/" rel="nofollow">pyfo</a>).</p>
3
2009-01-30T08:33:12Z
494,897
<p>I noticed you have commonality in adding items. Using this commonality I would refactor adding an item to a separate function.</p> <pre><code>def addItem(item, name, offset): if isinstance(item, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(item, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(item)), name)) def addList(value,name, offset): for item in value: addItem(item, name, offset) def addDict(node, offset): for name, value in node.iteritems(): if isinstance(value, list): addList(value, name, offset) else: addItem(value, name, offset) </code></pre> <p>Advisory warning: this code is not tested or written by anybody who actually uses Python.</p>
4
2009-01-30T08:48:38Z
[ "python", "xml", "dry" ]
refactor this dictionary-to-xml converter in python
494,881
<p>It's a small thing, really: I have this function that converts dict objects to xml.</p> <p>Here's the function:</p> <pre><code>def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for name, value in node.iteritems(): if isinstance(value, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(value, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) elif isinstance(value, list): for item in value: if isinstance(item, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(item, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(item)), name)) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(value)), name)) addDict(d, u"") lines.append(u"") return u"\n".join(lines) </code></pre> <p>For example, it converts this dictionary</p> <pre><code>{ 'site': { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } } </code></pre> <p>to:</p> <pre><code>&lt;site&gt; &lt;name&gt;stackoverflow&lt;/name&gt; &lt;blogger&gt;jeff&lt;/blogger&gt; &lt;blogger&gt;joel&lt;/blogger&gt; &lt;/site&gt; </code></pre> <p>It works, but the <code>addDict</code> function looks a little too repetitive. I'm sure there's a way to refactor it into 3 co-recursive functions named <code>addDict</code>, <code>addList</code> and <code>addElse</code>, but my brain is stuck. Any help?</p> <p>Also, any way to get rid of the <code>offset +</code> thing in every line would be nice.</p> <p><strong>NOTE</strong>: I chose these semantics because I'm trying to match the behavior of the <a href="http://www.json.org/javadoc/org/json/XML.html#toString(java.lang.Object)" rel="nofollow">json-to-xml converter</a> in <a href="http://www.json.org/java/index.html" rel="nofollow">org.json</a>, which I use in a different part of my project. If you got to this page just looking for a dictionary to xml converter, there are some <a href="#494905" rel="nofollow">really</a> good <a href="#495512" rel="nofollow">options</a> in some of the answers. (Especially <a href="http://foss.cpcc.edu/pyfo/" rel="nofollow">pyfo</a>).</p>
3
2009-01-30T08:33:12Z
494,905
<pre><code>&gt;&gt;&gt; from pyfo import pyfo &gt;&gt;&gt; d = ('site', { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } ) &gt;&gt;&gt; result = pyfo(d, pretty=True, prolog=True, encoding='ascii') &gt;&gt;&gt; print result.encode('ascii', 'xmlcharrefreplace') &lt;?xml version="1.0" encoding="ascii"?&gt; &lt;site&gt; &lt;blogger&gt; Jeff Joel &lt;/blogger&gt; &lt;name&gt;stackoverflow&lt;/name&gt; &lt;/site&gt; </code></pre> <p>To install <a href="http://foss.cpcc.edu/pyfo/" rel="nofollow">pyfo</a>:</p> <pre><code>$ easy_install pyfo </code></pre>
9
2009-01-30T08:52:10Z
[ "python", "xml", "dry" ]
refactor this dictionary-to-xml converter in python
494,881
<p>It's a small thing, really: I have this function that converts dict objects to xml.</p> <p>Here's the function:</p> <pre><code>def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for name, value in node.iteritems(): if isinstance(value, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(value, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) elif isinstance(value, list): for item in value: if isinstance(item, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(item, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(item)), name)) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(value)), name)) addDict(d, u"") lines.append(u"") return u"\n".join(lines) </code></pre> <p>For example, it converts this dictionary</p> <pre><code>{ 'site': { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } } </code></pre> <p>to:</p> <pre><code>&lt;site&gt; &lt;name&gt;stackoverflow&lt;/name&gt; &lt;blogger&gt;jeff&lt;/blogger&gt; &lt;blogger&gt;joel&lt;/blogger&gt; &lt;/site&gt; </code></pre> <p>It works, but the <code>addDict</code> function looks a little too repetitive. I'm sure there's a way to refactor it into 3 co-recursive functions named <code>addDict</code>, <code>addList</code> and <code>addElse</code>, but my brain is stuck. Any help?</p> <p>Also, any way to get rid of the <code>offset +</code> thing in every line would be nice.</p> <p><strong>NOTE</strong>: I chose these semantics because I'm trying to match the behavior of the <a href="http://www.json.org/javadoc/org/json/XML.html#toString(java.lang.Object)" rel="nofollow">json-to-xml converter</a> in <a href="http://www.json.org/java/index.html" rel="nofollow">org.json</a>, which I use in a different part of my project. If you got to this page just looking for a dictionary to xml converter, there are some <a href="#494905" rel="nofollow">really</a> good <a href="#495512" rel="nofollow">options</a> in some of the answers. (Especially <a href="http://foss.cpcc.edu/pyfo/" rel="nofollow">pyfo</a>).</p>
3
2009-01-30T08:33:12Z
494,924
<p>To get rid of repeated "offset+":</p> <pre><code>offset = 0 def addLine(str): lines.append(u" " * (offset * 4) + str </code></pre> <p>then</p> <pre><code>... addLine(u"&lt;%s&gt;" % name) offset = offset + 1 addDict(value) offset = offset - 1 addLine(u"&lt;/%s&gt;" % name) </code></pre> <p>Don't have access to an interpreter here, so take this with a grain of salt :(</p>
1
2009-01-30T09:13:22Z
[ "python", "xml", "dry" ]
refactor this dictionary-to-xml converter in python
494,881
<p>It's a small thing, really: I have this function that converts dict objects to xml.</p> <p>Here's the function:</p> <pre><code>def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for name, value in node.iteritems(): if isinstance(value, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(value, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) elif isinstance(value, list): for item in value: if isinstance(item, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(item, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(item)), name)) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(value)), name)) addDict(d, u"") lines.append(u"") return u"\n".join(lines) </code></pre> <p>For example, it converts this dictionary</p> <pre><code>{ 'site': { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } } </code></pre> <p>to:</p> <pre><code>&lt;site&gt; &lt;name&gt;stackoverflow&lt;/name&gt; &lt;blogger&gt;jeff&lt;/blogger&gt; &lt;blogger&gt;joel&lt;/blogger&gt; &lt;/site&gt; </code></pre> <p>It works, but the <code>addDict</code> function looks a little too repetitive. I'm sure there's a way to refactor it into 3 co-recursive functions named <code>addDict</code>, <code>addList</code> and <code>addElse</code>, but my brain is stuck. Any help?</p> <p>Also, any way to get rid of the <code>offset +</code> thing in every line would be nice.</p> <p><strong>NOTE</strong>: I chose these semantics because I'm trying to match the behavior of the <a href="http://www.json.org/javadoc/org/json/XML.html#toString(java.lang.Object)" rel="nofollow">json-to-xml converter</a> in <a href="http://www.json.org/java/index.html" rel="nofollow">org.json</a>, which I use in a different part of my project. If you got to this page just looking for a dictionary to xml converter, there are some <a href="#494905" rel="nofollow">really</a> good <a href="#495512" rel="nofollow">options</a> in some of the answers. (Especially <a href="http://foss.cpcc.edu/pyfo/" rel="nofollow">pyfo</a>).</p>
3
2009-01-30T08:33:12Z
495,295
<p>Here's what I find helpful when working with XML. Actually create the XML node structure first, then render this into text second.</p> <p>This separates two unrelated concerns.</p> <ol> <li><p>How do I transform my Python structure into an XML object model?</p></li> <li><p>How to I format that XML object model?</p></li> </ol> <p>It's hard when you put these two things together into one function. If, on the other hand, you separate them, then you have two things. First, you have a considerably simpler function to "walk" your Python structure and return an XML node. Your XML Nodes can be rendered into text with some preferred encoding and formatting rules applied.</p> <pre><code>from xml.sax.saxutils import escape class Node( object ): def __init__( self, name, *children ): self.name= name self.children= children def toXml( self, indent ): if len(self.children) == 0: return u"%s&lt;%s/&gt;" % ( indent*4*u' ', self.name ) elif len(self.children) == 1: child= self.children[0].toXml(0) return u"%s&lt;%s&gt;%s&lt;/%s&gt;" % ( indent*4*u' ', self.name, child, self.name ) else: items = [ u"%s&lt;%s&gt;" % ( indent*4*u' ', self.name ) ] items.extend( [ c.toXml(indent+1) for c in self.children ] ) items.append( u"%s&lt;/%s&gt;" % ( indent*4*u' ', self.name ) ) return u"\n".join( items ) class Text( Node ): def __init__( self, value ): self.value= value def toXml( self, indent ): def unicodify(o): if o is None: return u''; return unicode(o) return "%s%s" % ( indent*4*u' ', escape( unicodify(self.value) ), ) def dictToXml(d): def dictToNodeList(node): nodes= [] for name, value in node.iteritems(): if isinstance(value, dict): n= Node( name, *dictToNodeList( value ) ) nodes.append( n ) elif isinstance(value, list): for item in value: if isinstance(item, dict): n= Node( name, *dictToNodeList( value ) ) nodes.append( n ) else: n= Node( name, Text( item ) ) nodes.append( n ) else: n= Node( name, Text( value ) ) nodes.append( n ) return nodes return u"\n".join( [ n.toXml(0) for n in dictToNodeList(d) ] ) </code></pre>
0
2009-01-30T12:02:40Z
[ "python", "xml", "dry" ]
refactor this dictionary-to-xml converter in python
494,881
<p>It's a small thing, really: I have this function that converts dict objects to xml.</p> <p>Here's the function:</p> <pre><code>def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for name, value in node.iteritems(): if isinstance(value, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(value, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) elif isinstance(value, list): for item in value: if isinstance(item, dict): lines.append(offset + u"&lt;%s&gt;" % name) addDict(item, offset + u" " * 4) lines.append(offset + u"&lt;/%s&gt;" % name) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(item)), name)) else: lines.append(offset + u"&lt;%s&gt;%s&lt;/%s&gt;" % (name, escape(unicodify(value)), name)) addDict(d, u"") lines.append(u"") return u"\n".join(lines) </code></pre> <p>For example, it converts this dictionary</p> <pre><code>{ 'site': { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } } </code></pre> <p>to:</p> <pre><code>&lt;site&gt; &lt;name&gt;stackoverflow&lt;/name&gt; &lt;blogger&gt;jeff&lt;/blogger&gt; &lt;blogger&gt;joel&lt;/blogger&gt; &lt;/site&gt; </code></pre> <p>It works, but the <code>addDict</code> function looks a little too repetitive. I'm sure there's a way to refactor it into 3 co-recursive functions named <code>addDict</code>, <code>addList</code> and <code>addElse</code>, but my brain is stuck. Any help?</p> <p>Also, any way to get rid of the <code>offset +</code> thing in every line would be nice.</p> <p><strong>NOTE</strong>: I chose these semantics because I'm trying to match the behavior of the <a href="http://www.json.org/javadoc/org/json/XML.html#toString(java.lang.Object)" rel="nofollow">json-to-xml converter</a> in <a href="http://www.json.org/java/index.html" rel="nofollow">org.json</a>, which I use in a different part of my project. If you got to this page just looking for a dictionary to xml converter, there are some <a href="#494905" rel="nofollow">really</a> good <a href="#495512" rel="nofollow">options</a> in some of the answers. (Especially <a href="http://foss.cpcc.edu/pyfo/" rel="nofollow">pyfo</a>).</p>
3
2009-01-30T08:33:12Z
495,512
<p>Your original code produce malformed XML and can produce the same XML for two different dictionaries (is not <em>injective</em>, speaking mathematically).</p> <p>For example, if you have a list as a value of the only key in a dictionary:</p> <pre><code> d = { 'list': [1,2,3] } </code></pre> <p>I expect that your code would produce</p> <pre><code> &lt;list&gt;1&lt;/list&gt;&lt;list&gt;2&lt;/list&gt;&lt;list&gt;3&lt;/list&gt; </code></pre> <p>and there is no root element. Any XML should have one and only one root element.</p> <p>Then given the XML produced by your code, it is impossible to say if this XML</p> <pre><code> &lt;tag&gt;1&lt;/tag&gt; </code></pre> <p>was produced from <code>{ 'tag': 1 }</code> or from <code>{ 'tag': [1] } </code>.</p> <p>So, I suggest</p> <ul> <li>always start from the root element</li> <li>represent lists with either two special tags (e.g. <code>&lt;list/&gt;</code> and <code>&lt;item/&gt;</code>) or mark them as such in attributes</li> </ul> <p>Then, after decisions about these <em>conceptual</em> shortcomings we can generate correct and unambiguous XML. I chose to use attributes to markup lists, and used ElementTree to construct the XML tree automatically. Also, recursion helps (<code>add_value_to_xml</code> is called recursively):</p> <pre><code>from xml.etree.ElementTree import Element, SubElement, tostring def is_scalar(v): return isinstance(v,basestring) or isinstance(v,float) \ or isinstance(v,int) or isinstance(v,bool) def add_value_to_xml(root,v): if type(v) == type({}): for k,kv in v.iteritems(): vx = SubElement(root,unicode(k)) vx = add_value_to_xml(vx,kv) elif type(v) == list: root.set('type','list') for e in v: li = SubElement(root,root.tag) li = add_value_to_xml(li,e) li.set('type','item') elif is_scalar(v): root.text = unicode(v) else: raise Exception("add_value_to_xml: unsuppoted type (%s)"%type(v)) return root def dict_to_xml(d,root='dict'): x = Element(root) x = add_value_to_xml(x,d) return x d = { 'float': 5194.177, 'str': 'eggs', 'int': 42, 'list': [1,2], 'dict': { 'recursion': True } } x = dict_to_xml(d) print tostring(x) </code></pre> <p>The result of the conversion of the test dict is:</p> <pre><code>&lt;dict&gt;&lt;int&gt;42&lt;/int&gt;&lt;dict&gt;&lt;recursion&gt;True&lt;/recursion&gt;&lt;/dict&gt;&lt;float&gt;5194.177&lt;/float&gt;&lt;list type="list"&gt;&lt;list type="item"&gt;1&lt;/list&gt;&lt;list type="item"&gt;2&lt;/list&gt;&lt;/list&gt;&lt;str&gt;eggs&lt;/str&gt;&lt;/dict&gt; </code></pre>
1
2009-01-30T13:40:01Z
[ "python", "xml", "dry" ]
File and space in Python
494,919
<p>I have a file like:</p> <pre><code>&lt;space&gt; &lt;space&gt; line1 &lt;space&gt; column 1 column 2 column 3 ... . . . &lt;space&gt; &lt;space&gt; </code></pre> <p>How to remove this extra spaces?</p> <p>I need to extract the heading which will be on <code>line1</code>. Also, I need to extract <code>column 1</code>, <code>column 2</code>, <code>column 3</code> etc.</p> <p>At the end of last column content there is '\n'.How to get rid of it ???</p> <p>Help me with this...</p> <p>Thank you</p>
-2
2009-01-30T09:10:03Z
494,935
<p>Start by opening the file and reading all the lines:</p> <pre><code>f = open('filename string'); lines = f.readlines() </code></pre> <p>Then...</p> <pre><code># remove empty lines lines = [l for l in lines if len(l.strip()) &gt; 0] header = lines[0] line = lines[1].split(' ') column1 = line[0] column2 = line[1] ... </code></pre> <p>Also:</p> <pre><code>total_lines = len(lines) total_columns = len(line) </code></pre>
4
2009-01-30T09:18:37Z
[ "python", "file", "parsing", "spaces" ]
File and space in Python
494,919
<p>I have a file like:</p> <pre><code>&lt;space&gt; &lt;space&gt; line1 &lt;space&gt; column 1 column 2 column 3 ... . . . &lt;space&gt; &lt;space&gt; </code></pre> <p>How to remove this extra spaces?</p> <p>I need to extract the heading which will be on <code>line1</code>. Also, I need to extract <code>column 1</code>, <code>column 2</code>, <code>column 3</code> etc.</p> <p>At the end of last column content there is '\n'.How to get rid of it ???</p> <p>Help me with this...</p> <p>Thank you</p>
-2
2009-01-30T09:10:03Z
494,977
<p>A straightforward solution, using <a href="http://docs.python.org/library/stdtypes.html#str.strip" rel="nofollow"><code>strip()</code></a> to drop spaces and <a href="http://docs.python.org/library/stdtypes.html#str.split" rel="nofollow"><code>split()</code></a> to separate column data:</p> <pre><code>&gt;&gt;&gt; mylines [' \n', ' \n', 'line1\n', ' \n', ' \n', 'column1 column2 column3 \n'] &gt;&gt;&gt; def parser(lines): ... header="" ... data=[] ... for x in lines: ... line = x.strip() ... if line == "": ... continue ... if header == "": ... header=line ... else: ... data.append(line.split()) ... return {"header":header,"data":data} ... &gt;&gt;&gt; parser(mylines) {'header': 'line1', 'data': [['column1', 'column2', 'column3']]} &gt;&gt;&gt; </code></pre>
1
2009-01-30T09:43:12Z
[ "python", "file", "parsing", "spaces" ]
File and space in Python
494,919
<p>I have a file like:</p> <pre><code>&lt;space&gt; &lt;space&gt; line1 &lt;space&gt; column 1 column 2 column 3 ... . . . &lt;space&gt; &lt;space&gt; </code></pre> <p>How to remove this extra spaces?</p> <p>I need to extract the heading which will be on <code>line1</code>. Also, I need to extract <code>column 1</code>, <code>column 2</code>, <code>column 3</code> etc.</p> <p>At the end of last column content there is '\n'.How to get rid of it ???</p> <p>Help me with this...</p> <p>Thank you</p>
-2
2009-01-30T09:10:03Z
495,193
<p>Using Generator functions to handle each element of parsing</p> <pre><code>def nonEmptyLines( aFile ): """Discard empty lines, yield only non-empty lines.""" for line in aFile: if len(line) &gt; 0: yield line def splitFields( aFile ): """Split a non-empty line into fields.""" for line in nonEmptyLines(aFile): yield line.split() def dictReader( aFile ): """Turn non-empty lines file with header and data into dictionaries. Like the ``csv`` module.""" iter= iter( splitFields( aFile ) ) heading= iter.next() for line in iter: yield dict( zip( heading, line ) ) rdr= dictReader( "myFile", "r" ) for d in rdr: print d </code></pre>
0
2009-01-30T11:17:36Z
[ "python", "file", "parsing", "spaces" ]
HOWTO: XML-RPC dynamic function registration in python?
494,997
<p>I am new to XML-RPC.</p> <pre><code>#client code import xmlrpclib proxy = xmlrpclib.ServerProxy("http://localhost:8000/") x,y = arg1,arg2 print proxy.fun1(x,y) print proxy.fun2(x,y) </code></pre> <p>What server should do:</p> <ol> <li>load fun1</li> <li>register fun1</li> <li>return result</li> <li>unload fun1</li> </ol> <p>and then do same with fun2.</p> <p>What is the best way to do this?</p> <p>I have figured out a way to do this but it sounds "clumsy,far fetched and unpythonic".</p>
1
2009-01-30T09:54:23Z
495,027
<p>Generally the server keeps on running - so register both methods at the start. I don't understand why you want to unregister your functions. Servers stay up and handle multiple requests. You might possible want a <code>shutdown()</code> function that shuts the entire server down, but I don't see anyway to unregister a single function.</p> <p>The easiest way is with <a href="http://docs.python.org/library/simplexmlrpcserver.html" rel="nofollow">SimpleXMLRPCServer</a>:</p> <pre><code>from SimpleXMLRPCServer import SimpleXMLRPCServer def fun1(x, y): return x + y def fun2(x, y): return x - y server = SimpleXMLRPCServer(("localhost", 8000)) server.register_function(fun1) server.register_function(fun2) server.serve_forever() </code></pre>
2
2009-01-30T10:13:08Z
[ "python", "xml-rpc" ]
HOWTO: XML-RPC dynamic function registration in python?
494,997
<p>I am new to XML-RPC.</p> <pre><code>#client code import xmlrpclib proxy = xmlrpclib.ServerProxy("http://localhost:8000/") x,y = arg1,arg2 print proxy.fun1(x,y) print proxy.fun2(x,y) </code></pre> <p>What server should do:</p> <ol> <li>load fun1</li> <li>register fun1</li> <li>return result</li> <li>unload fun1</li> </ol> <p>and then do same with fun2.</p> <p>What is the best way to do this?</p> <p>I have figured out a way to do this but it sounds "clumsy,far fetched and unpythonic".</p>
1
2009-01-30T09:54:23Z
499,453
<p>If you want dynamic registering, register an instance of an object, and then set attributes on that object. You can get more advanced by using the <code>__getattr__</code> method of the class if the function needs to be determined at run time.</p> <pre><code>class dispatcher(object): pass def __getattr__(self, name): # logic to determine if 'name' is a function, and what # function should be returned return the_func server = SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(dispatcher()) </code></pre>
1
2009-01-31T20:07:49Z
[ "python", "xml-rpc" ]
HOWTO: XML-RPC dynamic function registration in python?
494,997
<p>I am new to XML-RPC.</p> <pre><code>#client code import xmlrpclib proxy = xmlrpclib.ServerProxy("http://localhost:8000/") x,y = arg1,arg2 print proxy.fun1(x,y) print proxy.fun2(x,y) </code></pre> <p>What server should do:</p> <ol> <li>load fun1</li> <li>register fun1</li> <li>return result</li> <li>unload fun1</li> </ol> <p>and then do same with fun2.</p> <p>What is the best way to do this?</p> <p>I have figured out a way to do this but it sounds "clumsy,far fetched and unpythonic".</p>
1
2009-01-30T09:54:23Z
25,202,763
<p>You can register functions dynamically (after the server has been started): </p> <pre><code>#Server side code: import sys from SimpleXMLRPCServer import SimpleXMLRPCServer def dynRegFunc(): #this function will be registered dynamically, from the client return True def registerFunction(function): #this function will register with the given name server.register_function(getattr(sys.modules[__name__], str(function))) if __name__ == '__main__': server = SimpleXMLRPCServer((address, port)), allow_none = True) server.register_function(registerFunction) server.serve_forever() #Client side code: import xmlrpclib if __name__ == '__main__': proxy = xmlrpclib.ServerProxy('http://'+str(address)+':'+str(port), allow_none = True) #if you'd try to call the function dynRegFunc now, it wouldnt work, since it's not registered -&gt; proxy.dynRegFunc() would fail to execute #register function dynamically: proxy.registerFunction("dynRegFunc") #call the newly registered function proxy.dynRegFunc() #should work now! </code></pre>
1
2014-08-08T11:44:29Z
[ "python", "xml-rpc" ]
Refactor this Python code to iterate over a container
495,294
<p>Surely there is a better way to do this?</p> <pre><code>results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) </code></pre> <p>The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set to an empty list. This code is from a Django view, but I don't think that matters--this seems like a more general Python question.</p> <p><strong>EDIT:</strong> I turns out that it was my code that was turning an empty queryset into a "None" instead of returning an empty list. Being able to assume that queryset is always iteratable simplifies the code by allowing the "if" statement to be removed. The answers below maybe useful to others who have the same problem, but cannot modify their code to guarantee that queryset is not "None".</p>
3
2009-01-30T12:02:34Z
495,327
<p>you can use list comprehensions, but other than that I don't see what you can improve</p> <pre><code>result = [] if queryset: result = [(getattr(obj, field.attname), obj.pk) for obj in queryset] </code></pre>
1
2009-01-30T12:16:41Z
[ "python", "django", "refactoring", "iterator" ]
Refactor this Python code to iterate over a container
495,294
<p>Surely there is a better way to do this?</p> <pre><code>results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) </code></pre> <p>The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set to an empty list. This code is from a Django view, but I don't think that matters--this seems like a more general Python question.</p> <p><strong>EDIT:</strong> I turns out that it was my code that was turning an empty queryset into a "None" instead of returning an empty list. Being able to assume that queryset is always iteratable simplifies the code by allowing the "if" statement to be removed. The answers below maybe useful to others who have the same problem, but cannot modify their code to guarantee that queryset is not "None".</p>
3
2009-01-30T12:02:34Z
495,343
<pre><code>results = [(getattr(obj, field.attname), obj.pk) for obj in queryset or []] </code></pre>
19
2009-01-30T12:22:05Z
[ "python", "django", "refactoring", "iterator" ]
Refactor this Python code to iterate over a container
495,294
<p>Surely there is a better way to do this?</p> <pre><code>results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) </code></pre> <p>The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set to an empty list. This code is from a Django view, but I don't think that matters--this seems like a more general Python question.</p> <p><strong>EDIT:</strong> I turns out that it was my code that was turning an empty queryset into a "None" instead of returning an empty list. Being able to assume that queryset is always iteratable simplifies the code by allowing the "if" statement to be removed. The answers below maybe useful to others who have the same problem, but cannot modify their code to guarantee that queryset is not "None".</p>
3
2009-01-30T12:02:34Z
495,400
<p>How about</p> <pre><code>for obj in (queryset or []): # Do your stuff </code></pre> <p>It is the same as J.F Sebastians suggestion, only not implemented as a list comprehension.</p>
8
2009-01-30T12:44:35Z
[ "python", "django", "refactoring", "iterator" ]
Refactor this Python code to iterate over a container
495,294
<p>Surely there is a better way to do this?</p> <pre><code>results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) </code></pre> <p>The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set to an empty list. This code is from a Django view, but I don't think that matters--this seems like a more general Python question.</p> <p><strong>EDIT:</strong> I turns out that it was my code that was turning an empty queryset into a "None" instead of returning an empty list. Being able to assume that queryset is always iteratable simplifies the code by allowing the "if" statement to be removed. The answers below maybe useful to others who have the same problem, but cannot modify their code to guarantee that queryset is not "None".</p>
3
2009-01-30T12:02:34Z
522,646
<p>For what it's worth, Django managers have a "none" queryset that you can use to avoid gratuitous None-checking. Using it to ensure you don't have a null queryset may simplify your code.</p> <pre><code>if queryset is None: queryset = MyModel.objects.none() </code></pre> <p>References:</p> <ul> <li><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#none" rel="nofollow">Django documentation on none()</a></li> <li><a href="http://en.wikipedia.org/wiki/Null_Object_pattern" rel="nofollow">Null Object Pattern</a></li> </ul>
2
2009-02-06T23:23:36Z
[ "python", "django", "refactoring", "iterator" ]
Confusion about global variables in python
495,422
<p>I'm new to python, so please excuse what is probably a pretty dumb question. </p> <p>Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it.</p> <p>I have two scripts:</p> <pre><code>one.py: ------- def my_function(): if _debug: print "debugging!" two.py: ------- from one import * _debug = False my_function() </code></pre> <p>Running two.py generates an error:</p> <pre><code>NameError: global name '_debug' is not defined </code></pre> <p>Can anyone tell me what I'm doing wrong?</p>
11
2009-01-30T12:56:57Z
495,444
<p>Names beginning with an underscore aren't imported with </p> <pre><code>from one import * </code></pre>
5
2009-01-30T13:07:48Z
[ "python", "global-variables", "python-import" ]
Confusion about global variables in python
495,422
<p>I'm new to python, so please excuse what is probably a pretty dumb question. </p> <p>Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it.</p> <p>I have two scripts:</p> <pre><code>one.py: ------- def my_function(): if _debug: print "debugging!" two.py: ------- from one import * _debug = False my_function() </code></pre> <p>Running two.py generates an error:</p> <pre><code>NameError: global name '_debug' is not defined </code></pre> <p>Can anyone tell me what I'm doing wrong?</p>
11
2009-01-30T12:56:57Z
495,559
<p>You can also use the <code>__debug__</code> variable for debugging. It is true if the interpreter wasn't started with the -O option. The assert statement might be helpful, too.</p>
4
2009-01-30T13:57:06Z
[ "python", "global-variables", "python-import" ]
Confusion about global variables in python
495,422
<p>I'm new to python, so please excuse what is probably a pretty dumb question. </p> <p>Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it.</p> <p>I have two scripts:</p> <pre><code>one.py: ------- def my_function(): if _debug: print "debugging!" two.py: ------- from one import * _debug = False my_function() </code></pre> <p>Running two.py generates an error:</p> <pre><code>NameError: global name '_debug' is not defined </code></pre> <p>Can anyone tell me what I'm doing wrong?</p>
11
2009-01-30T12:56:57Z
495,570
<p>There are more problems than just the leading underscore I'm afraid.</p> <p>When you call <code>my_function()</code>, it still won't have your <code>debug</code> variable in its namespace, unless you import it from <code>two.py</code>.</p> <p>Of course, doing that means you'll end up with cyclic dependencies (<code>one.py -&gt; two.py -&gt; one.py</code>), and you'll get <code>NameError</code>s unless you refactor where various things are imported and declared.</p> <p>One solution would be to create a simple third module which defines 'constants' like this, which can be safely imported from anywhere, e.g.:</p> <pre><code>constants.py ------------ debug = True one.py ------ from constants import debug #... two.py ------ from constants import debug #... </code></pre> <p>However, I would recommend just using the built in <a href="http://docs.python.org/library/logging.html#module-logging">logging</a> module for this - why not? It's easy to configure, simpler to use, reliable, flexible and extensible.</p>
15
2009-01-30T14:01:27Z
[ "python", "global-variables", "python-import" ]
Confusion about global variables in python
495,422
<p>I'm new to python, so please excuse what is probably a pretty dumb question. </p> <p>Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it.</p> <p>I have two scripts:</p> <pre><code>one.py: ------- def my_function(): if _debug: print "debugging!" two.py: ------- from one import * _debug = False my_function() </code></pre> <p>Running two.py generates an error:</p> <pre><code>NameError: global name '_debug' is not defined </code></pre> <p>Can anyone tell me what I'm doing wrong?</p>
11
2009-01-30T12:56:57Z
495,731
<p>A bit more explanation: The function <code>my_function</code>'s namespace is always in the module <code>one</code>. This means that when the name <code>_debug</code> is not found in <code>my_function</code>, it looks in <code>one</code>, not the namespace from which the function is called. <a href="#495570" rel="nofollow">Alabaster's answer</a> provides a good solution.</p>
1
2009-01-30T14:45:32Z
[ "python", "global-variables", "python-import" ]
Get rid of '\n' in Python
495,424
<p>How to get rid of '\n' at the end of a line ?</p>
1
2009-01-30T12:58:46Z
495,428
<pre><code>"string \n".strip(); </code></pre> <p>or</p> <pre><code>"string \n".rstrip(); </code></pre>
22
2009-01-30T13:00:09Z
[ "python" ]
Get rid of '\n' in Python
495,424
<p>How to get rid of '\n' at the end of a line ?</p>
1
2009-01-30T12:58:46Z
495,449
<p>If, as Rolf suggests in his comment, you want to print text without having a newline automatically appended, use</p> <pre><code>print "foo", </code></pre> <p>Note the trailing comma.</p>
18
2009-01-30T13:10:51Z
[ "python" ]
Get rid of '\n' in Python
495,424
<p>How to get rid of '\n' at the end of a line ?</p>
1
2009-01-30T12:58:46Z
495,654
<p>If you want a slightly more complex and explicit way of writing output:</p> <pre><code>import sys sys.stdout.write("string") </code></pre> <p>Then you would responsible for your own newlines.</p>
2
2009-01-30T14:25:59Z
[ "python" ]
Get rid of '\n' in Python
495,424
<p>How to get rid of '\n' at the end of a line ?</p>
1
2009-01-30T12:58:46Z
495,804
<p>Get rid of just the "\n" at the end of the line:</p> <pre><code>&gt;&gt;&gt; "string \n".rstrip("\n") 'string ' </code></pre> <p>Get rid of all whitespace at the end of the line:</p> <pre><code>&gt;&gt;&gt; "string \n".rstrip() 'string' </code></pre> <p>Split text by lines, stripping trailing newlines:</p> <pre><code>&gt;&gt;&gt; "line 1\nline 2 \nline 3\n".splitlines() ['line 1', 'line 2 ', 'line 3'] </code></pre>
6
2009-01-30T15:03:03Z
[ "python" ]
Get rid of '\n' in Python
495,424
<p>How to get rid of '\n' at the end of a line ?</p>
1
2009-01-30T12:58:46Z
497,746
<p>In Python 3, to print a string without a newline, set the end to an empty string:</p> <pre><code>print("some string", end="") </code></pre>
4
2009-01-30T23:59:16Z
[ "python" ]
Python's version of PHP's time() function
495,595
<p>I've looked at the <a href="http://docs.python.org/library/time.html" rel="nofollow">Python Time module</a> and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time().</p> <p>Am I simply missing something here or is there a common way to do this that's simply not listed there?</p>
2
2009-01-30T14:09:29Z
495,610
<pre><code>import time print int(time.time()) </code></pre>
19
2009-01-30T14:13:19Z
[ "python", "time" ]
Python's version of PHP's time() function
495,595
<p>I've looked at the <a href="http://docs.python.org/library/time.html" rel="nofollow">Python Time module</a> and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time().</p> <p>Am I simply missing something here or is there a common way to do this that's simply not listed there?</p>
2
2009-01-30T14:09:29Z
495,612
<p><a href="http://docs.python.org/library/time.html#time.time">time.time()</a> does it, but it might be float instead of int which i assume you expect. that is, precision can be higher than 1 sec on some systems.</p>
5
2009-01-30T14:14:05Z
[ "python", "time" ]
Python's version of PHP's time() function
495,595
<p>I've looked at the <a href="http://docs.python.org/library/time.html" rel="nofollow">Python Time module</a> and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time().</p> <p>Am I simply missing something here or is there a common way to do this that's simply not listed there?</p>
2
2009-01-30T14:09:29Z
500,445
<p>I recommend reading <a href="http://seehuhn.de/pages/pdate" rel="nofollow">"Date and Time Representation in Python"</a>. I found it very enlightening.</p>
3
2009-02-01T08:41:58Z
[ "python", "time" ]
Is there any case where len(someObj) does not call someObj's __len__ function?
496,009
<p>Is there any case where len(someObj) does not call someObj's <code>__len__</code> function?</p> <p>I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.<code>__len__</code>().</p>
5
2009-01-30T15:58:58Z
496,019
<p>According to Mark Pilgrim, it looks like no. <code>len(someObj)</code> is the same as <code>someObj.__len__()</code>;</p> <p>Cheers!</p>
-1
2009-01-30T16:01:46Z
[ "python" ]
Is there any case where len(someObj) does not call someObj's __len__ function?
496,009
<p>Is there any case where len(someObj) does not call someObj's <code>__len__</code> function?</p> <p>I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.<code>__len__</code>().</p>
5
2009-01-30T15:58:58Z
496,024
<p>I think the answer is that it will always work -- according to the Python docs:</p> <pre><code>__len__(self): </code></pre> <p>Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn't define a <code>__nonzero__()</code> method and whose <code>__len__()</code> method returns zero is considered to be false in a Boolean context.</p>
1
2009-01-30T16:03:57Z
[ "python" ]
Is there any case where len(someObj) does not call someObj's __len__ function?
496,009
<p>Is there any case where len(someObj) does not call someObj's <code>__len__</code> function?</p> <p>I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.<code>__len__</code>().</p>
5
2009-01-30T15:58:58Z
496,038
<p>What kind of speedup did you see? I cannot imagine it was noticeable was it?</p> <p>From <a href="http://mail.python.org/pipermail/python-list/2002-May/147079.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2002-May/147079.html</a></p> <blockquote> <p>in certain situations there is no difference, but using len() is preferred for a couple reasons.</p> <p>first, it's not recommended to go calling the <code>__methods__</code> yourself, they are meant to be used by other parts of python.</p> <p><code>len()</code> will work on any type of sequence object (<code>lists</code>, <code>tuples</code>, and all). <code>__len__</code> will only work on class instances with a <code>__len__</code> method.</p> <p><code>len()</code> will return a more appropriate exception on objects without length.</p> </blockquote>
7
2009-01-30T16:07:33Z
[ "python" ]
Is there any case where len(someObj) does not call someObj's __len__ function?
496,009
<p>Is there any case where len(someObj) does not call someObj's <code>__len__</code> function?</p> <p>I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.<code>__len__</code>().</p>
5
2009-01-30T15:58:58Z
497,096
<p>If <code>__len__</code> returns a length over <code>sys.maxsize</code>, <code>len()</code> will raise an exception. This isn't true of calling <code>__len__</code> directly. (In fact you could return any object from <code>__len__</code> which won't be caught unless it goes through <code>len()</code>.)</p>
4
2009-01-30T20:21:55Z
[ "python" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
496,641
<p>The easiest is to use an IDE. PyDev is a plugin for eclipse.</p> <p>I'm not a full on expert in all ways pythonic, but in general I define my class members right under the class definition in python, so if I add members, they're all relative.</p> <p>My personal opinion is that class members should be declared in one section, for this specific reason.</p> <p>Local scoped variables, otoh, should be defined closest to when they are used (except in C--which I believe still requires variables to be declared at the beginning of a method).</p>
0
2009-01-30T18:35:43Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
496,656
<p>First of all: class attributes, or instance attributes? Or both? =)</p> <p><em>Usually</em> you just add instance attributes in <code>__init__</code>, and class attributes in the class definition, often before method definitions... which should probably cover 90% of use cases.</p> <p>If code adds attributes on the fly, it probably (hopefully :-) has good reasons for doing so... leveraging dynamic features, introspection, etc. Other than that, adding attributes this way is probably less common than you think.</p>
7
2009-01-30T18:39:58Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
496,701
<p>It sounds like you're talking about instance variables and not class variables. Note that in the following code a is a class variable and b is an instance variable.</p> <pre><code>class foo: a = 0 #class variable def __init__(self): self.b = 0 #instance variable </code></pre> <p>Regarding the hypothetical where you create an unneeded instance variable because the other one was about one thousand lines away: The best solution is to not have classes that are one thousand lines long. If you can't avoid the length, then your class should have a well defined purpose and that will enable you to keep all of the complexities in your head at once.</p>
3
2009-01-30T18:50:16Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
496,820
<p>Instance variables should be initialized in the class's <code>__init__()</code> method. (In general)</p> <p>If that's not possible. You can use <code>__dict__</code> to get a dictionary of all instance variables of an object during runtime. If you really need to track this in documentation add a list of instance variables you are using into the docstring of the class. </p>
4
2009-01-30T19:18:27Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
496,906
<p>A documentation generation system such as <a href="http://epydoc.sourceforge.net/" rel="nofollow">Epydoc</a> can be used as a reference for what instance/class variables an object has, and if you're worried about accidentally creating new variables via typos you can use <a href="http://pychecker.sourceforge.net/" rel="nofollow">PyChecker</a> to check your code for this.</p>
3
2009-01-30T19:36:39Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
496,986
<p>Consider using <a href="http://docs.python.org/reference/datamodel.html#id3" rel="nofollow"><strong>slots</strong></a>.</p> <p>For example:</p> <pre> class Foo: __slots__ = "a b c".split() x = Foo() x.a =1 # ok x.b =1 # ok x.c =1 # ok x.bb = 1 # will raise "AttributeError: Foo instance has no attribute 'bb'" </pre> <p>It is generally a concern in any dynamic programming language -- any language that does not require variable declaration -- that a typo in a variable name will create a new variable instead of raise an exception or cause a compile-time error. Slots helps with instance variables, but doesn't help you with, module-scope variables, globals, local variables, etc. There's no silver bullet for this; it's part of the trade-off of not having to declare variables.</p>
-2
2009-01-30T19:56:27Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
498,284
<p>I would say, the standard practice to avoid this is to <em>not write classes where you can be 1000 lines away from anything!</em></p> <p>Seriously, that's way too much for just about any useful class, especially in a language that is as expressive as Python. Using more of what the Standard Library offers and abstracting away code into separate modules should help keeping your LOC count down.</p> <p>The largest classes in the standard library have well below 100 lines! </p>
9
2009-01-31T04:45:58Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
498,421
<p>This is a common concern I hear from many programmers who come from a C, C++, or other statically typed language where variables are pre-declared. In fact it was one of the biggest concerns we heard when we were persuading programmers at our organization to abandon C for high-level programs and use Python instead.</p> <p>In theory, yes you can add instance variables to an object at any time. Yes it can happen from typos, etc. In practice, it rarely results in a bug. When it does, the bugs are generally not hard to find. </p> <p>As long as your classes are not bloated (1000 lines is pretty huge!) and you have ample unit tests, you should rarely run in to a real problem. In case you do, it's easy to drop to a Python console at almost any time and inspect things as much as you wish.</p>
2
2009-01-31T06:45:25Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
498,435
<p><a href="http://www.logilab.org/project/pylint" rel="nofollow">pylint</a> can statically detect attributes that aren't detected in <code>__init__</code>, along with many other potential bugs.</p> <p>I'd also recommend writing unit tests and running your code often to detect these types of "whoopsie" programming mistakes.</p>
4
2009-01-31T07:15:15Z
[ "python", "variables" ]
What's a good way to keep track of class instance variables in Python?
496,582
<p>I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a <code>.h</code> file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?</p> <p>I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?</p> <p><strong>Edit:</strong> It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.</p>
8
2009-01-30T18:21:13Z
498,447
<p>It seems to me that the main issue here is that you're thinking in terms of C++ when you're working in python.</p> <p>Having a 1000 line class is not a very wise thing anyway in python, (I know it happens alot in C++ though), </p> <p>Learn to exploit the dynamism that python gives you, for instance you can combine lists and dictionaries in very creative ways and save your self hundreds of useless lines of code.</p> <p>For example, if you're mapping strings to functions (for dispatching), you can exploit the fact that functions are first class objects and have a dictionary that goes like:</p> <pre><code>d = {'command1' : func1, 'command2': func2, 'command3' : func3} #then somewhere else use this list to dispatch #given a string `str` func = d[str] func() #call the function! </code></pre> <p>Something like this in C++ would take up sooo many lines of code!</p>
2
2009-01-31T07:31:21Z
[ "python", "variables" ]
Progress bar not updating during operation
496,814
<p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...my question is - do i need to have a multi-threaded application to upload the file and simultaneously update the gui? or is there some other mistake that im making? </p> <p>Thanks in advance!</p>
7
2009-01-30T19:17:39Z
496,995
<p>More than likely the issue is that in your progress callback, which is where I presume you're updating the progress bar, you're not making a call to manually update the display i.e. run through the GUI's event loop. This is just speculation though, if you can provide more code, it might be easier to narrow it down further.</p> <p>The reason you need to manually update the display is because your main thread is also performing the upload, which is where it's blocking.</p>
1
2009-01-30T19:57:36Z
[ "python", "user-interface", "gtk", "progress-bar", "pygtk" ]
Progress bar not updating during operation
496,814
<p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...my question is - do i need to have a multi-threaded application to upload the file and simultaneously update the gui? or is there some other mistake that im making? </p> <p>Thanks in advance!</p>
7
2009-01-30T19:17:39Z
497,283
<p>In python 2.x integer operands result in integer division. Try this:</p> <pre><code>#Callback function invoked when download/upload has progress def progress(download_t, download_d, upload_t, upload_d): print 'in fileupload progress' mainwin.mainw.prog_bar.set_fraction(float(upload_d) / upload_t) </code></pre>
0
2009-01-30T21:15:17Z
[ "python", "user-interface", "gtk", "progress-bar", "pygtk" ]
Progress bar not updating during operation
496,814
<p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...my question is - do i need to have a multi-threaded application to upload the file and simultaneously update the gui? or is there some other mistake that im making? </p> <p>Thanks in advance!</p>
7
2009-01-30T19:17:39Z
497,313
<p>I'm going to quote the <a href="http://faq.pygtk.org/index.py?req=show&amp;file=faq23.020.htp">PyGTK FAQ</a>:</p> <blockquote> <p>You have created a progress bar inside a window, then you start running a loop that does some work:</p> </blockquote> <pre><code>while work_left: ...do something... progressbar.set_fraction(...) </code></pre> <blockquote> <p>You will notice that the window doesn't even show up, or if it does the progress bar stays frozen until the end of the task. The explanation is simple: gtk is event driven, and you are stealing control away from the gtk main loop, thus preventing it from processing normal GUI update events.</p> <p>The simplest solution consists on temporarily giving control back to gtk every time the progress is changed:</p> </blockquote> <pre><code>while work_left: ...do something... progressbar.set_fraction(...) while gtk.events_pending(): gtk.main_iteration() </code></pre> <blockquote> <p>Notice that with this solution, the user cannot quit the application (gtk.main_quit would not work because of new loop [gtk.main_iteration()]) until your heavy_work is done.</p> <p>Another solution consists on using gtk idle functions, which are called by the gtk main loop whenever it has nothing to do. Therefore, gtk is in control, and the idle function has to do a bit of work. It should return True if there's more work to be done, otherwise False.</p> <p>The best solution (it has no drawbacks) was pointed out by James Henstridge. It is taking advantage of python's generators as idle functions, to make python automatically preserve the state for us. It goes like this:</p> </blockquote> <pre><code>def my_task(data): ...some work... while heavy_work_needed: ...do heavy work here... progress_label.set_text(data) # here we update parts of UI # there's more work, return True yield True # no more work, return False yield False def on_start_my_task_button_click(data): task = my_task(data) gobject.idle_add(task.next) </code></pre> <blockquote> <p>The 'while' above is just an example. The only rules are that it should yield True after doing a bit of work and there's more work to do, and it must yield False when the task is done. </p> </blockquote>
12
2009-01-30T21:26:52Z
[ "python", "user-interface", "gtk", "progress-bar", "pygtk" ]
Progress bar not updating during operation
496,814
<p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...my question is - do i need to have a multi-threaded application to upload the file and simultaneously update the gui? or is there some other mistake that im making? </p> <p>Thanks in advance!</p>
7
2009-01-30T19:17:39Z
505,876
<p>Yes, you probably need concurrency, and yes threads are one approach, but if you do use threads, please use an method like this one: <a href="http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html" rel="nofollow">http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html</a> which will abstract away the pain, and allow you to focus on the important aspects.</p> <p>(I have not repeated everything in that blog post through laziness, hence community wiki).</p>
0
2009-02-03T02:51:56Z
[ "python", "user-interface", "gtk", "progress-bar", "pygtk" ]
Progress bar not updating during operation
496,814
<p>in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...my question is - do i need to have a multi-threaded application to upload the file and simultaneously update the gui? or is there some other mistake that im making? </p> <p>Thanks in advance!</p>
7
2009-01-30T19:17:39Z
661,113
<p>One option, if you are not married to pycurl, is to use GObject's IO watchers.</p> <p><a href="http://pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--io-add-watch" rel="nofollow">http://pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--io-add-watch</a></p> <p>Using this you can interleave the file upload with the normal PyGTK event loop, and even do the set_progress call in your IO watch callback. If you are offloading all the work for uploading onto pycurl this is not really feasible, but if you're just uploading a file over HTTP, io_add_watch will make using a socket for this much less painful as well.</p>
0
2009-03-19T05:00:58Z
[ "python", "user-interface", "gtk", "progress-bar", "pygtk" ]
Is there a Python equivalent of Perl's x operator?
497,114
<p>In Perl, I can replicate strings with the 'x' operator:</p> <pre><code>$str = "x" x 5; </code></pre> <p>Can I do something similar in Python?</p>
11
2009-01-30T20:27:49Z
497,119
<pre><code>&gt;&gt;&gt; "blah" * 5 'blahblahblahblahblah' </code></pre>
31
2009-01-30T20:29:15Z
[ "python", "perl" ]
Is there a Python equivalent of Perl's x operator?
497,114
<p>In Perl, I can replicate strings with the 'x' operator:</p> <pre><code>$str = "x" x 5; </code></pre> <p>Can I do something similar in Python?</p>
11
2009-01-30T20:27:49Z
30,409,778
<p>Here is a reference to the official Python3 docs:</p> <p><a href="https://docs.python.org/3/library/stdtypes.html#string-methods" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#string-methods</a></p> <blockquote> <p>Strings implement all of the <a href="https://docs.python.org/3/library/stdtypes.html#typesseq-common" rel="nofollow"><em>common</em></a> sequence operations...</p> </blockquote> <p>... which leads us to:</p> <p><a href="https://docs.python.org/3/library/stdtypes.html#typesseq-common" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#typesseq-common</a></p> <pre><code>Operation | Result s * n or n * s | n shallow copies of s concatenated </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; 'a' * 5 'aaaaa' &gt;&gt;&gt; 5 * 'b' 'bbbbb' </code></pre>
1
2015-05-23T06:43:10Z
[ "python", "perl" ]
Python's os.path choking on Hebrew filenames
497,233
<p>I'm writing a script that has to move some file around, but unfortunately it doesn't seem <code>os.path</code> plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:</p> <p><img src="http://eli.thegreenplace.net/files/temp/hebfilenameshot.png" alt="alt text" /></p> <p>Now consider this code that goes over the files in this directory:</p> <pre><code>files = os.listdir('test_source') for f in files: pf = os.path.join('test_source', f) print pf, os.path.exists(pf) </code></pre> <p>The output is:</p> <pre><code>test_source\ex True test_source\joe True test_source\mie.txt True test_source\__()'''.txt True test_source\????.txt False </code></pre> <p>Notice how <code>os.path.exists</code> thinks that the hebrew-named file doesn't even exist? How can I fix this?</p> <p>ActivePython 2.5.2 on Windows XP Home SP2</p>
13
2009-01-30T21:03:24Z
497,309
<p>It looks like a Unicode vs ASCII issue - <code>os.listdir</code> is returning a list of ASCII strings. </p> <p>Edit: I tried it on Python 3.0, also on XP SP2, and <code>os.listdir</code> simply omitted the Hebrew filenames instead of listing them at all.</p> <p>According to the docs, this means it was unable to decode it:</p> <blockquote> <p>Note that when os.listdir() returns a list of strings, filenames that cannot be decoded properly are omitted rather than raising UnicodeError.</p> </blockquote>
3
2009-01-30T21:25:24Z
[ "python", "internationalization", "hebrew" ]
Python's os.path choking on Hebrew filenames
497,233
<p>I'm writing a script that has to move some file around, but unfortunately it doesn't seem <code>os.path</code> plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:</p> <p><img src="http://eli.thegreenplace.net/files/temp/hebfilenameshot.png" alt="alt text" /></p> <p>Now consider this code that goes over the files in this directory:</p> <pre><code>files = os.listdir('test_source') for f in files: pf = os.path.join('test_source', f) print pf, os.path.exists(pf) </code></pre> <p>The output is:</p> <pre><code>test_source\ex True test_source\joe True test_source\mie.txt True test_source\__()'''.txt True test_source\????.txt False </code></pre> <p>Notice how <code>os.path.exists</code> thinks that the hebrew-named file doesn't even exist? How can I fix this?</p> <p>ActivePython 2.5.2 on Windows XP Home SP2</p>
13
2009-01-30T21:03:24Z
497,351
<p>It works like a charm using Python 2.5.1 on OS X:</p> <pre><code>subdir/bar.txt True subdir/foo.txt True subdir/עִבְרִית.txt True </code></pre> <p>Maybe that means that this has to do with Windows XP somehow?</p> <p>EDIT: I also tried with unicode strings to try mimic the Windows behaviour better:</p> <pre><code>for f in os.listdir(u'subdir'): pf = os.path.join(u'subdir', f) print pf, os.path.exists(pf) subdir/bar.txt True subdir/foo.txt True subdir/עִבְרִית.txt True </code></pre> <p>In the Terminal (os x stock command prompt app) that is. Using IDLE it still worked but didn't print the filename correctly. To make sure it really is unicode there I checked:</p> <pre><code>&gt;&gt;&gt;os.listdir(u'listdir')[2] u'\u05e2\u05b4\u05d1\u05b0\u05e8\u05b4\u05d9\u05ea.txt' </code></pre>
0
2009-01-30T21:38:37Z
[ "python", "internationalization", "hebrew" ]
Python's os.path choking on Hebrew filenames
497,233
<p>I'm writing a script that has to move some file around, but unfortunately it doesn't seem <code>os.path</code> plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:</p> <p><img src="http://eli.thegreenplace.net/files/temp/hebfilenameshot.png" alt="alt text" /></p> <p>Now consider this code that goes over the files in this directory:</p> <pre><code>files = os.listdir('test_source') for f in files: pf = os.path.join('test_source', f) print pf, os.path.exists(pf) </code></pre> <p>The output is:</p> <pre><code>test_source\ex True test_source\joe True test_source\mie.txt True test_source\__()'''.txt True test_source\????.txt False </code></pre> <p>Notice how <code>os.path.exists</code> thinks that the hebrew-named file doesn't even exist? How can I fix this?</p> <p>ActivePython 2.5.2 on Windows XP Home SP2</p>
13
2009-01-30T21:03:24Z
497,356
<p>Hmm, after <a href="http://www.amk.ca/python/howto/unicode">some digging</a> it appears that when supplying os.listdir a unicode string, this kinda works:</p> <pre><code>files = os.listdir(u'test_source') for f in files: pf = os.path.join(u'test_source', f) print pf.encode('ascii', 'replace'), os.path.exists(pf) </code></pre> <p>===></p> <pre><code>test_source\ex True test_source\joe True test_source\mie.txt True test_source\__()'''.txt True test_source\????.txt True </code></pre> <p>Some important observations here:</p> <ul> <li>Windows XP (like all NT derivatives) stores <em>all</em> filenames in unicode</li> <li><code>os.listdir</code> (and similar functions, like <code>os.walk</code>) should be passed a unicode string in order to work correctly with unicode paths. Here's a quote from the aforementioned link:</li> </ul> <blockquote> <p>os.listdir(), which returns filenames, raises an issue: should it return the Unicode version of filenames, or should it return 8-bit strings containing the encoded versions? os.listdir() will do both, depending on whether you provided the directory path as an 8-bit string or a Unicode string. If you pass a Unicode string as the path, filenames will be decoded using the filesystem's encoding and a list of Unicode strings will be returned, while passing an 8-bit path will return the 8-bit versions of the filenames.</p> </blockquote> <ul> <li>And lastly, <code>print</code> wants an ascii string, not unicode, so the path has to be encoded to ascii.</li> </ul>
14
2009-01-30T21:40:06Z
[ "python", "internationalization", "hebrew" ]
Python's os.path choking on Hebrew filenames
497,233
<p>I'm writing a script that has to move some file around, but unfortunately it doesn't seem <code>os.path</code> plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory:</p> <p><img src="http://eli.thegreenplace.net/files/temp/hebfilenameshot.png" alt="alt text" /></p> <p>Now consider this code that goes over the files in this directory:</p> <pre><code>files = os.listdir('test_source') for f in files: pf = os.path.join('test_source', f) print pf, os.path.exists(pf) </code></pre> <p>The output is:</p> <pre><code>test_source\ex True test_source\joe True test_source\mie.txt True test_source\__()'''.txt True test_source\????.txt False </code></pre> <p>Notice how <code>os.path.exists</code> thinks that the hebrew-named file doesn't even exist? How can I fix this?</p> <p>ActivePython 2.5.2 on Windows XP Home SP2</p>
13
2009-01-30T21:03:24Z
497,518
<p>A question mark is the more or less universal symbol displayed when a unicode character can't be represented in a specific encoding. Your terminal or interactive session under Windows is probably using ASCII or ISO-8859-1 or something. So the actual string is unicode, but it gets translated to ???? when printed to the terminal. That's why it works for PEZ, using OSX.</p>
0
2009-01-30T22:27:12Z
[ "python", "internationalization", "hebrew" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
497,434
<p>If you're deleting multiple non-adjacent items, then what you describe is the best way (and yes, be sure to start from the highest index).</p> <p>If your items are adjacent, you can use the slice assignment syntax:</p> <pre><code>a[2:10] = [] </code></pre>
65
2009-01-30T22:02:26Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
497,439
<p>Probably not the best solution for this problem:</p> <pre><code>indices = 0, 2 somelist = [i for j, i in enumerate(somelist) if j not in indices] </code></pre>
45
2009-01-30T22:05:01Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
497,451
<p>As a function:</p> <pre><code>def multi_delete(list_, *args): indexes = sorted(list(args), reverse=True) for index in indexes: del list_[index] return list_ </code></pre> <p>Runs in <strong>n log(n)</strong> time, which should make it the fastest correct solution yet.</p>
13
2009-01-30T22:09:38Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
497,455
<p>You can do that way on a dict, not on a list. In a list elements are in sequence. In a dict they depend only on the index.</p> <p>Simple code just to explain it <em>by doing</em>:</p> <pre><code>&gt;&gt;&gt; lst = ['a','b','c'] &gt;&gt;&gt; dct = {0: 'a', 1: 'b', 2:'c'} &gt;&gt;&gt; lst[0] 'a' &gt;&gt;&gt; dct[0] 'a' &gt;&gt;&gt; del lst[0] &gt;&gt;&gt; del dct[0] &gt;&gt;&gt; lst[0] 'b' &gt;&gt;&gt; dct[0] Traceback (most recent call last): File "&lt;pyshell#19&gt;", line 1, in &lt;module&gt; dct[0] KeyError: 0 &gt;&gt;&gt; dct[1] 'b' &gt;&gt;&gt; lst[1] 'c' </code></pre> <p>A way to "convert" a list in a dict is:</p> <pre><code>&gt;&gt;&gt; dct = {} &gt;&gt;&gt; for i in xrange(0,len(lst)): dct[i] = lst[i] </code></pre> <p>The inverse is:</p> <pre><code>lst = [dct[i] for i in sorted(dct.keys())] </code></pre> <p>Anyway I think it's better to start deleting from the higher index as you said.</p>
0
2009-01-30T22:10:18Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
497,467
<p>I can actually think of two ways to do it:</p> <ol> <li><p>slice the list like (this deletes the 1st,3rd and 8th elements)</p> <p>somelist = somelist[1:2]+somelist[3:7]+somelist[8:]</p></li> <li><p>do that in place, but one at a time:</p> <p>somelist.pop(2) somelist.pop(0)</p></li> </ol>
0
2009-01-30T22:13:28Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
498,074
<p>So, you essentially want to delete multiple elements in one pass? In that case, the position of the next element to delete will be offset by however many were deleted previously.</p> <p>Our goal is to delete all the vowels, which are precomputed to be indices 1, 4, and 7. Note that its important the to_delete indices are in ascending order, otherwise it won't work.</p> <pre><code>to_delete = [1, 4, 7] target = list("hello world") for offset, index in enumerate(to_delete): index -= offset del target[index] </code></pre> <p>It'd be a more complicated if you wanted to delete the elements in any order. IMO, sorting <code>to_delete</code> might be easier than figuring out when you should or shouldn't subtract from <code>index</code>.</p>
9
2009-01-31T02:23:39Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
500,076
<p>As a specialisation of Greg's answer, you can even use extended slice syntax. eg. If you wanted to delete items 0 and 2:</p> <pre><code>&gt;&gt;&gt; a= [0, 1, 2, 3, 4] &gt;&gt;&gt; del a[0:3:2] &gt;&gt;&gt; a [1, 3, 4] </code></pre> <p>This doesn't cover any arbitrary selection, of course, but it can certainly work for deleting any two items.</p>
14
2009-02-01T02:55:32Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
7,016,104
<p>here is another method which removes the elements in place. also if your list is really long, it is faster.</p> <pre><code>&gt;&gt;&gt; a = range(10) &gt;&gt;&gt; remove = [0,4,5] &gt;&gt;&gt; from collections import deque &gt;&gt;&gt; deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0) &gt;&gt;&gt; timeit.timeit('[i for j, i in enumerate(a) if j not in remove]', setup='import random;remove=[random.randrange(100000) for i in range(100)]; a = range(100000)', number=1) 0.1704120635986328 &gt;&gt;&gt; timeit.timeit('deque((list.pop(a, i) for i in sorted(remove, reverse=True)), maxlen=0)', setup='from collections import deque;import random;remove=[random.randrange(100000) for i in range(100)]; a = range(100000)', number=1) 0.004853963851928711 </code></pre>
2
2011-08-10T18:48:23Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
12,414,409
<p>I'm a total beginner in Python, and my programming at the moment is crude and dirty to say the least, but my solution was to use a combination of the basic commands I learnt in early tutorials:</p> <pre><code>SomeList = [1,2,3,4,5,6,7,8,10] Rem = [0,5,7] for i in Rem: SomeList[i]='!' # mark for deletion for i in range(0,SomeList.count('!')): SomeList.remove('!') # remove print SomeList </code></pre> <p>Obviously, because of having to choose a "mark-for-deletion" character, this has its limitations. </p> <p>As for the performance as the size of the list scales, I'm sure that my solution is sub-optimal. However, it's straightforward, which I hope appeals to other beginners, and will work in simple cases where SomeList is of a well-known format, e.g., always numeric...</p>
6
2012-09-13T20:36:53Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
20,589,125
<p>Here is an alternative, that does not use enumerate() to create tuples (as in SilentGhost's original answer).</p> <p>This seems more readable to me. (Maybe I'd feel differently if I was in the habit of using enumerate.) CAVEAT: I have not tested performance of the two approaches.</p> <pre><code># Returns a new list. "lst" is not modified. def delete_by_indices(lst, indices): indices_as_set = set(indices) return [ lst[i] for i in xrange(len(lst)) if i not in indices_as_set ] </code></pre> <p>NOTE: Python 2.7 syntax. For Python 3, <code>xrange</code> => <code>range</code>.</p> <p>Usage:</p> <pre><code>lst = [ 11*x for x in xrange(10) ] somelist = delete_by_indices( lst, [0, 4, 5]) </code></pre> <p>somelist:</p> <pre><code>[11, 22, 33, 66, 77, 88, 99] </code></pre> <hr> <p><strong>--- BONUS ---</strong></p> <p>Delete multiple values from a list. That is, we have the values we want to delete:</p> <pre><code># Returns a new list. "lst" is not modified. def delete__by_values(lst, values): values_as_set = set(values) return [ x for x in lst if x not in values_as_set ] </code></pre> <p>Usage:</p> <pre><code>somelist = delete__by_values( lst, [0, 44, 55] ) </code></pre> <p>somelist:</p> <pre><code>[11, 22, 33, 66, 77, 88, 99] </code></pre> <p>This is the same answer as before, but this time we supplied the VALUES to be deleted <code>[0, 44, 55]</code>.</p>
2
2013-12-14T22:45:47Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
25,792,322
<p>Remove method will causes a lot of shift of list elements. I think is better to make a copy:</p> <pre><code>... new_list = [] for el in obj.my_list: if condition_is_true(el): new_list.append(el) del obj.my_list obj.my_list = new_list ... </code></pre>
1
2014-09-11T16:12:03Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
26,084,037
<p>This has been mentioned, but somehow nobody managed to actually get it right.</p> <p>On <code>O(n)</code> solution would be:</p> <pre><code>indices = {0, 2} somelist = [i for j, i in enumerate(somelist) if j not in indices] </code></pre> <p>This is really close to <a href="http://stackoverflow.com/a/497439/1763356">SilentGhost's version</a>, but adds two braces.</p>
2
2014-09-28T10:37:42Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
28,697,246
<p>For some reason I don't like any of the answers here. Yes, they work, but strictly speaking most of them aren't deleting elements in a list, are they? (But making a copy and then replacing the original one with the edited copy).</p> <p>Why not just delete the higher index first?</p> <p>Is there a reason for this? I would just do:</p> <pre><code>for i in sorted(indices, reverse=True): del somelist[i] </code></pre> <p>If you really don't want to delete items backwards, then I guess you should just deincrement the indices values which are greater than the last deleted index (can't really use the same index since you're having a different list) or use a copy of the list (which wouldn't be 'deleting' but replacing the original with an edited copy).</p> <p>Am I missing something here, any reason to NOT delete in the reverse order?</p>
30
2015-02-24T13:36:44Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
30,901,421
<p>technically, the answer is NO it is not possible to delete two objects AT THE SAME TIME. However, it IS possible to delete two objects in one line of beautiful python.</p> <pre><code>del (foo['bar'],foo['baz']) </code></pre> <p>will recusrively delete <code>foo['bar']</code>, then <code>foo['baz']</code></p>
1
2015-06-17T20:08:39Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
32,744,088
<p>You can use <code>numpy.delete</code> as follows:</p> <pre><code>import numpy as np a = ['a', 'l', 3.14, 42, 'u'] I = [0, 2] np.delete(a, I).tolist() # Returns: ['l', '42', 'u'] </code></pre> <p>If you don't mind ending up with a <code>numpy</code> array at the end, you can leave out the <code>.tolist()</code>. You should see some pretty major speed improvements, too, making this a more scalable solution. I haven't benchmarked it, but <code>numpy</code> operations are compiled code written in either C or Fortran.</p>
4
2015-09-23T15:49:17Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
34,121,072
<p>An alternative list comprehension method that uses list index values:</p> <pre><code>stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof'] index = [0, 3, 6] new = [i for i in stuff if stuff.index(i) not in index] </code></pre> <p>This returns:</p> <pre><code>['b', 'c', 'e', 'f'] </code></pre>
1
2015-12-06T18:32:34Z
[ "python", "list" ]
Deleting multiple elements from a list
497,426
<p>Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].</p> <p>I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.</p>
78
2009-01-30T21:59:38Z
34,349,945
<p>we can do this by use of a for loop iterating over the indexes after sorting the index list in descending order</p> <pre><code>mylist=[66.25, 333, 1, 4, 6, 7, 8, 56, 8769, 65] indexes = 4,6 indexes = sorted(indexes, reverse=True) for i in index: mylist.pop(i) print mylist </code></pre>
1
2015-12-18T06:50:23Z
[ "python", "list" ]