Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.9k views
in Technique[技术] by (71.8m points)

python - kaprekar numbers

def kaprekar_num(num):
    count = 0
    while count <= num:
        n = 1
        sqr = n ** 2
        digits = str(sqr)
        length = len(digits)
        for x in range(1, length):
            left = int("".join(digits[:x]))
            right = int("".join(digits[x:]))
            if (left + right) == n:
                print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
                n += 1
                count += 1
            else:
                n += 1
kaprekar_num(5)

hello guys, I'm new to python programming and I got a task in class to print the first 5 kaprekar numbers. (I only have C programming background...) I have a problem with the "for x in range..." line.. the code doesn't enter the loop and I don't know why. the program needs to print:

Number: 9, Left: 8 +  Right: 1 = 9
Number: 10, Left: 10 +  Right: 0 = 10
Number: 45, Left: 20 +  Right: 25 = 45
Number: 55, Left: 30 +  Right: 25 = 55
Number: 99, Left: 98 +  Right: 1 = 99

I will appreciate some insights :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How you're managing the n value is incorrect. It should be set before the loop starts, then after each try, regardless of the outcome, it should increment.

def kaprekar_num(num):
    count = 0
    # Start n at one, and don't reset it on each loop
    n = 1
    while count <= num:
        sqr = n ** 2
        digits = str(sqr)
        length = len(digits)
        for x in range(1, length):
            left = int("".join(digits[:x]))
            right = int("".join(digits[x:]))
            if (left + right) == n:
                print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
                count += 1
                # This number is a Kaprekar number, so break out of the loop
                break
        # Regardless of the status of this number, try the next one
        n += 1
kaprekar_num(5)

And as a recommendation: I'd highly recommend you look into stepping through the code with a debugger in the future. If you had done so, you'd have seen that n is not changing fairly quickly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...