'float' / 'int' object is not iterable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ghostdog74
    Recognized Expert Contributor
    • Apr 2006
    • 511

    #16
    Code:
    import operator
    def factorial(x):
       return reduce(operator.mul, xrange(2, x+1))
    result = reduce(operator.add,[ factorial(x) for x in xrange(2,101) ])
    print result

    Comment

    • python101
      New Member
      • Sep 2007
      • 90

      #17
      I intended to use only for loop (without using while loop, conditional statement, def)

      [code=python]
      n=10
      e=0
      for k in range(1,n):
      e=2+1.0/k*(k-1)

      print e

      [/code]
      I got 2.88888888889 which wasn't closed to 2.7. What did I do wrong, how could I fix this without using while loop, conditional statement, def

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #18
        Originally posted by python101
        I intended to use only for loop (without using while loop, conditional statement, def)

        [code=python]
        n=10
        e=0
        for k in range(1,n):
        e=2+1.0/k*(k-1)

        print e

        [/code]
        I got 2.88888888889 which wasn't closed to 2.7. What did I do wrong
        For one thing, you are assigning, not accumulating, as in:[CODE=python]#
        e += 2+1.0/k*(k-1)[/CODE]But that won't make the formula that you have work.

        Comment

        • KaezarRex
          New Member
          • Sep 2007
          • 52

          #19
          Originally posted by python101
          I intended to use only for loop (without using while loop, conditional statement, def)

          [code=python]
          n=10
          e=0
          for k in range(1,n):
          e=2+1.0/k*(k-1)

          print e

          [/code]
          I got 2.88888888889 which wasn't closed to 2.7. What did I do wrong, how could I fix this without using while loop, conditional statement, def
          In your for loop, "k*(k-1)" isn't equivalent to factorial. Every time it multiplies only two numbers together instead of the correct amount. As a result, the fractions being added together aren't getting smaller fast enough.

          Comment

          • python101
            New Member
            • Sep 2007
            • 90

            #20
            Is there any other way to accomplish this?

            Comment

            Working...