Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I would like to convert birnary to in using own algorithm.
Here is the code:
binary=""
decimal=""
while binary!="exit":
decimal= input(">>")
decimal = decimal
if decimal!="0":
n = len(decimal) -1
n = pow(n, 2)
print(n)
Input:
1010
Bad Output:
9
When I enter binary and check them with calculator they arent true.
I dont have big clue how to make it so sorry for mistakes in code.
Thanks for reply
You need to move the input (where the user enters a binary number) outside the loop that's processing it. Then you have string containing ones (1) and zeros (0) which you can loop through.
Starting at the right-hand end of the string, multiply that number (1 or 0) by 1 (let's call this multiplier the ordinal) and save the result as total.
Multiply the ordinal by 2.
Grab the next number (from the right) from the input string and multiply it by the ordinal, add the result to total.
Keep going, multiplying the ordinal and using that to multiply the next number from the input string, until you run out of "numbers" in the input string.
Print total
First off, I think the line n = pow(n, 2) might be backwards from what you need. If you're converting binary digits, 2 is the base and n will be the power to raise it to, so you'll need n = pow(2, n).
Now, since you want to add up all the digits that are set to 1, you'll also need to add them to a new variable too. If you have more questions about this just ask here, and I'll see how I can help :)
Related
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 6 years ago.
Improve this question
How do I write recursive procedure for this?
N is an integer, and C<10. A procedure must return how many times digit C appers in N
I won't give you the full answer, but I'll help you get oriented.
To write recursive functions you need to think of two parts.
Base case - What is the simplest possible case you could handle? For this problem, that could be when N is a 1-digit number.
Recursive case - Let's say you can handle N-digit numbers. How can you solve N+1-digit numbers, using your 1-digit function and your N-digit function? The answer is, carve off one digit. Feed that digit to the 1-digit checker and the other N digits to the N-digit checker. (The "N-digit checker" is the very function you're writing.)
In pseudo-code, a recursive function is typically structured like so:
def recursive_function(n):
if is_base_case:
return base_case(n)
else:
return combine(
recursive_function(smaller(n)),
base_case(bite_sized_chunk(n))
)
Your job is to fill in:
The is_base_case test: is n one digit?
The base_case function, which handles only 1-digit numbers.
The smaller function, which gives you all but the last digit of n. If n is 1234, smaller(n) is 123.
The bite_sized_chunk function, which gives you the last digit of n. If n is 1234, bite_sized_chunk is 4.
The combine function, which combines the base case and recursive answers.
(None of these functions need to be actual separate functions. They can be inlined.)
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 6 years ago.
Improve this question
I want to perform a power operation combined with a modulo. I have trouble performing this pow() function with real numbers.
This works fine for integers:
pow(2,6000,400) = 176
However, this returns an error with real numbers:
pow(1.4142, 6000, 400)
I have tried also the math.pow() function but it doesn't
work either... how can I get this to work with real numbers ?
The python function pow() accepts 2 or 3 arguments. In your case, pow(x,y,z) does x power y and applies a modulo z to the result. But the documentation is explicit:
If the second argument is negative, the third argument must be
omitted. If z is present, x and y must be of integer types, and y must
be non-negative.
So:
Your first call works fine, because the arguments comply with the requirements. Note that despite pow(2,6000) being a huge number, the result of the combined modulo operation can be calculated easily without overflow, by using properties on modular exponentiation of integers.
Your second call fails with an error, because the first argument is not an integer. The workaround would be to decompose your operation into pow(1.4142,6000) % 400, because modulo is defined for real numbers. Unfortunately, pow(1.4142,6000) is too big and causes an overflow error. This is because contrary to the python integers which are of unlimited range, real numbers are limited by the range of the C floating point encoding.
P.S.: I assumed that it's about python and not VB, because VB's pow() accepts only 2 arguments.
Edit: hint for a workaround
Here a little workaround that makes use of the fact that technically, a floating point number is not a mathematical real of unlimited precision, but a rational number. We can then make use of the numerator and denominator and use integer operations to master the huge numbers:
n=pow(14142,6000) # take the first argument multiplied by a 10 exponent to make it an integer
d=pow(10000,6000) # keep track of this 10 exponent
i=n//d # integer division to compute the integral value
r=n-d*i # remainder of the integer division
precision=6 # precision
f=r*pow(10,precision)//d # keep the 6 most significant digits
result=(i%400)+(f/pow(10,precision))
The result is 271.048181 to the 6th digit. I let you as an exercise the writing of a function that performs this in a less artisanal way.
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 8 years ago.
Improve this question
Hi I have a somewhat strange question. I am converting a list of numbers (which represent physical measurements), where each are reported to some specified accuracy in arbitrary units depending on the study it comes from. Here is an example of what I mean:
[...,105.0,20.0,3.5,4.25,9.78,7.2,7.2]
These are of course of type:
<type 'numpy.float64'>.
If I print out the last number, for instance:
print list[-1]
>>> 7.2
However, if accessed in this way, I get:
7.2000000000000002
I understand that floats are by default 64 bits, so doing a calculation with them (i.e. - converting this list of measurements) returns a converted value which is 64 bits. Here is an example of the converted values:
[105.27878958,20.0281600192,3.47317185649,4.27596751688,9.82706595042,7.27448290596,7.26291009446]
Accessing them either way (using print or not), returns a 64 bit number. But clearly there is something else going on, otherwise the print function wouldn't really know how to display the true measurement. I would like to report the converted values to the same level of accuracy as the original measurements. Is there a way I can do this in python?
You have three problems:
1) How do I determine the number of decimal places in the input?
If your Python code literally says [...,105.0,20.0,3.5,4.25,9.78,7.2,7.2], you're out of luck. You've already lost the information you need.
If, instead, you have the list of numbers as some kind of input string, then you have the info you need. You probably already have code like:
for line in input_file:
data = [float(x) for x in line.split(',')]
You need to record the number of places to the right of the decimal before converting to float, for example:
for line in input_file:
places = [len(x.partition('.')[2]) for x in line.split(',')]
data = [float(x) for x in line.split(',')]
2) How do I store that information?
That's up to you. Sorry, I can't help you with that one without seeing your whole program.
3) How do I format the output to round to that number of decimal places?
Use the % operator or {}-style formatting, like so:
print '%.*f' % (places[i], data[i])
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
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
Improve this question
I have a number which I want to split into smaller numbers of equal length.
Suppose, I have the number 212313454
I, now want to split it into 3 numbers of 3 digits each:
212, 313 and 454
What if I want to randomly split it? I mean
212313454 into
213, 354, 114
Is there any way to do this?
You can use modulus operator % and division operator / and form the divisor as 10^n where n is number of digits in each result of split.
Convert them to a string and then split them. Like:
s = str(212313454)
a = s[0:3]
b = s[3:6]
c = s[6:]
Use a loop for a variable length number.
I'm sorry to ask but your question is vague (yes I know people have "answered" the question...).
"split [a number] into smaller numbers of equal length". Your example and hence everyone's answers assume you just have 9 decimal digits and want three smaller integers back, but what if you have a longer or shorter number, or want more/less subdivisions?
and randomly splitting "212313454 into 213, 354, 114". What is the correlation of these smaller numbers with the larger # exactly? 213 isn't in 212313454 if my eyes are working properly. If you want to pick random digits from an integer you can do that.
Lastly if you are just experimenting for fun, cool, but you should think a bit about making integers into strings and back and forth. A lot of math routines in python you should checkout are in the standard library, e.g. math module, random module, and bitwise operators too.
Im not going to write the code for you but here is a simple way to do it:
Make the int a string
split the string each 3 characters
once you do that iterate the list and turn the strings back into ints
I think you can figure it out if you try!
Good luck :)
The easiest way to convert the integer to a string adn then change it back to int again...
Here is how I would do...
Code:
c = 212313454
def splits(c,length):
l = [c[i:i+3] for i in range(0,len(c),3)]
print map(int,l)
if __name__=='__main__':
splits(str(c),3)
Output:
[212, 313, 454]
Hope this helps :)
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
How to convert number such as 24 to the two words "two", "four".
Quick way I thought of.
First you need a way to loop through the integer. You can try doing some weird diving by 10 and using the modulus of it... or just convert it to a string.
Then you can iterate through each 'number' in the string and use a simple lookup table to print out each number.
numberconverterlookup={'1':'one'
'2':'two'
'3':'three'
'4':'four'
'5':'five'
'6':'six'
'7':'seven'
'8':'eight'
'9':'nine'
'0':'zero'
}
number = 24
stringnumber = str(number)
for eachdigit in stringnumber:
print numberconverterlookup[eachdigit]
Note this only handles single digits and can't easily handle large numbers. Otherwise you'd have to write out each number in the lookup table by hand. That is very cumbersome.
Some key concepts are illustrated here:
Dictionary: This maps a 'key' to a 'value'. I.e. '1' maps to 'one'
For loop: This allows us to go through each digit in the number. In the case of 24, it will loop twice, once with eachdigit set to '2', and loops around again with eachdigit set to '4'. We cant loop through an integer because it is itself a single entity.
Typecasting: This converts the integer type 24 into a string '24'. A string is basically a list of individual characters grouped together, whereas an integer is a single entity.