Formatting in Python 2.7 - python

I have a column formatting issue:
from math import sqrt
n = raw_input("Example Number? ")
n = float(n)
sqaureRootOfN = sqrt(n)
print '-'*50
print ' # of Decimals', '\t', 'New Root', '\t', 'Percent error'
print '-'*50
for a in range(0,10):
preRoot = float(int(sqaureRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n*100
print ' ', a, '\t\t', newRoot, '\t\t', percentError, '%'
It comes out like:
Not in the same column!?!

#Bjorn has the right answer here, using the String.format specification. Python's string formatter has really powerful methods for aligning things properly. Here's an example:
from math import sqrt
n = raw_input("Example Number? ")
n = float(n)
sqaureRootOfN = sqrt(n)
print '-'*75
print ' # of Decimals', ' ' * 8, 'New Root', ' ' * 10, 'Percent error'
print '-'*75
for a in range(0,10):
preRoot = float(int(sqaureRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n*100
print " {: <20}{: <25}{: <18}".format(a, newRoot, str(percentError) + ' %')
Note that instead of tabs I'm using spaces to space things out. This is because tabs are really not what you want to use here, because the rules for how tabs space things are inconsistent (and depend on what your terminal/viewer settings are).
This is what the answer looks like:
---------------------------------------------------------------------------
# of Decimals New Root Percent error
---------------------------------------------------------------------------
0 9.0 18.1818181818 %
1 9.9 1.0 %
2 9.94 0.198383838384 %
3 9.949 0.0175747474747 %
4 9.9498 0.00149490909092 %
5 9.94987 8.7861717162e-05 %
6 9.949874 7.45871112931e-06 %
7 9.9498743 1.4284843602e-06 %
8 9.94987437 2.14314187048e-08 %
9 9.949874371 1.33066711409e-09 %

Using str.format,
import math
n = float(raw_input("Example Number? "))
squareRootOfN = math.sqrt(n)
print('''\
{dashes}
{d:<16}{r:<15}{p:<}
{dashes}'''.format(dashes = '-'*50, d = ' # of Decimals', r = 'New Root', p = 'Percent error'))
for a in range(0,10):
preRoot = float(int(squareRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n
print(' {d:<14}{r:<15}{p:13.9%}'.format(d = a, r = newRoot, p = percentError))
yields
--------------------------------------------------
# of Decimals New Root Percent error
--------------------------------------------------
0 9.0 18.181818182%
1 9.9 1.000000000%
2 9.94 0.198383838%
3 9.949 0.017574747%
4 9.9498 0.001494909%
5 9.94987 0.000087862%
6 9.949874 0.000007459%
7 9.9498743 0.000001428%
8 9.94987437 0.000000021%
9 9.949874371 0.000000001%
A few tricks/niceties:
Instead of three print statements, you can use one print statement on
a multiline string.
The percent symbol in the format {p:13.9%} lets you leave
percentError as a decimal (without multiplication by 100) and it
places the % at the end for you.

This is how tabs work. To get a correct formatting, you should use string.format. For your example, it could look like this:
print "{0:2d} {1:9.8f} {2:f} %".format(a, newRoot, percentError)

Related

How to place a number into a string?

I want to create the following function
Left_padded(n, width)
That returns, for example:
Left_padded(6, 4):
' 6' #number 6 into a 4 digits space
Left_padded(54, 5)
' 54' #number 54 into a 5 digits space
You can use rjust:
>>> def Left_padded(n, width):
... return str(n).rjust(width)
>>> Left_padded(54, 5)
' 54'
Assuming you want to put the number next to another string, you can also use % formatting to achieve the same result:
>>> w1 = "your number is:"
>>> num = 20
>>> line = '%s%10s' % (w1, num)
>>> print(line)
'your number is: 20'

python task: price in dollars and cents

As input, I have a number, price in dollars and cents (for example: 10.35) I need to print dollar and cents (based on above exmaple: 10 35). (input 10.09 - output 10 09
I created the code:
from math import floor, trunc
a = float(input())
r = trunc(a)
k = trunc(a * 100)
k = (k % 100)
if k <= 9:
print(r, "%02d" % (k,))
else:
print(r, k)
However, when I test it on automatic tester, one of the conditions is not working. I am not able to see input in the test, please could you tell me where do I have mistake?
You should test function not script. Problem probably caused by no correct test.
Try this:
from math import trunc
def to_new_format(price):
dolar_part = trunc(price)
cent_part = round(((price % 1) * 100), 3)
return "%i %i" % (dolar_part, cent_part)
input_price = float(input())
print(to_new_format(input_price))
If the input is a string 10.35 (as it seems to me) than you could also try the following (I know you were not asking this, but it might help nevertheless):
a = string(input())
b = a.split(".")
res = b[0] + " " + b[1]
print(res)
which outputs:
10 35

Python Gtin 8 Code not totaling

Hi I have been experimenting for some time to try and total 7 variables at once. I am trying to calculate the 8th number for GTIN 8 codes. I have tried many things and so far I am using float. I Don't know what it does but people say use it. I need to times the 1,3,5,7 number by 3 and 2,4,6 number by 1. Then find the total of all of them added together. I have looked everywhere and I cant find anything. Anything will help. Thanks Ben
code = input ("enter 7 digit code? ")
sum1 = 3 * (code[0] + ',')
sum2 = code[1] + ','
sum3 = 3 * (code[2] + ',')
sum4 = code[3] + ','
sum5 = 3 * (code[4] + ',')
sum6 = code[5] + ','
sum7 = 3 * (code[6] + ',')
checksum_value = sum1 + sum2 + sum3+ sum4 + sum5+ sum6 + sum7
b = str(checksum_value)
print(b)
Quick solution:
x = "1234567"
checksum_value = sum(int(v) * 3 if i in (0,2,4,6) else int(v) for (i, v) in enumerate(x[:7]))
# (1*3) + 2 + (3*3) + 4 + (5*3) + 6 + (7*3)
# ==
# 3 + 2 + 9 + 4 + 15 + 6 + 21
# ==
# sum(int(v) * 3 if i in (0,2,4,6) else int(v) for (i, v) in enumerate(x[:7]))
Explanation:
# Sum the contained items
sum(
# multiply by three if the index is 0,2,4 or 6
int(v) * 3 if i in (0,2,4,6) else int(v)
# grab our index `i` and value `v` from `enumerate()`
for (i, v) in
# Provide a list of (index, value) from the iterable
enumerate(
# use the first 7 elements
x[:7]
)
)
`enter code here`code = input ("enter 7 digit code? ")
sum1 = 3 * (code[0] + ',')
sum2 = code[1] + ','
sum3 = 3 * (code[2] + ',')
sum4 = code[3] + ','
sum5 = 3 * (code[4] + ',')
sum6 = code[5] + ','
sum7 = 3 * (code[6] + ',')
checksum_value = sum1 + sum2 + sum3+ sum4 + sum5+ sum6 + sum7
b = str(checksum_value)
print(b)
GS1 codes come in different lengths, ranging from GTIN-8 (8 digits) to SSCC (2 digit application ID + 18 digits). Here's a simple, general Python formula that works for any length GS1 identifier:
cd = lambda x: -sum(int(v) * [3,1][i%2] for i, v in enumerate(str(x)[::-1])) % 10
Explanation:
Convert input to string, so input can be numeric or string - just a convenience factor.
Reverse the string - simple way to align the 3x/1x pattern with variable-length input.
The weighting factor is selected based on odd and even input character position by calculating i mod 2. The last character in the input string (i=0 after the string has been reversed) gets 3x.
Calculate the negative weighted sum mod 10. Equivalent to the (10 - (sum mod 10)) mod 10 approach you'd get if you follow the GS1 manual calculation outline exactly, but that's ugly.
Test Cases
## GTIN-8
>>> cd(1234567)
0
>>> cd(9505000)
3
## GTIN-12
>>> cd(71941050001)
6
>>> cd('05042833241')
2
## GTIN-13
>>> cd(900223631103)
6
>>> cd(501234567890)
0
## GTIN-14
>>> cd(1038447886180)
4
>>> cd(1001234512345)
7
## SSCC (20 digits incl. application identifier)
>>> cd('0000718908562723189')
6
>>> cd('0037612345000001009')
1

How to duplicate lines in Python

I have print (5*"#"), which gives me:
#####
Now if I add \n to it, print (5*"#\n"), it gives me five lines consisting of one # each.
What do I do when I want it to give me this:
Four lines consisting of five # each without having to type ##### in the code?
I tried something like print(5*"#", 4*"\n") but it obviously didn't work.
You can use the following:
(5 * '#' + '\n') * 4
Note that this is much less clear than '#####\n' * 4.
How about you loop over the print statement 4 times?
for _ in range(4):
print(5 * '#')
Or, use + to append the newline, and multiply the result by 4:
print((5 * '#' + '\n') * 4)
Or, use a list and .join() the elements with newlines:
print('\n'.join([5 * '#'] * 4))
for x in [5 * "#"] * 4:
print x
or:
print "\n".join([5 * "#"] * 4)
one line version:
>>> print 4 * ("%s\n" % (5*"#"))
or
>>> print 4 * ( 5*"#" + "\n" )
multiline:
>>> for x in xrange(4):
print "#####"
#####
#####
#####
#####
You could do print "%s\n" % (5*"#")*4

Format a number as a string

How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?
a = str(52500)
b = str(5)
lengthDiff = len(a) - len(b)
formatted = '%s/%s' % (' '*lengthDiff + b, a)
# formatted looks like:' 5/52500'
Format operator:
>>> "%10d" % 5
' 5'
>>>
Using * spec, the field length can be an argument:
>>> "%*d" % (10,5)
' 5'
>>>
'%*s/%s' % (len(str(a)), b, a)
You can just use the %*d formatter to give a width. int(math.ceil(math.log(x, 10))) will give you the number of digits. The * modifier consumes a number, that number is an integer that means how many spaces to space by. So by doing '%*d' % (width, num)` you can specify the width AND render the number without any further python string manipulation.
Here is a solution using math.log to ascertain the length of the 'outof' number.
import math
num = 5
outof = 52500
formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof)
Another solution involves casting the outof number as a string and using len(), you can do that if you prefer:
num = 5
outof = 52500
formatted = '%*d/%d' % (len(str(outof)), num, outof)
See String Formatting Operations:
s = '%5i' % (5,)
You still have to dynamically build your formatting string by including the maximum length:
fmt = '%%%ii' % (len('52500'),)
s = fmt % (5,)
Not sure exactly what you're after, but this looks close:
>>> n = 50
>>> print "%5d" % n
50
If you want to be more dynamic, use something like rjust:
>>> big_number = 52500
>>> n = 50
>>> print ("%d" % n).rjust(len(str(52500)))
50
Or even:
>>> n = 50
>>> width = str(len(str(52500)))
>>> ('%' + width + 'd') % n
' 50'

Categories

Resources