i want to display numbers in scientific notation:
-407.45833
So far i used this:
i = '%E' % Decimal(i)
result:
-4.074583E+02
now my question: how can i add one more digit so it looks like this:?
-4.074583E+002
I know i should find my answer in the tables from Python string formatting to select the proper format layout, but i cant find it. Can someone tell me the result and where to find it please?
There's unfortunately not any direct way using string formatting to have three digits following the +. A easy method to replace it is to use this since what we know is that is exponential forms are all stored as strings, so all the string methods will work on it.
I wrote a little function that takes a regular scientific notation and returns a formatted notation with three digits after the +:
from decimal import Decimal
def pretty(notation, n):
if '+' in notation:
return "+".join([notation.split('+')[0],notation.split('+')[1].zfill(n)])
return "-".join([notation.split('-')[0],notation.split('-')[1].zfill(n)])
i = '%E' % Decimal(-407.45833)
print(pretty(i,3)) # leave three digits
Related
It is easy to format the base of a number in python, but the exponent displays two digits by default. However, I would like to display only on digit (i.e. without the leading zero). See this example:
x=1.25e-5
s=f'{x:.2e}'
s will read '1.25e-04', however, I would like it to be '1.25e-4'.
How can I do this?
If you don't mind using external packages, this can be done using numpy.format_float_scientific
namely you can
import numpy as np
x = 1.25e-5
s = np.format_float_scientific(x,exp_digits=1)
Try this:
format(x).replace("E-0", "E-")
Actually this might be better
(x).ToString("0.#E+0");
I am writing a small function that turns a integer into its reciprocal in its fraction form. This is how I've defined my function so far:
def reciprocal (number):
return "1/",number
This sort of works but the problem is that it doesn't print the answer on the screen as I'd like to because say i did print reciprocal(3) it would show ('1/', 3) on the screen instead of 1/3. I have tried all sorts of combinations of speech marks and brackets in the code but the answer has still got extra brackets and back-ticks around it. I am using python 2.7.10, is there any way to get rid of these? Or is there any other simple way to express an integer as its reciprocal in fraction form that would get rid of them? Thank you
Yes. Because what this line is actually doing is returning a tuple:
return "1/",number
If you simply print:
type(reciprocal(3))
You will see the result will be tuple.
In order to keep the functionality of:
print(reciprocal(3))
You would want to do something like this instead:
return "1/{}".format(number)
Now, the above will actually return you a string instead of a tuple. The above is using the string format method, which you can read about here. Ultimately what you are doing is creating a string that will look like 1/x, where x will be number. The way to denote the x is by using the curly braces which is then used a placeholder that will set whatever you passed to format. Read more in the documentation to understand how it works.
To help expand it, what it actually looks like when separated is this:
s = "1/"
Now, you want to be able to set your argument number. The string object supports several methods, one of which, is format. So you can actually simply call it: s.format(). However, that won't simply work the way you want it. So, per the documentation, in order to use this format method, you need to set in your string where exactly you want to set your argument that you want to place in your string. This is done by using the placeholder characters {} to indicate this. So:
s = "1/"
Will now be
s = "1/{}".format(number)
We set our {} as the placeholder of where we want number to be, and we assigned what will be in that placeholder by passing number to format.
You can further see how now you have a string if you in fact print the type of the result:
print(type(reciprocal(3)))
You will see it is now a str type.
As a note in Python, you can create a tuple with comma separated values:
>>> d = 1, 2
>>> type(d)
<class 'tuple'>
This is exactly why your function returns the tuple, because of the fact you are returning two values simply separated by a comma.
You can try this:
def reciprocal (number):
return "1/{}".format(number)
print reciprocal(4)
print reciprocal(100)
Output:
1/4
1/100
Right now you're returning a tuple made of the string "1/" and your number because of the comma. I think what you want to do is return just a string.
Something like return "1/" + str(number)
First of all, this is not for any class.
I have been working on these 2 programs for a long time and cannot make heads or tails of it. I really want to get past these problems so I can move onto other lessons.
"Create a function that transforms the prefix notation into postfix notation, and postfix notation into prefix notation. The function takes two arguments. The first is a string of an expression without spaces or syntax errors, and the second is another string contains all the operators. Characters not in the second string are regarded as operands. The lengths of all the operators and operands are 1, and all the operators are binary operators."
ex:
>>> fix_trans('ab33c2c11','abc')
'33b211cca'
and Convert to (reverse) Polish notation:
>>> toPolish('(3+5)*(7-2)',D,0)
'*+35-72'
Can you provide any examples of how far you've gotten with this, or what methods haven't worked for you? Also, are you familiar with the shunting-yard algorithm?
def parse(expression):
operators= set("*/+-")
numbers= set("0123456789")#not used anywhere as of now
opExtrapolate= []
numExtrapolate= []
buff=[]
for i in expression:
if i in operators:
if len(buff) >0: #prevents buff if multiple operators
numExtrapolate.append(''.join(buff))
buff= []
opExtrapolate.append(i)
opExtrapolation=opExtrapolate
else:
buff.append(i)
numExtrapolate.append(''.join(buff))
numExtrapolation=numExtrapolate
print(numExtrapolation)
print("z:", len(opExtrapolation))
return numExtrapolation, opExtrapolation
def errors():
numExtrapolation,opExtrapolation=parse(expression)
#Error for muliple operators
if (len(numExtrapolation) ==3) and (len(opExtrapolation) !=2):
print("Bad1")
if (len(numExtrapolation) ==2) and (len(opExtrapolation) !=1):
print("Bad2")
#
I posted similar code in an older question however the premise for questions is different in this post.
The code above takes a mathematical input entered in a variable expression by the user and it splits it into operands and operators. The errors function will later print errors if the input is incorrect.
Input would look something like this , where the operators can only be in the set("*/+-") and operands are real numbers. so an example input would be 45/23+233
With the help of an SO user I was able to get one of the errors to work(error for multiple operators), but I am having trouble implementing a few more error messages.
1)If the input contains items that are not numbers or not the allowed operators then an error message is displayed
2)If a user enters a number such as .23 or something like 554. where there is no number before the decimal place or after the decimal place then a different error is displayed.(note that a number like 0.23 is fine).
3)If the user attempts to divide by zero an error is displayed.
::What I have tried:
In the else statement of parse(), I tried to put conditions on buff.append(i) so that it would only run that code if buff.isdigit()==true but I got errors saying that there were no digits in buff. I also tried creating a set called "numbers"(in code below) and limiting buff.append(i) to that set through a for statement similar to the initial for statement. But unfortunately nothing worked. Any and all help would be appreciated.
Please don't introduce large amounts of code more advanced than the code below. I am trying to fix a problem, not completely change my code. Thanks for all your help.
You can use regular expressions to do these checks:
If the input contains items that are not numbers or not the allowed operators then an error message is displayed
if not re.match(r'[\d.*/+\- ]+$', expression):
print("Bad3") # Characters exist that are not allowed
Explanation: [\d.*/+\- ] will only match digits, your operators, and spaces, the + means to allow one or more of those characters, and the $ matches at the very end of the string. re.match() starts at the beginning of the string so this means that only those characters are allowed.
If a user enters a number such as .23 or something like 554. where there is no number before the decimal place or after the decimal place then a different error is displayed.(note that a number like 0.23 is fine).
if re.search(r'(?<!\d)\.|\.(?!\d)', expression):
print("Bad4") # There is a '.' without a digit before or after it
Explanation: \. in a regex matches a literal '.' character. The | in the middle is an alternation, so the regex will match if the expression on either side of it matches. (?<!\d) means that the previous character is not a number, and (?!\d) means that the next character is not a number, so this regex means "match a '.' that is not preceeded by a digit OR match a '.' that is not followed by a digit".
If the user attempts to divide by zero an error is displayed.
if re.search(r'/ *[0.]+(?![.\d])', expression):
print("Bad5") # Division by 0
Explanation: This matches / followed by any number of spaces, then one or more 0 or . characters, so this will match if anywhere in expression you have something like / 0, / 0.0, or / 0.00. The (?![.\d]) means that the next character can't be a digit or ., which will prevent you from matching something like / 0.4.
I will give you some indications, but not solve it for you :).
If you need more, ask a precise question and I'll answer it.
The answers I give you are NOT directly related with your code.
You can test if a string variable can be an integer by trying to cast it :
try:
var2 = int(var)
I let you see what Error it gives
For a version that doesn't use try, you can look at the isdigit method
You can see if a string variable if one of your operator by checking it
if (var in ["+", "-", "/", "*"])
to check even more, you can look at the variable's length first
if len(var) != and ... see above
To check if a user inputs something like .543 and refuse it, and can look at the first element of your string variable :
if myvar[0] is ".":
To check if your user wants to divide by 0, you can simply check whether the last number is equals to 0
if int(myvar) == 0:
All these expect you to be able to get operators and numbers first though.
The other solution would be to use regular expressions to perform these checks before parsing your numbers and operators.
It seems quite complex compared to the exercise you are trying to achieve though as it is homework. Might be a good idea to look at them anyway.
Yes, this is homework.
I have the basic idea. I know that basically I need to introduce a for loop and set if's saying if the value is above 9 then it's a, b, c, and so forth. But what I need is to get the for loop to grab the integer and its index number to calculate and go back and forth and then print out the hex. by the way its an 8 bit binary number and has to come out in two digit hex form.
thanks a lot!!
I'm assuming that you have a string containing the binary data.
In Python, you can iterate over all sorts of things, strings included. It becomes as simple as this:
for char in mystring:
pass
And replace pass with your suite (a term meaning a "block" of code). At this point, char will be a single-character string. Nice an straight forward.
For getting the character ordinal, investigate ord (find help for it yourself, it's not hard and it's good practice).
For converting the number to hex, you could use % string formatting with '%x', which will produce a value like '9f', or you could use the hex function, which will produce a value like '0x9f'; there are other ways, too.
If you can't figure any thing out, ask; but try to work it out first. It's your homework. :-)
So assuming that you've got the binary number in a string, you will want to have an index variable that gets incremented with each iteration of the for loop. I'm not going to give you the exact code, but consider this:
Python's for loop is designed to set the index variable (for index in list) to each value of a list of values.
You can use the range function to generate a list of numbers (say, from 0 to 7).
You can get the character at a given index in a string by using e.g. binary[index].