Function to express an integer as its reciprocal in fraction form - python

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)

Related

How can I get Regex to remove redundancies and call itself again?

I have a simple function which when given an input like (x,y), it will return {{x},{x,y}}.
In the cases that x=y, it naturally returns {{x},{x,x}}.
I can't figure out how to get Regex to substitute 'x' in place of 'x,x'. But even if I could figure out how to do this, the expression would go from {{x},{x,x}} to {{x},{x}}, which itself would need to be substituted for {{x}}.
The closest I have gotten has been:
re.sub('([0-9]+),([0-9]+)',r'\1',string)
But this function will also turn {{x},{x,y}} into {{x},{x}}, which is not desired. Also you may notice that the function searches for numbers only, which is fine because I really only intend to be using numbers in the place of x and y; however, if there is a way to get it to work with any letter as well (lower case or capital) the would be even more ideal.
Note also that if I give my original function (x,y,z) it will read it as ((x,y),z) and thus return {{{{x},{x,y}}},{{{x},{x,y}},z}}, thus in the case that x=y=z, I would want to be able to have a Regex function call itself repeatedly to reduce this to {{{{x}}},{{{x}},x}} instead of {{{{x},{x,x}}},{{{x},{x,x}},x}}.
If it helps at all, this is essentially an attempt at making a translation (into sets) using the Kuratowski definition of an ordered pair.
Essentially to solve this you need recursion, or more simply, keep applying the regex in a loop until the replacement doesn't change the input string. For example using your regex from https://regex101.com/r/Yl1IJv/4:
s = '{{ab},{ab,ab}}'
while True:
news = re.sub(r'(?P<first>.?(\w+|\d+).?),(?P=first)', r'\g<1>', s, 0)
if news == s:
break
s = news
print(s)
Output
{{ab}}
Demo on rextester
With
s = '{{{{x},{x,x}}},{{{x},{x,x}},x}}'
The output is
{{{{x}}},{{{x}},x}}
as required. Demo on rextester

float() argument must be a string or a number, not '_sre.SRE_Match'

I'm writing some code to get raw HTML from a site, pinpoint a certain value which might change over time using regex and compare it with a value stored in a text file.
Everything works, apart from converting my regex object into a floating point number to allow comparison with another floating point number.
def find_new_value(): # retrieves value from website
cmc_html = requests.get('https://websitewithvalue.com')
noStarchSoup = bs4.BeautifulSoup(cmc_html.text,
features="html.parser")
return noStarchSoup
new_value = float(btc_regex2.search(str(find_new_value())))
leads to -
TypeError: float() argument must be a string or a number, not '_sre.SRE_Match'
print(new_value)
prints:
<_sre.SRE_Match object; span=(77, 85), match='10191.53'>
I want to use match='10191.53' from the object to perform arithmetic with it. How can I pick this value out from the object?
I've read the regex documentation and tried a number of different combinations of str() int() and float() functions to manipulate the object's value into eventually being float.
I can understand why float() can't be used on this, but not how to get the 10191.53 value from the object to use it in mathematical operations.
If your pattern matches exactly the string you want to convert to a float, you can call
result = regex.search(value)
new_value_str = result.group(0)
new_value = float(new_value_str)
to return the resulting match from your search as a string and convert it to a float (docs). m.group(0) returns the entire match as a string. Also see this answer.
As people have pointed out in the comments, you need to extract the captured group using
new_value.groups()
The output of this method depends on the syntax of your regular expression. In order for groups to work, you need to have capturing groups in you regular expression, otherwise groups will always be empty even if the expression was a match to the input.
TLDR;
Make sure your expression is capturing the text that you want, and extract it from the match using the method groups.

Display a number in scientific notation with specific digits

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

How to make binary to hex converter using for loop - Python

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].

Why do I get the u"xyz" format when I print a list of unicode strings in Python?

Please observe the following behavior:
a = u"foo"
b = u"b\xe1r" # \xe1 is an 'a' with an accent
s = [a, b]
print a, b
print s
for x in s: print x,
The result is:
foo bár
[u'foo', u'b\xe1r']
foo bár
When I just print the two values sitting in variables a and b, I get what I expect; when I put the string values in a list and print it, I get the unwanted u"xyz" form; finally, when I print values from the list with a loop, I get the first form again. Can someone please explain this seemingly odd behavior? I know there's probably a good reason.
When you print a list, you get the repr() of each element, lists aren't really meant to be printed, so python tries to print something representative of it's structure.
If you want to format it in any particular way, either be explicit about how you want it formatted, or override it's __repr__ method.
Objects in Python have two ways to be turned into strings: roughly speaking, str() produces human readable output, and repr() produces computer-readable output. When you print something, it uses str().
But the str() of a list uses the repr() of its elements.
You get this because lists can contain any number of elements, of mixed types. In the second case, instead of printing unicode strings, you're printing the list itself - which is very different than printing the list contents.
Since the list can contain anything, you get the u'foo' syntax. If you were using non-unicode strings, you'd see the 'foo' instead of just foo, as well.

Categories