Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #58545

Re: Help me with this code

Date 2013-11-06 02:37 +0000
From MRAB <python@mrabarnett.plus.com>
Subject Re: Help me with this code
References <612c0028-ae66-4200-b9a5-a613eca94762@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.2072.1383705462.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 06/11/2013 01:51, chovdary@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.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Help me with this code chovdary@gmail.com - 2013-11-05 17:51 -0800
  Representing fractions (was: Help me with this code) Ben Finney <ben+python@benfinney.id.au> - 2013-11-06 13:06 +1100
  Re: Help me with this code MRAB <python@mrabarnett.plus.com> - 2013-11-06 02:37 +0000
  Re: Help me with this code Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-11-06 02:42 +0000
  Re: Help me with this code Dave Angel <davea@davea.name> - 2013-11-05 23:44 -0600
  Re: Help me with this code Piet van Oostrum <piet@vanoostrum.org> - 2013-11-07 09:08 -0400

csiph-web