Converting decimal number to binary in Python - python

I am writing a program that converts a decimal number into a binary. I made it that far and I stuck with a problem. In the code with print(aa).
I tried to get a binary form of given number but it prints 1. I think I have "return" function problem here how can I solve it. Also, when I print binaryform it prints like the way below. Shouldn't it print reversely I mean first 1 and then 11 and then 111 .......10111.
# Python program to convert decimal number into binary number using recursive function
def binary(n, binaryform,i):
if n >= 1:
digit= n % 2
binaryform += digit*i
#print(binaryform)
i*=10
binary(n/2, binaryform, i)
print("xxx", binaryform)
return binaryform
dec = int(input("Enter an integer: "))# Take decimal number from user
aa = binary(dec, 0, 1)
print(aa)
OUTPUT:
Enter an integer: 23
('xxx', 10111)
('xxx', 111)
('xxx', 111)
('xxx', 11)
('xxx', 1)
1

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer. Python Documentation

You're writing a recursive function - that's fun and good.
Now consider what you do: you check the LOW part of the number. If the LOW part of the number is 1 or 0 you do something, but then you shrink the number and recurse, checking a new LOW part, but the new low part came from a HIGHER part originally.
So whatever you determine should actually be at the end of the string, not the beginning, when you come back from recursion.
That's your question about printing reversely, I think. And yes, except you should just assemble it reversely, and then print it normally.
Also, you're actually trying to construct a decimal integer that will print out as if it were a binary number. It would be a lot simpler if you just constructed a string: "10101".

If you just want to convert integer to binary, try this code here . It looks like this :
def binary(n):
b = ''
while n > 0:
b = str(n % 2) + b
n >>= 1
print(b)
binary(10)

Related

How to convert an integer from any base to any other base?

I am trying to do something that will convert any base to any other base without using decimal converting.
For example program will ask from user:
"Please put number which you would like to convert: 101"
"Please write from which base you want to convert: 2 " #base(2)
"Please write to which base you want to convert: 6" #base(6)
and will return value which converted from base(2) to base(6)
"Here is the result: 5"
You don't convert integers from one base to another. The integer doesn't change. You render an integer into a representation.
A normal (conventional) number is not, technically, a "decimal" number. It is a decimal representation of a number. Likewise for binary, octal, hexadecimal, etc.
For converting string representations of integers into any base between 2 and 36 you can simply use the int() built-in function with its extra (optional) argument. Python assumes a reasonably intuitive sequence of the letters 'a' through 'z' to represent "digits" greater than 9.
For example: int('101101',2) -> 45 and int('101101',3) -> 280 and so on.
For rendering an integer into binary, octal or hexadecimal one can simply use Python's built-in string formatting (though binary and perhaps octal were added sometime after version 2.2 of CPython ... and I don't remember the details).
It is, perhaps, not coincidental that Python's standard library definition of string.literal is returned in precisely the correct sequence to be used for any base up to 36 ... and one could, conceivably, use it to render integers into bases up through 99 ... though the notion of number representations where 'a' and 'A' are distinct digits along with spaces, newlines, etc. is a bit of a mind bender.
I have a naive approach, converting the number to base 10, our checkpoint, and then from ten.
def base(k,b,n):
def to_ten(k,b):
index = [
'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
]
k = str(k)[::-1]
r = 0
for i in range(len(k)):
r += (b**i)*int(index.index(k[i]))
return r
def from_base(k,b):
r = ""
while k>0:
d = int(k%b)
if d<10:
r += str(d)
else:
r += chr(ord('A')+d-10)
k //= b
r = r[::-1]
return r
return from_base(to_ten(k,b),n)
k = input('Insert the number you\'d like to convert: ')
b = int(input('Insert the base you\'d like to convert ' + k + ' from: '))
n = int(input('Insert the base you\'d like to convert to: '))
print('Your answer is: ' + str(base(k,b,n)))
Please tell me if the code does not work.

Exact Value after Floating point not rounding up [duplicate]

I want to remove digits from a float to have a fixed number of digits after the dot, like:
1.923328437452 → 1.923
I need to output as a string to another function, not print.
Also I want to ignore the lost digits, not round them.
round(1.923328437452, 3)
See Python's documentation on the standard types. You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.
First, the function, for those who just want some copy-and-paste code:
def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '{}'.format(f)
if 'e' in s or 'E' in s:
return '{0:.{1}f}'.format(f, n)
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])
This is valid in Python 2.7 and 3.1+. For older versions, it's not possible to get the same "intelligent rounding" effect (at least, not without a lot of complicated code), but rounding to 12 decimal places before truncation will work much of the time:
def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '%.12f' % f
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])
Explanation
The core of the underlying method is to convert the value to a string at full precision and then just chop off everything beyond the desired number of characters. The latter step is easy; it can be done either with string manipulation
i, p, d = s.partition('.')
'.'.join([i, (d+'0'*n)[:n]])
or the decimal module
str(Decimal(s).quantize(Decimal((0, (1,), -n)), rounding=ROUND_DOWN))
The first step, converting to a string, is quite difficult because there are some pairs of floating point literals (i.e. what you write in the source code) which both produce the same binary representation and yet should be truncated differently. For example, consider 0.3 and 0.29999999999999998. If you write 0.3 in a Python program, the compiler encodes it using the IEEE floating-point format into the sequence of bits (assuming a 64-bit float)
0011111111010011001100110011001100110011001100110011001100110011
This is the closest value to 0.3 that can accurately be represented as an IEEE float. But if you write 0.29999999999999998 in a Python program, the compiler translates it into exactly the same value. In one case, you meant it to be truncated (to one digit) as 0.3, whereas in the other case you meant it to be truncated as 0.2, but Python can only give one answer. This is a fundamental limitation of Python, or indeed any programming language without lazy evaluation. The truncation function only has access to the binary value stored in the computer's memory, not the string you actually typed into the source code.1
If you decode the sequence of bits back into a decimal number, again using the IEEE 64-bit floating-point format, you get
0.2999999999999999888977697537484345957637...
so a naive implementation would come up with 0.2 even though that's probably not what you want. For more on floating-point representation error, see the Python tutorial.
It's very rare to be working with a floating-point value that is so close to a round number and yet is intentionally not equal to that round number. So when truncating, it probably makes sense to choose the "nicest" decimal representation out of all that could correspond to the value in memory. Python 2.7 and up (but not 3.0) includes a sophisticated algorithm to do just that, which we can access through the default string formatting operation.
'{}'.format(f)
The only caveat is that this acts like a g format specification, in the sense that it uses exponential notation (1.23e+4) if the number is large or small enough. So the method has to catch this case and handle it differently. There are a few cases where using an f format specification instead causes a problem, such as trying to truncate 3e-10 to 28 digits of precision (it produces 0.0000000002999999999999999980), and I'm not yet sure how best to handle those.
If you actually are working with floats that are very close to round numbers but intentionally not equal to them (like 0.29999999999999998 or 99.959999999999994), this will produce some false positives, i.e. it'll round numbers that you didn't want rounded. In that case the solution is to specify a fixed precision.
'{0:.{1}f}'.format(f, sys.float_info.dig + n + 2)
The number of digits of precision to use here doesn't really matter, it only needs to be large enough to ensure that any rounding performed in the string conversion doesn't "bump up" the value to its nice decimal representation. I think sys.float_info.dig + n + 2 may be enough in all cases, but if not that 2 might have to be increased, and it doesn't hurt to do so.
In earlier versions of Python (up to 2.6, or 3.0), the floating point number formatting was a lot more crude, and would regularly produce things like
>>> 1.1
1.1000000000000001
If this is your situation, if you do want to use "nice" decimal representations for truncation, all you can do (as far as I know) is pick some number of digits, less than the full precision representable by a float, and round the number to that many digits before truncating it. A typical choice is 12,
'%.12f' % f
but you can adjust this to suit the numbers you're using.
1Well... I lied. Technically, you can instruct Python to re-parse its own source code and extract the part corresponding to the first argument you pass to the truncation function. If that argument is a floating-point literal, you can just cut it off a certain number of places after the decimal point and return that. However this strategy doesn't work if the argument is a variable, which makes it fairly useless. The following is presented for entertainment value only:
def trunc_introspect(f, n):
'''Truncates/pads the float f to n decimal places by looking at the caller's source code'''
current_frame = None
caller_frame = None
s = inspect.stack()
try:
current_frame = s[0]
caller_frame = s[1]
gen = tokenize.tokenize(io.BytesIO(caller_frame[4][caller_frame[5]].encode('utf-8')).readline)
for token_type, token_string, _, _, _ in gen:
if token_type == tokenize.NAME and token_string == current_frame[3]:
next(gen) # left parenthesis
token_type, token_string, _, _, _ = next(gen) # float literal
if token_type == tokenize.NUMBER:
try:
cut_point = token_string.index('.') + n + 1
except ValueError: # no decimal in string
return token_string + '.' + '0' * n
else:
if len(token_string) < cut_point:
token_string += '0' * (cut_point - len(token_string))
return token_string[:cut_point]
else:
raise ValueError('Unable to find floating-point literal (this probably means you called {} with a variable)'.format(current_frame[3]))
break
finally:
del s, current_frame, caller_frame
Generalizing this to handle the case where you pass in a variable seems like a lost cause, since you'd have to trace backwards through the program's execution until you find the floating-point literal which gave the variable its value. If there even is one. Most variables will be initialized from user input or mathematical expressions, in which case the binary representation is all there is.
The result of round is a float, so watch out (example is from Python 2.6):
>>> round(1.923328437452, 3)
1.923
>>> round(1.23456, 3)
1.2350000000000001
You will be better off when using a formatted string:
>>> "%.3f" % 1.923328437452
'1.923'
>>> "%.3f" % 1.23456
'1.235'
n = 1.923328437452
str(n)[:4]
At my Python 2.7 prompt:
>>> int(1.923328437452 * 1000)/1000.0
1.923
The truely pythonic way of doing it is
from decimal import *
with localcontext() as ctx:
ctx.rounding = ROUND_DOWN
print Decimal('1.923328437452').quantize(Decimal('0.001'))
or shorter:
from decimal import Decimal as D, ROUND_DOWN
D('1.923328437452').quantize(D('0.001'), rounding=ROUND_DOWN)
Update
Usually the problem is not in truncating floats itself, but in the improper usage of float numbers before rounding.
For example: int(0.7*3*100)/100 == 2.09.
If you are forced to use floats (say, you're accelerating your code with numba), it's better to use cents as "internal representation" of prices: (70*3 == 210) and multiply/divide the inputs/outputs.
Simple python script -
n = 1.923328437452
n = float(int(n * 1000))
n /=1000
def trunc(num, digits):
sp = str(num).split('.')
return '.'.join([sp[0], sp[1][:digits]])
This should work. It should give you the truncation you are looking for.
So many of the answers given for this question are just completely wrong. They either round up floats (rather than truncate) or do not work for all cases.
This is the top Google result when I search for 'Python truncate float', a concept which is really straightforward, and which deserves better answers. I agree with Hatchkins that using the decimal module is the pythonic way of doing this, so I give here a function which I think answers the question correctly, and which works as expected for all cases.
As a side-note, fractional values, in general, cannot be represented exactly by binary floating point variables (see here for a discussion of this), which is why my function returns a string.
from decimal import Decimal, localcontext, ROUND_DOWN
def truncate(number, places):
if not isinstance(places, int):
raise ValueError("Decimal places must be an integer.")
if places < 1:
raise ValueError("Decimal places must be at least 1.")
# If you want to truncate to 0 decimal places, just do int(number).
with localcontext() as context:
context.rounding = ROUND_DOWN
exponent = Decimal(str(10 ** - places))
return Decimal(str(number)).quantize(exponent).to_eng_string()
>>> from math import floor
>>> floor((1.23658945) * 10**4) / 10**4
1.2365
# divide and multiply by 10**number of desired digits
If you fancy some mathemagic, this works for +ve numbers:
>>> v = 1.923328437452
>>> v - v % 1e-3
1.923
I did something like this:
from math import trunc
def truncate(number, decimals=0):
if decimals < 0:
raise ValueError('truncate received an invalid value of decimals ({})'.format(decimals))
elif decimals == 0:
return trunc(number)
else:
factor = float(10**decimals)
return trunc(number*factor)/factor
You can do:
def truncate(f, n):
return math.floor(f * 10 ** n) / 10 ** n
testing:
>>> f=1.923328437452
>>> [truncate(f, n) for n in range(5)]
[1.0, 1.9, 1.92, 1.923, 1.9233]
Just wanted to mention that the old "make round() with floor()" trick of
round(f) = floor(f+0.5)
can be turned around to make floor() from round()
floor(f) = round(f-0.5)
Although both these rules break around negative numbers, so using it is less than ideal:
def trunc(f, n):
if f > 0:
return "%.*f" % (n, (f - 0.5*10**-n))
elif f == 0:
return "%.*f" % (n, f)
elif f < 0:
return "%.*f" % (n, (f + 0.5*10**-n))
def precision(value, precision):
"""
param: value: takes a float
param: precision: int, number of decimal places
returns a float
"""
x = 10.0**precision
num = int(value * x)/ x
return num
precision(1.923328437452, 3)
1.923
Short and easy variant
def truncate_float(value, digits_after_point=2):
pow_10 = 10 ** digits_after_point
return (float(int(value * pow_10))) / pow_10
>>> truncate_float(1.14333, 2)
>>> 1.14
>>> truncate_float(1.14777, 2)
>>> 1.14
>>> truncate_float(1.14777, 4)
>>> 1.1477
When using a pandas df this worked for me
import math
def truncate(number, digits) -> float:
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
df['trunc'] = df['float_val'].apply(lambda x: truncate(x,1))
df['trunc']=df['trunc'].map('{:.1f}'.format)
int(16.5);
this will give an integer value of 16, i.e. trunc, won't be able to specify decimals, but guess you can do that by
import math;
def trunc(invalue, digits):
return int(invalue*math.pow(10,digits))/math.pow(10,digits);
Here is an easy way:
def truncate(num, res=3):
return (floor(num*pow(10, res)+0.5))/pow(10, res)
for num = 1.923328437452, this outputs 1.923
def trunc(f,n):
return ('%.16f' % f)[:(n-16)]
A general and simple function to use:
def truncate_float(number, length):
"""Truncate float numbers, up to the number specified
in length that must be an integer"""
number = number * pow(10, length)
number = int(number)
number = float(number)
number /= pow(10, length)
return number
There is an easy workaround in python 3. Where to cut I defined with an help variable decPlace to make it easy to adapt.
f = 1.12345
decPlace= 4
f_cut = int(f * 10**decPlace) /10**decPlace
Output:
f = 1.1234
Hope it helps.
Most answers are way too complicated in my opinion, how about this?
digits = 2 # Specify how many digits you want
fnum = '122.485221'
truncated_float = float(fnum[:fnum.find('.') + digits + 1])
>>> 122.48
Simply scanning for the index of '.' and truncate as desired (no rounding).
Convert string to float as final step.
Or in your case if you get a float as input and want a string as output:
fnum = str(122.485221) # convert float to string first
truncated_float = fnum[:fnum.find('.') + digits + 1] # string output
I think a better version would be just to find the index of decimal point . and then to take the string slice accordingly:
def truncate(number, n_digits:int=1)->float:
'''
:param number: real number ℝ
:param n_digits: Maximum number of digits after the decimal point after truncation
:return: truncated floating point number with at least one digit after decimal point
'''
decimalIndex = str(number).find('.')
if decimalIndex == -1:
return float(number)
else:
return float(str(number)[:decimalIndex+n_digits+1])
int(1.923328437452 * 1000) / 1000
>>> 1.923
int(1.9239 * 1000) / 1000
>>> 1.923
By multiplying the number by 1000 (10 ^ 3 for 3 digits) we shift the decimal point 3 places to the right and get 1923.3284374520001. When we convert that to an int the fractional part 3284374520001 will be discarded. Then we undo the shifting of the decimal point again by dividing by 1000 which returns 1.923.
use numpy.round
import numpy as np
precision = 3
floats = [1.123123123, 2.321321321321]
new_float = np.round(floats, precision)
Something simple enough to fit in a list-comprehension, with no libraries or other external dependencies. For Python >=3.6, it's very simple to write with f-strings.
The idea is to let the string-conversion do the rounding to one more place than you need and then chop off the last digit.
>>> nout = 3 # desired number of digits in output
>>> [f'{x:.{nout+1}f}'[:-1] for x in [2/3, 4/5, 8/9, 9/8, 5/4, 3/2]]
['0.666', '0.800', '0.888', '1.125', '1.250', '1.500']
Of course, there is rounding happening here (namely for the fourth digit), but rounding at some point is unvoidable. In case the transition between truncation and rounding is relevant, here's a slightly better example:
>>> nacc = 6 # desired accuracy (maximum 15!)
>>> nout = 3 # desired number of digits in output
>>> [f'{x:.{nacc}f}'[:-(nacc-nout)] for x in [2.9999, 2.99999, 2.999999, 2.9999999]]
>>> ['2.999', '2.999', '2.999', '3.000']
Bonus: removing zeros on the right
>>> nout = 3 # desired number of digits in output
>>> [f'{x:.{nout+1}f}'[:-1].rstrip('0') for x in [2/3, 4/5, 8/9, 9/8, 5/4, 3/2]]
['0.666', '0.8', '0.888', '1.125', '1.25', '1.5']
The core idea given here seems to me to be the best approach for this problem.
Unfortunately, it has received less votes while the later answer that has more votes is not complete (as observed in the comments). Hopefully, the implementation below provides a short and complete solution for truncation.
def trunc(num, digits):
l = str(float(num)).split('.')
digits = min(len(l[1]), digits)
return l[0] + '.' + l[1][:digits]
which should take care of all corner cases found here and here.
Am also a python newbie and after making use of some bits and pieces here, I offer my two cents
print str(int(time.time()))+str(datetime.now().microsecond)[:3]
str(int(time.time())) will take the time epoch as int and convert it to string and join with...
str(datetime.now().microsecond)[:3] which returns the microseconds only, convert to string and truncate to first 3 chars
# value value to be truncated
# n number of values after decimal
value = 0.999782
n = 3
float(int(value*1en))*1e-n

Converting binary to decimal integer output

I need to convert a binary input into a decimal integer. I know how to go from a decimal to a binary:
n = int(raw_input('enter a number: '))
print '{0:b}'.format(n)
I need to go in the reverse direction. My professor said that when he checks our code, he is going to input 11001, and he should get 25 back. I've looked through our notes, and I cannot figure out how to do this. Google and other internet resources haven't been much help either.
The biggest problem is that we are not allowed to use built-in functions. I understand why we are not allowed to use them, but it's making this problem much more difficult, since I know Python has a built-in function for binary to decimal.
You can use int and set the base to 2 (for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a demonstration:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>
Binary to Decimal
int(binaryString, 2)
Decimal to Binary
format(decimal ,"b")
There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:
Train an AI algorithm to convert 32-binary number to decimal based.
Predict a decimal representation from 32-binary.
See example and time comparison below:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np
y = np.random.randint(0, 2**32, size=10_000)
def gen_x(y):
_x = bin(y)[2:]
n = 32 - len(_x)
return [int(sym) for sym in '0'*n + _x]
X = np.array([gen_x(x) for x in y])
model = LinearRegression()
model.fit(X, y)
def convert_bin_to_dec_ai(array):
return model.predict(array)
y_pred = convert_bin_to_dec_ai(X)
Time comparison:
This AI solution converts numbers almost x10 times faster than conventional way!
If you want/need to do it without int:
sum(int(c) * (2 ** i) for i, c in enumerate(s[::-1]))
This reverses the string (s[::-1]), gets each character c and its index i (for i, c in enumerate(), multiplies the integer of the character (int(c)) by two to the power of the index (2 ** i) then adds them all together (sum()).
I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:
def __degree(number):
power = 1
while number % (10**power) != number:
power += 1
return power
def __getDigits(number):
digits = []
degree = __degree(number)
for x in range(0, degree):
digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
return digits
def binaryToDecimal(number):
list = __getDigits(number)
decimalValue = 0
for x in range(0, len(list)):
if (list[x] is 1):
decimalValue += 2**(len(list) - x - 1)
return decimalValue
Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:
binaryNum = int(input("Enter a binary number: "))
print(binaryToDecimal(binaryNum))
This prints out the correct result. Cheers!
The input may be string or integer.
num = 1000 #or num = '1000'
sum(map(lambda x: x[1]*(2**x[0]), enumerate(map(int, str(num))[::-1])))
# 8
a = input('Enter a binary number : ')
ar = [int(i) for i in a]
ar = ar[::-1]
res = []
for i in range(len(ar)):
res.append(ar[i]*(2**i))
sum_res = sum(res)
print('Decimal Number is : ',sum_res)
Using the power (**) function is a bit of a waste, so #user2555451's solution really is the way to go (Horner's method). Here's a fancy variation on it (less efficient, though, since the string needs to be reversed. The str-cast is there to allow for integers to be passed as well):
from itertools import accumulate, repeat
from operator import mul
def bin2dec(bin_str):
return sum(
int(n) * m for n, m in zip(
str(bin_str)[::-1],
accumulate((repeat(2)), func=mul, initial=1)))

Generate and Enter Value for OEIS Sequence in Python?

This is a rather difficult challenge for me as I am new to Python. How would I write a program in python based off this sequence function:
http://oeis.org/A063655
and does the following:
It asks for the value of the sequence and returns the corresponding number. For example, the number corresponding to the 10th value of the sequence is 7. I'd like to be able to do this for values over 300,000,000.
So, the final product would look like this:
Enter a value: 4
[7]
Any ideas where to start? I have a framework to generate sequences where (x) would be to put a mathematical equation or numbers, but I'm not exactly sure how to go from here or how to implement the "Enter a value" portion:
import math
def my_deltas():
while True:
yield (x)
yield (x)
def numbers(start, deltas, max):
i=start
while i<=max:
yield i
i+=next(deltas)
print(','.join(str(i) for i in numbers((x), my_deltas(),(x))))
If you're looking to have your computer keep track of over 300,000,000 elements of a sequence, if each is a 4 byte integer, you'll need at least 300,000,000 * 4bytes, or over 1.1GB of space to store all the values. I assume generating the sequence would also take a really long time, so generating the whole sequence again each time the user wants a value is not quite optimal either. I am a little confused about how you are trying to approach this exactly.
To get a value from the user is simple: you can use val = input("What is your value? ") where val is the variable you store it in.
EDIT:
It seems like a quick and simple approach would be this way, with a reasonable number of steps for each value (unless the value is prime...but lets keep the concept simple for now): You'd need the integer less than or equal to the square root of n (start_int = n ** .5), and from there you test each integer below to see if it divides n, first converting start_int to an integer with start_int = int(start_int) (which gives you the floor of start_int), like so: while (n % start_int) != 0: start_int = start_int - 1, decrement by one, and then set b = start_int. Something similar to find d, but you'll have to figure that part out. Note that % is the modulus operator (if you don't know what that is, you can read up on it, google: 'modulus python'), and ** is exponentiation. You can then return a value with the return statement. Your function would look something like this (lines starting with # are comments and python skips over them):
def find_number(value):
#using value instead of n
start_int = value ** .5
start_int = int(start_int)
while (n % start_int) != 0:
#same thing as start_int = start_int - 1
start_int -= 1
b = start_int
#...more code here
semiperimeter = b + d
return semiperimeter
#Let's use this function now!
#store
my_val = input("Enter a value: ")
my_number = find_number(my_val)
print my_number
There are many introductory guides to Python, and I would suggest you go through one first before tackling implementing a problem like this. If you already know how to program in another language you can just skim a guide to Python's syntax.
Don't forget to choose this answer if it helped!
from math import sqrt, floor
def A063655(n):
for i in range(floor(sqrt(n)), 0, -1):
j = floor(n / i)
if i * j == n:
return i + j
if __name__ == '__main__':
my_value = int(input("Enter a value: "))
my_number = A063655(my_value)
print(my_number)
USAGE
> python3 test.py
Enter a value: 10
7
> python3 test.py
Enter a value: 350000
1185
>

Reading values with raw_input in Python

I am trying to do integration in Python but whenever I key in a value my outputs always results in 0. What the reason?
E.g.:
def main():
eq_of_form()
value_of_a()
value_of_b()
value_of_c()
value_of_m()
value_of_n()
value_of_x()
area_under_graph()
def eq_of_form():
print "Eq of the form y = ax^m + bx^n + c " + ":"
def value_of_a():
return raw_input("Enter value for a \n")
def value_of_b():
return raw_input("Enter value for b \n")
def value_of_c():
return raw_input("Enter value for c \n")
def value_of_m():
return raw_input("Enter value for m \n")
def value_of_n():
return raw_input("Enter value for n \n")
def value_of_x():
return raw_input("Enter a value for x to find " +
"value of y and the gradient at that point \n " + "x = ")
def area_under_graph():
y = (int(value_of_a())*int(value_of_x())**(int(value_of_m())+1))/((int(value_of_m())+1))
// * 2nd part.This works for me(:
// + (int(value_of_b())) * (int(value_of_x())**
// (int(value_of_n())+1))/(int(value_of_n())+1) + ((int(value_of_c())*int(value_of_x())))
print y
main()
(* Note: the eq under the area_under_graph() function is only half of it because the other half kind of work so I did not post it:))
For the top code, I tried inputting the values here: (maybe you can try using the same(: )
a = 1
b = 2
c = 1
m = 2
n = 1
x = 1
I am supposed to get 7/3 which is 2.333, but I end up getting 2. The problem appears to lie in the first part of the eq.
Sorry for the newbie question.
Your code at the start is wrong. You need to assign your variables after you read the user input:
value_of_a()
should be:
a = value_of_a()
It is also unnecessary to write a separate function for inputting each variable. You could instead have a function that takes a parameter:
def get_user_value(name):
return raw_input("Enter value for %s\n" % name)
a = get_user_value("a")
b = get_user_value("b")
# etc..
But then you ignore all these values and read them again inside the area_under_curve() method. This is probably not what you intend to do. Furthermore inside this method you assume that all parameters are integers. If you are using Python 2.5 the division here is integer division:
m1/m2
This could return 0 when the result was actually supposed to be a non-integer like 0.125. You need to use floats instead of integers to do the calculation. You can do this in Python 2.5 using float(m). In Python 3.0 the division operator does what you want by default.
/ does Integer division in Python2, this means a/b is the biggest integer c with c*b <=a, so 7/3 is indeed 2. You want floats, so you need to use them .. replace all the int with float in your code.
You should probably take another look at functions too ... you code can be much much shorter :-)
In Python 2.x, dividing an integer by another integer results in an integer. Either use from __future__ import division, or turn one of the integers into a float by passing it to float().
The issue is that you're using integer arithmetic - see all those int calls you've got everywhere. Integer arithmetic (in Python 2.x) will only ever return integers, so you'll never get 2.33, only 2.
Use float() instead of int() and things should work.

Categories