Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

string - My python code that converts numbers between bases has several errors. What could be wrong and how can I find them?

My program is a function that converts numbers from one base to another. It takes three arguments: the initial value, the base of the initial value, then the base it is to be converted to.

The thing has several errors. For one, the thing won't accept any value that contains a letter for cnum. I don't know why. And I can't seem to figure out how to force the thing to recognize the argument 'cnum' as a string within the function call. I have to convert it into a function in the code itself.

Also, I can't get the second half, the part that converts the number to the final base, to work. Either it gives me an infinite loop (for some reason I can't figure out), or it doesn't do the complete calculation. This one, if I enter fconbase(100, 10, 12) Should convert 100 from base 10 to base 12. It only spits out 8. The answer should be 84.

Here's my entire function.

    #delcaring variables

cnum=0 #number to be converted
cbase1=0 #base the number is written in
cbase2=0 #base the number will be converted to
cnumlen=0 #number of digits
digitNum=0 #used to fetch out each digit one by one in order
exp=0 #used to calculate position in result
currentDigit="blank" #stores the digit that's been pulled from the string
result=0 #stores the result of internal calculations
decimalResult=0 #stores cnum as a base 10 number
finalResult=0 #the final result of the conversion

def fconbase(cnum, cbase1, cbase2):
    #converts number into base 10, because the math must be done in base 10
    #resets variables used in calculations
    exp=0
    result=0
    decimalResult=0
    currentDigit="blank"
    cnumlen=len(str(cnum)) #finds length of cnum, stays constant
    digitNum=cnumlen #sets starting placement
    while exp<cnumlen:
        currentDigit=str(cnum)[digitNum-1:digitNum]
        #the following converts letters into their corresponding integers
        if currentDigit=="a" or currentDigit=="A":
            currentDigit="10"
        if currentDigit=="b" or currentDigit=="B":
            currentDigit="11"
        if currentDigit=="c" or currentDigit=="C":
            currentDigit="12"
        if currentDigit=="d" or currentDigit=="D":
            currentDigit="13"
        if currentDigit=="e" or currentDigit=="E":
            currentdigit="14"
        if currentDigit=="f" or currentDigit=="F":
            currentDigit="15"
        result=int(currentDigit)
        decimalResult=decimalResult+result*(cbase1**exp)
        exp=exp+1
        digitNum=digitNum-1
    #this part converts the decimal number into the target base
    #resetting variables again
    exp=0
    result=0
    finalResult=""
    while int(decimalResult)>(cbase2**exp):
        exp=exp+1
    exp=exp-1
    while int(decimalResult)/cbase2**exp!=int(decimalResult):
        result=int(decimalResult/(cbase2**exp))
        if result==10:
            result="a"
        if result==11:
            result="b"
        if result==12:
            result="c"
        if result==13:
            result="d"
        if result==14:
            result="e"
        if result==15:
            result="f"
        finalResult=str(finalResult)+str(result)
        decimalResult=decimalResult%cbase2**exp
        exp=exp+1
    print(finalResult)

Here is what is supposed to happen in the latter half of the equation:

The program solves cbase2^exp. Exp starts at 0. If that number is less than the decimalResult, then it increases the exp(onent) by 1 and tries again until it results in a number that's greater than the decimalResult.

Then, it divides the decimalResult by cbase2^exp. It converts numbers between 10 and 15 as letters (for bases higher than 10), then appends the result to the final result. It should be concatenating the results together to form the final result that gets printed. I don't understand why its not doing that.

Why does it not generate the right result and why can't I enter a string into the function call?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Without going into specific problems with your code, which as you stated are many, I'll give a brief answer to the actual question in the title

What could be wrong and how can I find [the errors in my code]?

Rather than treating your code as one big complicated function that you have to stare at and understand all at once (I can rarely hold more than 10 lines of code in my own internal brain cache at once), try to break it down into smaller pieces "first I do this and expect this result. Then I take that result and do this to it, and expect another result."

From your description of the problem it seems like you're already thinking that way, but you still dumped this big chunk of code and seemed to struggle with figuring out exactly where the problem is. A lot of beginners will write some big pile of code, and then treat it as a black box while testing it. Like "I'm not getting the right answer and I don't know where the problem begins." This is where learning good debugging skills is crucial.

I would first break things into smaller pieces to just try out at the interactive Python prompt. Put in dummy values for different variables and make sure small snippets of code (1 to 5 lines or so, small small enough that it's easy to reason about) do exactly what you expect to do with different values of the variables.

If that doesn't help, then for starters the tried and true method, often for beginners and advanced developers alike, is to riddle your code with print statements. In as many places as you think is necessary, put a statement to print the values of one or more variables. Like print("exp = %s; result = %s" % (exp, result). Put something this in as many places as you need to trace the values of some variables through the execution. See where it starts to give answers that don't make sense.

Sometimes this is hard to do though. You might not be able to guess the most effective places to put print statements, or even what's important to print. In cases like this (and IMO in most cases) it is more effective to use an interactive debugger like Python's built in pdb. There are many good resources to learn pdb but the basics shouldn't take too long to get down and will save you a whole lot of headache.

pdb will run your code line-by-line, stopping after each line (and in loops it will step through each loop through the loop), allowing you to examine the contents of each variable before advancing to the next line. This gives you full power to check that each part of your code does or doesn't do what you expect, and should help you pinpoint numerous problem areas.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...