[Tutor] String module; Count

Alan Gauld alan.gauld at btinternet.com
Mon Oct 22 09:22:36 CEST 2007

<ddm2 at sfu.ca> wrote

> think), but since I'm new to this thing, I thought I'd do the safe 
> thing and
> try a second time.

I personally didn't see the earlier one so can't say if it got here or 
But I'll throw in some comments below.

But first I will say that you seem to be going out of your way
to make easy things hard!

> def conversion(n):
>    b = ''
>    while n > 0:

So this returns the empty string when n is negative.
Is that really what you want?

> r = n%2
> n = n/2
> r = str(r)
> b = r+b
>    return b

No real comments other than you might consider putting
the code to pad with zeros in here. Then in the main code
you only need to convert the leftmost bit to 1 if negative...
In fact you could move that here too sonce arguably its
part of conversion...

> def signed_mag():
>    n = int(raw_input("Please enter a signed integer: "))
>    bits = int(raw_input("Please enter the number of bits: "))
>    count = conversion(n).count("0") + conversion(n).count("1") \

count = len(conversion(n))

But recall from above that conversion(n) returns an empty
string for negative numbers.

Also to save calling conversion(n) multiple times you could
introduce a new variable to store the result.

>     #count the amount of digits to know how many 0s to add
>    append_zeros = bits - count
>    if bits - 1 < count:
> print "Out of range."
>    else:
> if n < 0:
>     n = abs(n)

Now you change n so that conversion(n) will now
work on negative inputs...

>     if append_zeros > 0:
> print -n," is encoded as","1"+(append_zeros-4)*"0" \
> +conversion(n),"in Signed Magnitude."

This confused me, why are you subtracting 4? Surely you
just want to change a single bit?

> elif n > 0:
>     if append_zeros > 0:
> print n,"is encoded as","0" + (append_zeros-1)*"0" \
> +conversion(n),"in Signed Magnitude."

And why subtract 1 then add a "0"? Why not just append_zeros*"0"

> else:
>     print "That is not an valid signed interger."

Why is zero not a valid signed integer?

> I know the problem is at the '(append_zeros-4)' bit, but I'm not 
> sure what
> to change/add. Thanks in advance.

I think a problem may also be in the fact that the first call to
conversion(n) returns "" whereas subsequent calls return a
bit pattern.

In general it would be better to get your conversion function to 
all of the bit generation , padding and signing of the number. That 
leaves the presentation logic outside in signed_mag()


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list