Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm taking an introductory Python course and we have an assignment that asks us to simulate the way the floating point numbers are stored.
Basically, we have to demonstrate 5 digits of Mantissa. For example, you input 123 and it must come out as 12300. If you input 12345678 it must come out as 12345. How can this be done? Is there a function for that or is it just a formmating issue? Keep in mind, this is an introductory course and we're not allowed to use any external libraries.
You can use Python's string formatting functionality:
'{:<05d}'.format(number)[:5]
Some examples:
>>> '{:<05d}'.format(123)[:5]
'12300'
>>> '{:<05d}'.format(12345678)[:5]
'12345'
Some clarification:
< says: align the number on the left.
0 says: use 0 as padding character.
5 says: set the width to at least five.
d says: it's a decimal.
As the number can be longer than five digits we take only the first five characters by doing [:5]. This is called slice notation and it allows you to take a slice of a string.
So, let's try taking the problem, and writing the rough framework of what we have to do. Notice that whenever I run into a problem that isn't immediately obvious, I push it into its own function, which I can deal with later:
string = str(number)
if len(string) > 5:
string = truncate_string(string)
elif len(string) < 5:
string = pad_string_with_zeros(string)
So, let's try implementing truncate_string and pad_string_with_zeros.
A string is basically a list of characters. How would we get the first 5 elements of a list? Through list slicing. Therefore, we can implement truncate_string like so:
def truncate_string(string):
return string[:5]
How do we pad strings with zeros? Well, if you consult the Python documentation, you could use the ljust function:
>>> '11'.ljust(5, '0')
'11000'
>>> '12345678'.ljust(5, '0')
'12345'
Therefore, our function could be:
def pad_string_with_zeros(string):
return string.ljust(5, '0')
Alternatively, we could have used a while loop:
def pad_string_with_zeros(string):
while len(string) < 5:
string += '0'
...although that'll be more inefficient.
If we move all our functions into the main code, then we might get something like this:
string = str(number)
if len(string) > 5:
string = string[:5]
elif len(string) < 5:
string = string.ljust(5, '0')
As it turns out, list slicing will not throw errors, even if you pass in too small or too large strings. For example, '12'[:5] will result in the string '12'.
Therefore, we don't need to even check for the size of the string, and can compact it down to the following lines:
string = str(number)
string = string[:5].ljust(5, '0')
Related
I have a bunch of floating point numbers that are either x.0 or x.5 and if they are x.0 I want no decimal points displayed, and if they are x.5 I want one decimal point displayed.
I have come up with a one-liner that does the job:
f'{x:+.{int(bool(x % 1))}f}'
Where int(bool(x % 1)) will always be 0 or 1 depending on whether modulo yields a remainder.
This works fine because of the nature of my float inputs, but it got me thinking, what if my inputs weren't so neat? For example the above one-liner with 10.01 as an input returns 10.0. My temptation is to first round the float to the desired precision:
f'{x:+.{int(bool(round(x, 1) % 1))}f}'
If there wasn't already a lot going on inside the f-string in my first example, there is now.
To be clear about my question:
Firstly, is my first method the 'right' way to go about what I'm actually trying to achieve given my real-world inputs?
Secondly, how about in the case of the hypothetical problem and my second example?
Thirdly, I'd like to canvas opinion from the community regarding where use of f-string crosses the line to abuse. As an example of how one might be tempted to pack a lot of stuff into the f-string, how about something like this to get a list of strings containing numbers to sort alphabetically:
f"String with number:{' ' if x >= 1000 else ' ' if x >= 100 else ' ' if x >= 10 else ' '}{x:+.{int(bool(round(x, 1) % 1))}f}"
So I hope tying this question about overuse of f-string in with my rounding question doesn't cause the overall question to be too vague, but these are two issues that I'm considering together. I suppose the 'neatness' of f-string can provide a temptation to shoehorn everything into one-liners.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I try to find a way to check if number contains "2" "3" "4" "5";
So 1234 meaning is "false" and 0110 meaning is true.
I try convert float to string and check with .find() but it's too long and i can't convert properly.
a = Decimal(1) / Decimal(123456789)
print a
8.100000073710000670761006104E-9
a = str(a)
print a
8.100000073710000670761006104E-9
So please help me (:
edit:
I have a calculation formula and want to refine results. so i can use result as an input and calculate original number.
it's some kind of encription algoritm and need special number set.
for example
9,9989001209866914639389667136615e-8
is in my set cause
1 / 9,9989001209866914639389667136615e-8 = 10001100
1 / 10001100 = 9,9989001209866914639389667136615e-8
also, number source has been generated seperately. i try to read source and refine only accepted numbers.
To divide these numbers and getting rid of scientific notation, I used the following code:
from decimal import *
a = '{0:f}'.format(Decimal(1)/Decimal(123456789))
print a.find('1234')
print a.find('810')
I am not sure of the conditions of your search in the string. But I hope that would be helpful.
I don't understand your initial problem description. If you meant whether the reciprocal of a number contains those digits, one issue is that the majority of such results have an infinite number of digits. Writing a number like 0110 complicates matters further because that's octal in Python 2 (invalid in Python 3); its value is 72.
But one thing I can easily adress, the "too long" part. You can request arbitrary (but still finite) precision from Decimal:
>>> f='{:f}'.format(decimal.Context(prec=200).divide(1,1234))
>>> f[:40]
'0.00081037277147487844408427876823338735'
>>> f.index('00810372')
3
>>> f.index('00810372', 3+1)
91
So as it happens, the digit stream of 1/1234 repeats after 88 decimal digits. All rationals have some such loop length (1/123456789 loops after 6855006 digits). But the default Decimal context didn't produce enough digits to observe the entire loop for this number.
A proper solution to this challenge would probably involve performing the long division explicitly, and tracking the fractions encountered along the way. Then you can easily detect when you find a repetition. Something along the lines of (probably slow):
fractions=set()
digits=[]
while fraction not in fractions:
digit = math.floor(fraction)
fractions.add(fraction)
digits.append(digit)
fraction = (fraction-digit)*10
If I understand your problem well, you could try using regular expressions. Here's an interactive way to play around with regular expressions given your problem: https://regex101.com/r/i2mZmK/2/
And a potential solution in python:
import re
from decimal import *
regex = re.compile(r"(2|3|4|5)")
a = Decimal(1) / Decimal(123456789)
def check_number():
result = regex.search(str(a))
if result is None:
check = True
else:
check = False
return check
print(check_number())
def returnsomething():
demo_number = 345.43565
list = [2, 3, 4]
for number in list:
if str(number) in str(demo_number):
return True
return False
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm writing my first python game and trying to incorporate two extra elements but I'm unsure how to write it.
1: The idea is that the game will generate a random three digit number with the inbuilt random module (ie. 123) and the user will have 23 tries to guess the correct numbers. It will initiate by asking the user to input three digits between 0-9. I want to create a hint system so that the user knows if they are on the right track. See the example in the link below (I can't embed images apparently).
Click to see example Input/Output for hints
A "W" indicates that all of the characters in the guess are wrong.
One or more "X"s indicates that they have a correct character, but in an incorrect position
One or more "R"s indicates they have a correct character in the right position
To get this kind of hint will I need to create 3 separate numbers and combine them together to form the target number or will I still be able to do it with the following code:
target = random.randint(111, 999)
I've started writing a function that takes in the variables guess (this is what the user has entered) and target (the generated number):
def get_hint(guess, target):
This is as far as I have gotten with it. Laughable, I know. I literally have no idea if it even possible to create this hint system.
2: I would also like it to have a points system where the points start at 10000 (if the user guesses correctly first try) and decreases by 10% each incorrect guess (second guess = 9000, third guess = 8100, etc.) to two decimal places. I have it incrementing a count for the amount of guesses the user has tried so when they guess the correct number the following happens:
if guess == target:
print("Congratulations!")
print("{} was the correct answer!".format(target))
print("You guessed the correct answer in {} tries and scored {} points.".format(tries, points))
First the point system is fairly trivial: just have a score varible and modify it at each round score=score*0.9 and round it to 2 decimals when printing with "{:.2f}".format(score)
Regarding the hint system :
Having a list of three numbers will be far easier to deal with so I'll assume target and guess have one of the following format "123" or [1,2,3] (as strings can be indexed as lists)
The tricky part is doing the right comparisons because you have take care of what digit have already been matched against the target in order to give only "r" in the example case of guess=113 and target=333. Here is a function that does the job:
def hint(guess,target):
if guess == target:
print("win")
else:
#we store a list to keep track of the numbers
#already matched so we don't count them twice as x and r
r=[0]*len(target)
#first we check if there's a direct match
for i,n in enumerate(guess):
if guess[i] == target[i]:
r[i]=1
#we make new lists without the digits that matched
stripped_guess=[n for i,n in enumerate(guess) if r[i] == 0]
stripped_target=[n for i,n in enumerate(target) if r[i] == 0]
#we will now try to count the amount of x
x=0
for n in set(stripped_guess):
#we count how many time that given digit appears
# in the two lists, the smallest is our x amount
x+=min(stripped_guess.count(n),stripped_target.count(n))
if sum(r) == 0 and x == 0:
print("w")
else:
print("r"*sum(r)+"x"*x)
Some tests:
>>> hint(guess="404",target="404")
win
>>> hint("135","331")
rx
>>>hint("11123","12133")
rrrx
If you have a three-digit number in variable num, you can peel away the digits:
In [1]: num = 347
In [2]: num % 10
Out[2]: 7
In [3]: (num % 100) // 10
Out[3]: 4
In [4]: (num % 1000) // 100
Out[4]: 3
Then you can compare digits and place your Xs and Rs.
I've been working on some homework I've been given and I've ran into a couple problems. I'm hoping someone can shed some light on them and perhaps give me some examples to help aide me.
My first question deals with binary operators in python.
Problem #13: Python supports 18 different binary operators. Experiment with each of these, using arguments that are both integer, both floating point, and both string. Not all operators work with each argument type. Fill in the following table. For each operator, provide either a short description and indicate the type of the result or the words “not legal”.
Operator Integer Floating point String
+
-
*
**
/
%
<<
>>
&
|
^
<
>
<=
>=
==
!=
<>
In this example we're supposed to explain how to operator works as an integer, float point and a string. What confuses me is the float and string aspect, using the addition portion as an example:
Would the integer aspect be something like x=3 y=4 x+y=answer (to show as an integer)? If so how would I go about showing examples of the float and string portion.
My second question deals with string splitting
Problem #20: Each row in the following table consists of a starting word and an ending word. Assign the starting word to the name w. Then using only indexing and slicing commands, convert the starting word into the ending word.
Starting word Ending word Command
w=’kyoto’ ‘tokyo’ w[3:]+w[:3]
w=’bread’ ‘bead’ w[0]+w[2:]
w=’kartasura’ ‘surakarta’ w[5:]+w[:5]
w=’listen’ ‘silent’
As you can see I've completed the first three which seemed relatively simple, I had to rearrange the words. The final one confuses me because I am not longer flipping the back with the front or vise versa. Instead I am rotating sections, now I am rotating lis to sil and ten to ent and I'm not exactly sure how to rotate letters.
Any help would be greatly appreciated, TY.
What confuses me is the float and string aspect, using the addition portion as an example?
3 + 4
3.5 + 4.25
'hello' + ' world'
The final one confuses me because I am not longer flipping the back with the front or vise versa.
w[2::-1] + w[4:6] + w[3]
There's probably someone else who asked a similar question, but I didn't take much time to search for this, so just point me to it if someone's already answered this.
I'm trying to take an integer (or long) and turn it into a string, in a very specific way.
The goal is essentially to split the integer into 8-bit segments, then take each of those segments and get the corresponding ASCII character for that chunk, then glue the chunks together.
This is easy to implement, but I'm not sure I'm going about it in the most efficient way.
>>> def stringify(integer):
output = ""
part = integer & 255
while integer != 0:
output += chr(part)
integer = integer >> 8
return output
>>> stringify(10)
'\n'
>>> stringify(10 << 8 | 10)
'\n\n'
>>> stringify(32)
' '
Is there a more efficient way to do this?
Is this built into Python?
EDIT:
Also, as this will be run sequentially in a tight loop, is there some way to streamline it for such use?
>>> for n in xrange(1000): ## EXAMPLE!
print stringify(n)
...
struct can easily do this for integers up to 64 bits in size. Any larger will require you to carve the number up first.
>>> struct.pack('>Q', 12345678901234567890)
'\xabT\xa9\x8c\xeb\x1f\n\xd2'