need help in understanding a code - python

Can anyone explain this code a little. I can't understand what n does here? We already have taken N = int(input()) as input then why n=len(bin(N))-2? I couldn't figure it out.
N = int(input())
n = len(bin(N))-2
for i in range(1,N+1):
print(str(i).rjust(n) + " " + format(i,'o').rjust(n) + " " + format(i,'X').rjust(n) + " " + format(i,'b').rjust(n))

n counts the number of bits in the number N. bin() produces the binary representation (zeros and ones), as as string with the 0b prefix:
>>> bin(42)
'0b101010'
so len(bin(n)) takes the length of that output string, minus 2 to account for the prefix.
See the bin() documentation:
Convert an integer number to a binary string prefixed with “0b”.
The length is used to set the width of the columns (via str.rjust(), which adds spaces to the front of a string to create an output n characters wide). Knowing how many characters the widest binary representation needs is helpful here.
However, the same information can be gotten directly from the number, with the int.bitlength() method:
>>> N = 42
>>> N.bit_length()
6
>>> len(bin(N)) - 2
6
The other columns are also oversized for the numbers. You could instead calculate max widths for each column, and use str.format() or an f-string to do the formatting:
from math import log10
N = int(input())
decwidth = int(log10(N) + 1)
binwidth = N.bit_length()
hexwidth = (binwidth - 1) // 4 + 1
octwidth = (binwidth - 1) // 3 + 1
for i in range(1, N + 1):
print(f'{i:>{decwidth}d} {i:>{octwidth}o} {i:>{hexwidth}X} {i:>{binwidth}b}')

Related

Floating point number (base-10) to IEEE-754 32 bits converter's result is wrong

My floating point number (base-10) to IEEE-754 32 bits converter's answer is wrong and I'm not quite sure what is the reason. This is my code, please forgive me for the confusing variable names. I am new to coding.
I got this solution from this website.
https://www.wikihow.com/Convert-a-Number-from-Decimal-to-IEEE-754-Floating-Point-Representation
The result that it supposed to be :
0100001001101010010000000000000
The result that I got :
0100001001011110010000000000000
x = str(58.5625)
s = x.split(".")
a = int(s[0])
p = int(s[1])
q = "0." + str(p)
b = float(q)
front = ""
end = ""
while a > 0:
front += str(a % 2)
a //= 2
a = int(a)
while b != 1 and len(end) < 17:
b *= 2
end += str(b)[0]
b -= int(str(b)[0])
print(a, b)
print(front, end)
whole = front + "." + end
count = whole.find('.') - 1
ff = whole.split('.')
q1 = ff[0]
q2 = ff[1]
c = (q1 + q2)[1:]
te = float(x)
if te > 0:
signofnum = '0'
else :
signofnum = '1'
expobased = count + 127
exponent = ""
while expobased > 0:
exponent += str(expobased % 2)
expobased //= 2
expobased = int(expobased)
exponent = exponent[::-1]
mantissa = c
result = signofnum + exponent + mantissa
print(result)
Your front is backwards. The loop gets the bits from right-to-left (lowest/rightmost bit first, greatest/leftmost bit last) and appends them onto front, so the lowest bit goes on first, then the second lowest bit is appended on its right, and so on until the highest bit of the input is put as the rightmost bit of front. Fixing that gets the correct result for the sample value in the question. It can be fixed by changing front += str(a % 2) to front = str(a % 2) + front
Also, do not use:
s = x.split(".")
…
p = int(s[1])
The fraction part is not an integer, and converting it to an integer loses information about its position (leading zeros). To get b, the fraction part, simply subtract a (the integer part) from the original number. It is probably also preferable to obtain a as int(number); there is no need to convert to a string at all.

How to convert Bailey Borwein Plouffe algorithm from hex to decimal?

def S(j, n):
k = 0
s = 0
left_sum = 0
while (k <= n):
denominator = 8k + j
numerator = pow(16, n-k, denominator)
left_sum = (left_sum + (numerator / denominator)) % 1.0
k += 1
right_sum = 0
k = n + 1
newt = 0
while 1:
numerator = pow(16, n-k)
denominator = 8k + j
check = numerator / denominator
right_sum = newt + check
if right_sum == check:
break
else:
newt = right_sum
k += 1
result = left_sum + (right_sum % 1.0)
return result
def pi(n):
n -= 1
x = (4*S(1, n) - 2*S(4, n) - S(5, n) - S(6, n)) % 1.0
I'm trying to find the nth digit of pi using the Bailey Borwein Plouffe algorithm. Because the algorithm uses hexadecimal, I need to convert it back into decimal. I found some code on Python fiddle that seems to do this properly:
return "%014x" % int(x * 16**14)
Could someone explain what this return statement is doing? Thank you.
This does not convert to decimal. If anything, it converts a decimal value to a hexadecimal string.
This is string formatting, usually used for output. The format specification is on the left, before the % separator; the value is on the right.
Value: x * 16**14 is x, shifted left 14 hex digits.
Format: %...x specifies unsigned hexadecimal.
014 specifies a minimum of 14 columns, zero-padded.
The resulting string is returned to the calling program.
To convert to decimal, you'll need to
Fix your posted code. This still has syntax errors.
Alter the base-specific code from hex to dec. This starts with changing the power base from 16 to 10.
If you get stuck, you can post your coding problem. In that case, please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem.
We should be able to paste your posted code into a text file and reproduce the problem you described.

I have an int 123. How to produce a string "100+20+3" using python?

I have a int 123. I need to convert it to a string "100 + 20 + 3"
How can I achieve it using Python?
I am trying to divide the number first (with 100) and then multiple the quotient again with 100. This seems to be pretty inefficient. Is there another way which I can use?
a = 123
quot = 123//100
a1 = quot*100
I am repeating the above process for all the digits.
Another option would be to do it by the index of the digit:
def int_str(i):
digits = len(str(i))
result = []
for digit in range(digits):
result.append(str(i)[digit] + '0' * (digits - digit - 1))
print ' + '.join(result)
which gives:
>>> int_str(123)
100 + 20 + 3
This works by taking each digit and adding a number of zeroes equal to how many digits are after the current digit. (at index 0, and a length of 3, you have 3 - 0 - 1 remaining digits, so the first digit should have 2 zeroes after it.)
When the loop is done, I have a list ["100", "20", "3"] which I then use join to add the connecting " + "s.
(Ab)using list comprehension:
>>> num = 123
>>> ' + '.join([x + '0' * (len(str(num)) - i - 1) for i, x in enumerate(str(num))])
'100 + 20 + 3'
How it works:
iteration 0
Digit at index 0: '1'
+ ('0' * (num_digits - 1 - iter_count) = 2) = '100'
iteration 1
Digit at index 1: '2'
+ ('0' * 1) = '20'
iteration 2
Digit at index 2: '3'
+
('0' * 0) = '3'
Once you've created all the "numbers" and put them in the list, call join and combine them with the string predicate +.
Another way of achieving what you intended to do:
def pretty_print(a):
aa = str(a)
base = len(aa) - 1
for v in aa:
yield v + '0' * base
base -= 1
>>> ' + '.join(pretty_print(123))
'100 + 20 + 3'
Here's my approach:
numInput= 123
strNums= str(numInput)
numberList= []
for i in range(0,len(strNums)):
digit= (10**i)*int(strNums[-(i+1)])
numberList.append(str(digit))
final= "+".join(numberList)
print(final)
It's the mathematical approach for what you want.
In number system every digit can be denoted as the 10 to the power of the actual place plus number(counting from zero from right to left)
So we took a number and converted into a string. Then in a loop we decided the range of the iteration which is equal to the length of our number.
range: 0 to length of number
and we give that number of power to the 10, so we would get:
10^0, 10^1, 10^2...
Now we need this value to multiply with the digits right to left. So we used negative index. Then we appended the string value of the digit to an empty list because we need the result in a form as you said.
Hope it will be helpful to you.

Python Issue with Loops

I have designed a code which will take a 'number' as an input from the user.
The number will be used to make a...
numerator = (3*number) - 2
and a denominator, which will be denominator = (4*n) + 1.
The code will also allow the user to choose how many times they want this sequence to go on after which the sum of all the fractions will be totaled and displayed.
Here is the Code I have:
l=int(input("How many times do you repeat this sequence?: "))
n=int(input("Enter a base number: "))
n1=n
n2=n
total=0
s = ''
def calculate(l,n,n1,n2,total,s):
for j in range(l):
s += "{}/{} + ".format(3*n1-2, 4*n2+1)
n1=n+n1
n2=n+n2
total=(((n*3)-2)/((4*n)+1))+total
print(s)
print(total)
calculate(l, n, n1, n2, total, s)
Now here are the two errors that I receive when I get the output for this code for example:
How many times do you repeat this sequence?: 2
Enter a base number: 1
1/5 + 4/9 +
0.4
The two Issues:
Since 4/9 is the last fraction, is there a way to get rid of that "+" addition sign at the end, because it just points to a blank space..
The total for the two fractions shows to be 0.4 which is incorrect, the total sum should be 1/5 + 4/9 = 0.2 + 0.44 = 0.64, I am unsure where I went astray when inputting my total sum formula above.
Any suggestions/comments would be appreciated!
A cheap way of removing the + would be to simply cut off the last character in the string: str[:-1].
As far a issue 2 goes, it looks like you want to use n1 and n2 instead of n.
As of now, you're getting 1/5(.2) + 1/5(.2) = .4
Instead of concatening a string like that, collect all the parts in a list and then join the items on the plus sign:
s = []
s.append('{}/{}'.format(1, 5))
s.append('{}/{}'.format(4, 9))
print(' + '.join(s)) # 1/5 + 4/9
I’m not really sure what you are doing but if you want to get the sum of the fractions you print, you should just make sure that you calculate those individual fractions in the same way. So instead of incrementing n1 and n2 first before calculating the sum, calculate the sum in the same way you did for the fraction output and only afterwards change those variables:
s.append("{}/{}".format(3 * n1 - 2, 4 * n2 + 1))
total += (3 * n1 - 2) / (4 * n2 + 1)
n1 += n
n2 += n
I dont know python but you could do the following to correct your logical errors.
to remove the '+' at the end, you can do something like below,
if j = l (implies last fraction)
dont include +
else
include +
While calculating total you are using 'n' value which always remains as your input value
total=(((n*3)-2)/((4*n)+1))+total
Here use n1 or n2
total=(((n1*3)-2)/((4*n2)+1))+total

How to keep a number below n

I have a python program that outputs a list of coordinates that correspond to points in a survey. To keep this simple, I'm trying to make any coordinate above n (36) display something like: 1.8+36, which is 37.8, however 1x1.8 (same number) could also work, or any similar permutation... the coordinates are in lists (one for x and one for y). I currently use an if statement, but that obviously only works for numbers less than 72.
The simplest way is probably to use integer division and the modulus operator (which takes the remainder), so;
blocks = n // 36
small = n % 36
format_n = str(small) + ' + ' + str(blocks) + '*36'
Should give i + k*36, where i < 36 and k is an integer.
As long as your values remain below 1296 (36*36), you can divide your number by 36 and represent it as this number into 36.
input_1 = 105
output_1 = (105 * 1.0) / 36 # 2.197
print '36*' + output_1 # 36*2.197
n = float(input())
if n > 36:
result = str(n -36) + "+36"
else:
result = n
print(result)
this outputs the remainder of n-36, and then +36, for example if n is 124.79, 88.79+36 is outputted.

Categories

Resources