How to see if a number ends in .0 - python

I am trying to run a test if the number ends in .0
I am running a program with numbers orders of magnitude apart so I can't estimate to a certain amount of digits. using % doesn't work either because then certain numbers are excluded. All the numbers in this program are floating point numbers so I need a way to check if it ends with .0, not with .00000000000001232 or something it has to end exactly in .0
The problem with the round function is that I am dealing with numbers of several orders of magnitude. I need something that checks if it has only 1 decimal after the . or something that checks if the that decimal is a 0.
code:
from myro import *
from math import *
def main():
z = 3
a = 2
b = 2
x = 3
y = 2 #starts at y = 3
lim = 25
c = (a**x + b**y)**(1.0/z)
resultnum = 0
while z <= lim:
while a <= lim:
while b <= lim:
while x <= lim:
while y <= lim:
y = y + 1
c = (a**x + b**y)**(1.0/z)
if float(int(c) + 1) != round(c, 6):
pass
else:
print str(a) + "^" + str(x) + " + " + str(b) + "^" + str(y) + " = " + str(int(c)+1) + "^" + str(z)
resultnum = resultnum + 1
print c
y = 3
x = x + 1
x = 3
b = b + 1
b = 3
a = a + 1
a = 3
z = z + 1
print z
print "code cycle complete"
print str(resultnum) + " results"
main()

>>> n1 = 2.0
>>> int(n1) == n1 and isinstance(n1, float)
True
>>> n1 = 2
>>> int(n1) == n1 and isinstance(n1, float)
False
>>> n1 = 2.01
>>> int(n1) == n1 and isinstance(n1, float)
False
>>> n1 = 1E1 #works for scientific notation as well
>>> int(n1) == n1 and isinstance(n1, float)
True

Python does this already. Going with what Python gives as a string might be what you want:
In [577]: def dot_zero(number):
.....: return str(number).endswith('.0')
.....:
In [578]: dot_zero(2.0)
Out[578]: True
In [579]: dot_zero(2)
Out[579]: False
In [580]: dot_zero(2.01)
Out[580]: False
EDIT
As pointed out by #jamylak this does not work for large numbers since the scientific notation used by str. Keeping the basic idea of conversion into a string, but also catering for large numbers, we end up with more verbose and admittedly rather ugly solution:
def dot_zero_string(number):
# tested and works with Python 3.3
split = str(number).split('e')
return len(split) == 2 or split[0].endswith('.0')
This is the solution in the answer from #AshwiniChaudhary
def dot_zero_inst(number):
return int(number) == number and isinstance(number, float)
Comparing different cases gives the same result:
numbers = [1, 1.0, 1000, 1000.0, 3e38, 1.5555555555555555555555e12,
1.5555555555555555555555e17, 0, 0.0]
numbers = numbers + [-number for number in numbers]
for number in numbers:
assert dot_zero_inst(number) == dot_zero_string(number)

Just to show another method, you can always split by the '.':
>>> num = 12.023
>>> str(num).split('.')[1] == '0'
False
>>> num = 12.0
>>> str(num).split('.')[1] == '0'
True
Note that this works because you said that all were floating points. This will provide an error num is an int

x = 26.5
b % math.floor(b) == 0
>>> False
x = 26.0
b % math.floor(b) == 0
>>> True
should also do it.

Related

How do I check every possible combination for validity?

For context, I am trying to find all viable solutions to this question:
here's the code I have so far, but I am having trouble with the part that is supposed to iterate through every possible combination.
x = 1
y = 1
z = 10
a = 10
while x < 10 and y < 10 and z < 100 and a < 100: #iterates through every possible combination
x = x + 1
y = y + 1
z = z + 1
a = a + 1
if x != y: #checks if x and are the same
if a/x == z/y or z/x == a/y: #checks if x and y are proportional to a and z
a = str(a) #converting each int to string
z = str(z)
x = str(x)
y = str(y)
if a.count(x) < 1 and a.count(y) < 1 and z.count(y) <1 and z.count(x) < 1: #checks if any number reapeats
print(x, y, z, a) #prints viable solution```
You have six boxes to fill. Just run through all permutations of 6 members and check the conditions:
import itertools
for a,b,c,d,e,f in itertools.permutations([0,1,2,3,4,5,6,7,8,9],6):
if a == 0 or b == 0 or c == 0 or e == 0:
continue
if (10*c + d) / a == (10*e + f) / b:
print( a, b, c*10+d, e*10+f )
It looks like there are 57 solutions.

python-How to reverse an negative integer or non-integer

I am learning python and I meet some troubles.
I want to write the script to reverse a negative integer " -1234 to 4321- " and non-integer " 1.234 to 432.1". please help me.
P.S. cannot use "str()" function
I just only can write the script to reverse positive integer 1234 to 4321
def reverse_int(n):
x = 0
while n > 0:
x *= 10
x += n % 10
n /= 10
return x
print reverse_int(1234)
def reve(x):
x=str(x)
if x[0]=='-':
a=x[::-1]
return f"{x[0]}{a[:-1]}"
else:
return x[::-1]
print(reve("abc"))
print(reve(123))
print(reve(-123))
#output
cba
321
-321
how about using your code, but just concatenate a - when n is negative?
rev_int.py:
def reverse_int(m):
x = 0
n = m
if m < 0 :
n *= -1
while n > 0 :
x *= 10
x += n % 10
n /= 10
if m < 0:
#concatenate a - sign at the end
return `x` + "-"
return x
print reverse_int(1234)
print reverse_int(-1234)
This produces:
$ python rev_int.py
4321
4321-
Using SLICING EASILY DONE IT
def uuu(num):
if num >= 0:
return int(str(num)[::-1])
else:
return int('-{val}'.format(val = str(num)[1:][::-1]))
Below code runs fine on Python-3 and handles positive and negative integer case. Below code takes STDIN and prints the output on STDOUT.
Note: below code handles only the integer case and doesn't handles the
non-integer case.
def reverseNumber(number):
x = 0
#Taking absolute of number for reversion logic
n = abs(number)
rev = 0
#Below logic is to reverse the integer
while(n > 0):
a = n % 10
rev = rev * 10 + a
n = n // 10
#Below case handles negative integer case
if(number < 0):
return (str(rev) + "-")
return (rev)
#Takes STDIN input from the user
number=int(input())
#Calls the reverseNumber function and prints the output to STDOUT
print(reverseNumber(number))
Using str convert method.
num = 123
print(str(num)[::-1])
Use this as a guide and make it work for floating point values as well:
import math
def reverse_int(n):
if abs(n) < 10:
v = chr(abs(n) + ord('0'))
if n < 0: v += '-'
return v
else:
x = abs(n) % 10
if n < 0: return chr(x + ord('0')) + reverse_int(math.ceil(n / 10))
else: return chr(x + ord('0')) + reverse_int(math.floor(n / 10))
print reverse_int(1234)
Why not just do the following?:
def reverse(num):
revNum = ''
for i in `num`:
revNum = i + revNum
return revNum
print reverse(1.12345)
print reverse(-12345)
These would print 54321.1 and 54321-.

Increase digits of a number by one

I am working on this seemingly simple problem, where I need to add one to every digit of a number. Example: number = 1234 ; output = 2345
That's simple, but when 9 is one of those digits, then by the law of addition, that 9 will be replaced by 0 and 1 will be added to the number on the left (9 + 1 = 10, hence, place value = 0 & carry over = 1)
Example: number = 1239 ; output = 2350
number = 1234
s = str(number)
l = []
for num in s:
num = int(num)
num += 1
if num > 9:
num = 0
l.append(num)
else:
l.append(num)
print int(''.join(str(v) for v in l))
Can someone please explain to me, what logic should I use? I can see something on the lines of modular arithmetic, but not really sure how to implement that.
Thanks :)
A simple approach would be as follows
Consider a number N = anan-1an-2...a0
Then F(N) = N + (10n-1+10n-2 .. 100) = N + int('1' X N)
= N + (10n - 1) / (10 - 1) = N + (10n - 1) / 9
>>> def foo(N):
return N + int('1'*len(str(N)))
>>> foo(1234)
2345
>>> foo(1239)
2350
Edit: Simplifying a bit by utilizing sum of power formula
>>> def foo(N):
return N + ((10**len(str(N)) - 1) // 9)
With pure math:
num = num + (10**int(math.ceil(math.log10(num)))-1)//9
Your code can be easily modified to process the digits in reversed order and maintain the carry state. The "modular arithmetic" you're looking for is typically implemented using the % operator:
number = 1234
s = str(1234)
l = []
carry = 0
for num in reversed(s):
num = int(num) + carry
num += 1
carry = num / 10
l.append(num % 10)
print int(''.join(str(v) for v in reversed(l)))

python 2.7: round a float up to next even number

I would like to round up a float to the next even number.
Steps:
1) check if a number is odd or even
2) if odd, round up to next even number
I have step 1 ready, a function which checks if a give number is even or not:
def is_even(num):
if int(float(num) * 10) % 2 == 0:
return "True"
else:
return "False"
but I'm struggling with step 2....
Any advice?
Note: all floats will be positive.
There is no need for step 1. Just divide the value by 2, round up to the nearest integer, then multiply by 2 again:
import math
def round_up_to_even(f):
return math.ceil(f / 2.) * 2
Demo:
>>> import math
>>> def round_up_to_even(f):
... return math.ceil(f / 2.) * 2
...
>>> round_up_to_even(1.25)
2
>>> round_up_to_even(3)
4
>>> round_up_to_even(2.25)
4
a = 3.5654
b = 2.568
a = int(a) if ((int(a) % 2) == 0) else int(a) + 1
b = int(b) if ((int(b) % 2) == 0) else int(b) + 1
print a
print b
value of a after execution
a = 4
value of b after execution
b = 2
import math
def round_to_ceil_even(f):
if (math.floor(f)%2 == 0):
return math.floor(f)
else:
return math.floor(f)+1
def round_to_ceil_even(f):
if (math.floor(f)%2 == 0):
return int(f)
else:
return int(f+1)

How to make python print 1 as opposed to 1.0

I am making a math solving program, it keeps printing the whole numbers as decimals. Like 1 is 1.0, 5 is 5.0, and my code is:
print("Type in the cooridinates of the two points.")
print("")
print("---------------------")
print("First point:")
x1 = int(input("X: "))
y1 = int(input("Y: "))
print("")
print("---------------------")
print("Second point:")
x2 = int(input("X: "))
y2 = int(input("Y: "))
m = (y1-y2) / (x1-x2)
b = y1 - m * x1
round(m, 0)
round(b, 0)
print("Completed equation:")
print("")
if b < 0:
print("Y = "+ str(m) +"X - "+ str(b) +".")
elif b > 0:
print("Y = "+ str(m) +"X + "+ str(b) +".")
elif b == 0:
print("Y = "+ str(m) +"X.")
input("Press enter to continue.")
Since you're dividing integers, Python represents the result as a float, not as an int. To format the floats as you'd like, you'll have to use string formatting:
>>> print('{:g}'.format(3.14))
3.14
>>> print('{:g}'.format(3.0))
3
So plugging it into your code:
print("Y = {:g}X - {}.".format(m, b))
Try this,
> x = 10.0
> print int(x)
10
> print x
> 10.0
Is this what you are really looking for?
When you do this:
m = (y1-y2) / (x1-x2)
You get a float (a floating point representation of a real number), not an int (an integer).
Then, because m is a float, b too is a float. Then, when you call str on a float, you get a decimal point.
The right way to fix this depends on what you actually want to do.
If you really want to deal only with integers, you can use integer division:
m = (y1-y2) // (x1-x2)
That means if, say, x1, x2, y1, y2 = 4, 2, 2, 1 you'll end up with b = 2 (2 - 0 * 4). I suspect that isn't what you want; you actually want to multiply that 4 by 1/2, and then round the result afterward.
In that case, you can do the conversion the same place you round:
m = int(round(m, 0))
b = int(round(b, 0))
Note that your existing calls to round didn't actually do anything; round(m, 0) doesn't modify m, it returns a new value that's the rounded version of m, which you have to assign back to m (or somewhere else).
One more thing to consider: You probably really do want literally one half, not "the closest floating point representation to 0.5".
You probably don't actually care about the difference—unless you're using quite large integers, the rounding errors won't ever be visible. But if you do care, you may want to consider using a third-party exact-fraction module (e.g., clnum), or possibly the standard library decimal. This would mean you have to be more explicit, so I wouldn't do this unless you expect it to be necessary. But if it is necessary, it would look something like this:
m = decimal.Decimal(y1-y2) / (x1-x2)
b = y1 - m * x1
m = int(m.to_integral(rounding=decimal.ROUND_HALF_UP))
b = int(b.to_integral(rounding=decimal.ROUND_HALF_UP))
Finally, you can always keep the numbers around as floats (or Decimals, etc.), never rounding or converting them, and force them to print as integers anyway:
print("Y = {:.0g}X - {:.0g}.".format(m, b))
Just tried this one
n = -0.0
#n = 0.0
#n = +0.0
#n = 5.0
#n = 5
#n = 5.4
#n = -5.0
#n = -5
#n = 5.25
n = (n**2)**0.5
n = '{:g}'.format(n)
if n.find('.') == -1:
n=int(n)
else:
n=float(n)
print(n)
print(type(n))
-------------------------------------------------------------------
The same in one line
n = -0.0
n = int('{:g}'.format((n**2)**0.5)) if
'{:g}'.format((n**2)**0.5).find('.') == -1 else
float('{:g}'.format((n**2)**0.5))
-------------------------------------------------------------------
Example for a list
numlist = [-0.0, 0.0, +0.0, 5.0, 5, 5.4, +5.0, +5, +5.15,-5.0, -5, 5.25]
print(f'Numbers are {numlist}')
for n in numlist:
print(f'Before n is {n} and type of n is {type(n)}')
n = int('{:g}'.format((n**2)**0.5)) if '{:g}'.format((n**2)**0.5).find('.')
== -1 else float('{:g}'.format((n**2)**0.5))
print(f'After n is {n} and type of n is {type(n)}')

Categories