On 06/11/2013 01:51, chovd...@gmail.com wrote:
Hi friends
help me with the following code. Im able to execute the code but getting wrong
output
def sequence_b(N):
N = 10
result = 0
for k in xrange (1,N):
result += ((-1) ** (k+1))/2*k-1
print result
print sequence_b(10)
This is the output which im getting
-1
-4
-5
-10
-11
-18
-19
-28
-29
But i want output as
1
-1/3
1/5
-1/7
1/9
-1/11
1/13
-1/15
1/17
-1/19
1. Multiplication and division take precedence over addition and
subtraction, and both multiplication/division and addition/subtraction
are calculated left-to-right, so an expression like x/2*k-1 is
calculated as ((x/2)*k)-1.
2. In Python 2, dividing an integer by an integer gives an integer
result, e.g. 7/2 gives 3, not 3.5. The simplest way of fixing
that is to introduce a float into either the numerator or denominator.
That means that your expression should be, say:
((-1) ** (k + 1)) / (2.0 * k - 1)
3. It won't print fractions like 1/5, but instead decimals like 0.2.
4. You're adding the result of the expression to 'result' and then
printing the value of 'result', so your output would be the results of:
-1
-1+(-1/3)
-1+(-1/3)+(1/5)
and so on.
5. Your function prints the result but doesn't return anyhing, so, by
default, it'll return None. Therefore, 'print sequence_b(10)' will
print 'None'. What you'll get is a series of numbers and then a None.
--
https://mail.python.org/mailman/listinfo/python-list