1 / 4
Aug 2009

Hi Everyone,
I am new to both Python and SPOJ. I hope that I can find some helps here smile
I have tried "The 3n plus 1 problem" (spoj.pl/problems/PROBTNPO/7) for today, but the result is always NZEC.
Here is my code

import string
def cycle(x):
    result=1
    while (x!=1):
        if (x%2==1):
            x=(3*x)+1
        elif (x%2==0):
            x=x/2
    result+=1
    return result
def main():
    data=raw_input()
    while data!=" ":
        p=data.find(" ")
        a=int(data[0:p])
        b=int(data[(p+1):len(data)])
        result=0
        for i in range(b-a+1):
            result=result+cycle(i+a)
        print result
        data=raw_input()
    return 0
main()

I do not know where it goes wrong. Can someone help me?

  • created

    Aug '09
  • last reply

    Nov '17
  • 3

    replies

  • 995

    views

  • 4

    users

  • 2

    links

First of all: You really should take some time to go through the official python tutorial (http://www.python.org3).

Some aspects:
- you can't use raw_input() for an input that ends with an EOF - search for it in the forum and you'll get some hints
- your cycle()-function doesn't work correctly because of wrong indentation
- there is no need of importing the string module
- there is a much more elegant way to read two values separated by a space
- if you found out that a number is not odd, you don't have to check, if it's really even ... smiley

a much more elegant way to read 2 values on the same line separated by a space is

a,b=([int(x) for x in raw_input().split()])
8 years later

I would add strip() as follows:

a, b = ([int(x) for x in raw_input().strip().split(" ")])