Related
I found a program of changing digit 5 with 6 in python , but the issue is I've got it in python2 and if I change it in python3 and rerun it it gives weird output.
The source of python 2 code is
http://www.geeksforgeeks.org/replace-0-5-input-integer/
and my full python3 code is
def convert5to6rec(num):
# Base case for recurssion termination
if(num == 0):
return 0
# Extract the last digit and change it if needed
digit = num % 10
if(digit == 5):
digit = 6
# Convert remaining digits and append the last digit
return convert5to6rec(num/10) * 10 + digit
# It handles 0 to 5 calls convert0to5rec() for other numbers
def convert5to6(num):
if(num == 5):
return 6
else:
return convert5to6rec(num)
# Driver Program
num = 520
print(convert5to6(num))
The output it gives is
170642.43254304124
SO can anyone point out that silly mistake that I left
PS: I need the program to replace the digits 5 with 6.
the expected output should be 620
Change num/10 to num//10. In Python 3, integer division with the / operator produces a floating point result. To get integer division, you need to use the // operator.
Instead of doing it mathematically, you could convert the integer to a string, replace the 5's with 6's and cast it back to an integer. The easiest way to do this would be
int(str(num).replace('5', '6'))
The reason it's not working in python 3 is because of the difference in the behavior of division in python 2 and 3. In python 2, / does a floor division, whereas in python 3, it is a true division.
So in python 2,
In [1]: 11 / 2
Out[1]: 5
In python 3,
In [2]: 11/2
Out[2]: 5.5
For doing floor division in python 3 you will need to use // instead of /. So, you just need to replace / with // in your code.
I am trying to solve this excercise:
https://projecteuler.net/problem=16
The code is pretty self-explanatory: I calculate 2^n in power(n), and in sum(n), I cut off the last digit of the number. I do this as long as pow > 0. I receive the right solution for 2^15, but for one reason or another, the same code doesn't work for 2^1000. I receive 1889, which is apparently wrong.
def power(n):
power = 2
for x in range(1, n):
power = 2*power
return power
def sum(n):
pow = power(n)
sum = 0
while pow > 0:
modulo = pow%10
sum = sum + modulo
pow = int((pow - modulo)/10)
return sum
def main():
print(int(sum(1000)))
if __name__ == '__main__':
main()
A simple change in your code will give you the correct answer,
def power(n):
power = 2
for x in range(1, n):
power = 2*power
return power
def sum(n):
pow = power(n)
sum = 0
while pow > 0:
modulo = pow%10
sum = sum + modulo
pow = pow//10 # modified line
return sum
def main():
print(int(sum(1000)))
if __name__ == '__main__':
main()
The reason why your example doesn't work is because you are casting the result of a float operation to int. Floats are never precise and when they are very large, they loose precision. Hence if you convert them back to integer, you get a much lower value.
A better function using divmod() is,
def sum(n):
pow = power(n)
sum = 0
while pow > 0:
pow,modulo = divmod(pow,10)
sum = sum + modulo
return sum
Your original solution would have worked in Python 2 because Python 2 and Python 3 handle division differently.
For example print(1/2) gives 0 in Python2, and 0.5 in Python3. In Python3, we use // for floor division (which is what you want here).
Your code doesn't work for any number >= 57
The problem here is very easy to solve.
In python 3 and higher, / is a division that returns a float, while // is an integer division that always returns an integer. Since you are using float division, you are encountering the issues with floating point arithmetic.
More about the issues and limitations.
To solve your problem, change the line
pow = int(pow - modulo)/10
into
pow = int(pow - modulo)//10
or even better, you can just say pow//=10
Isn't python beatiful?
def Power_digit_sum(n):
number = list(str(2**n)) # pow number and convert number in string and list
result= [int(i) for i in number]# convert number in int and
return sum(result) # sum list
print(Power_digit_sum(15)) # result 26
print(Power_digit_sum(1000)) # result 1366
This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 5 months ago.
I am a complete python beginner and I am trying to solve this problem :
A number is called triangular if it is the sum of the first n positive
integers for some n For example, 10 is triangular because 10 = 1+2+3+4
and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program
to find the smallest 6-digit triangular number. Enter it as your
answer below.
I have written this program:
n = 0
trinum = 0
while len(str(trinum)) < 6:
trinum = n*(n+1)/2
n += 1
print(trinum)
And it only works in the python I have installed on my computer if I say while len(str(trinum)) < 8: but it is supposed to be while len(str(trinum)) < 6:. So I went to http://www.skulpt.org/ and ran my code there and it gave me the right answer with while len(str(trinum)) < 6: like it's supposed to. But it doesn't work with 6 with the python i have installed on my computer. Does anyone have any idea what's going on?
Short Answer
In Python 3, division is always floating point division. So on the first pass you get something like str(trinum) == '0.5'. Which isn't what you want.
You're looking for integer division. The operator for that is //.
Long Answer
The division operator changed in Python 2.x to 3.x. Previously, the type of the result was dependent on the arguments. So 1/2 does integer division, but 1./2 does floating point division.
To clean this up, a new operator was introduced: //. This operator will always do integer division.
So in Python 3.x, this expression (4 * 5)/2 is equal to 10.0. Note that this number is less than 100, but it has 4 characters in it.
If instead, we did (4*5)//2, we would get the integer 10 back. Which would allow your condition to hold true.
In Python 2, the / operator performs integer division when possible: "x divided by y is a remainder b," throwing away the "b" (use the % operator to find "b"). In Python 3, the / operator always performs float division: "x divided by y is a.fgh." Get integer division in Python 3 with the // operator.
You have two problems here, that combine to give you the wrong answer.
The first problem is that you're using /, which means integer division in Python 2 (and the almost-Python language that Skulpt implements), but float division in Python 3. So, when you run it on your local machine with Python 3, you're going to get floating point numbers.
The second problem is that you're not checking for "under 6 digits" you're checking for "under 6 characters long". For positive integers, those are the same thing, but for floats, say, 1035.5 is only 4 digits, but it's 6 characters. So you exit early.
If you solve either problem, it will work, at least most of the time. But you really should solve both.
So:
n = 0
trinum = 0
while trinum < 10**6: # note comparing numbers, not string length
trinum = n*(n+1)//2 # note // instead of /
n += 1
print(trinum)
The first problem is fixed by using //, which always means integer division, instead of /, which means different things in different Python versions.
The second problem is fixed by comparing the number as a number to 10**6 (that is, 10 to the 6th power, which means 1 with 6 zeros, or 1000000) instead of comparing its length as a string to 6.
Taking Malik Brahimi's answer further:
from itertools import *
print(next(dropwhile(lambda n: n <= 99999, accumulate(count(1))))
count(1) is all the numbers from 1 to infinity.
accumulate(count(1)) is all the running totals of those numbers.
dropwhile(…) is skipping the initial running totals until we reach 100000, then all the rest of them.
next(…) is the next one after the ones we skipped.
Of course you could argue that a 1-liner that takes 4 lines to describe to a novice isn't as good as a 4-liner that doesn't need any explanation. :)
(Also, the dropwhile is a bit ugly. Most uses of it in Python are. In a language like Haskell, where you can write that predicate with operator sectioning instead of a lambda, like (<= 99999), it's a different story.)
The division method in Py2.x and 3.x is different - so that is probably why you had issues.
Just another suggestion - which doesn't deal with divisions and lengths - so less buggy in general. Plus addition is addition anywhere.
trinum = 0
idx =0
while trinum < 99999: #largest 5 digit number
idx += 1
trinum += idx
print trinum
import itertools # to get the count function
n, c = 0, itertools.count(1) # start at zero
while n <= 99999:
n = n + next(c)
Ive been give a task, it is as follows:
write a function called decToBin that takes in an integer and converts it to an 8-bit binary number represented as a string
As I am new to this im very lost! Having no introduction to my task as thrown me off a little and I really need some help!
I have tried the following code:
#function
def decTobin(integer)
return bin
#main program
decToBin(3)
decToBin(4)
decToBin(5)
However I had no sucess, could someone point me in the right direction, it would be much appreciated, thank you!
Please try to keep your questions tidy. Also, judging from your other questions, you should look at some basic python tutorials. Happy coding!
Try to learn about base conversions. Here is a great place to find a step by step walkthrough for doing it manually.
You will need to use the modulo (%) operator. The modulo operator is a binary operator, meaning it has two inputs. You use it like so:
a % b
It returns the remainder when a is divided by b:
10 % 7 = 3
The following code will do what you need:
def decToBin(x):
if x == 0:
return "00000000"
bits = []
while x:
bits.append(str(x % 2))
x >>= 1
return "".join(bits).zfill(8)
I will explain line by line.
def decToBin(x):
This declares the function.
if x == 0:
return "00000000"
This returns a string of eight zeros if the input is zero. We need this because the while loop only operates when x is not equal to zero.
bits = []
This initializes the array of bits. During the while loop, we will add to this with the append function.
while x:
This begins a while loop, which runs until x is false (or zero).
bits.append(str(x % 2))
This adds to the bits array the remainder when x is divided by 2. str() converts it to a string.
x >>= 1
>>= 1 Shifts the bits in x to the right one time like so:
Before: 1 1 0 1 0 1
After: 0 1 1 0 1 0
It is the same as dividing by 2, without keeping the remainder.
return "".join(bits).zfill(8)
Breakdown:
"abc".join(l)
Joins all the strings in list l, separating it with abc.
"2345".zfill(i)
adds zeros to the beginning of a string until there are i numbers. So
return "".join(bits).zfill(8)
returns the array of bits as one string, and pads the beginning until there are eight characters.
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.
Can I just write:
import math
def is_triangular1(x):
num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
return int(num) == num
Or do I need to do check within a tolerance instead?
epsilon = 0.000000000001
def is_triangular2(x):
num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
return abs(int(num) - num) < epsilon
I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.
As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.
There is is_integer function in python float type:
>>> float(1.0).is_integer()
True
>>> float(1.001).is_integer()
False
>>>
Both your implementations have problems. It actually can happen that you end up with something like 4.999999999999997, so using int() is not an option.
I'd go for a completely different approach: First assume that your number is triangular, and compute what n would be in that case. In that first step, you can round generously, since it's only necessary to get the result right if the number actually is triangular. Next, compute n * (n + 1) / 2 for this n, and compare the result to x. Now, you are comparing two integers, so there are no inaccuracies left.
The computation of n can be simplified by expanding
(1/2) * (math.sqrt(8*x+1)-1) = math.sqrt(2 * x + 0.25) - 0.5
and utilizing that
round(y - 0.5) = int(y)
for positive y.
def is_triangular(x):
n = int(math.sqrt(2 * x))
return x == n * (n + 1) / 2
You'll want to do the latter. In Programming in Python 3 the following example is given as the most accurate way to compare
def equal_float(a, b):
#return abs(a - b) <= sys.float_info.epsilon
return abs(a - b) <= chosen_value #see edit below for more info
Also, since epsilon is the "smallest difference the machine can distinguish between two floating-point numbers", you'll want to use <= in your function.
Edit: After reading the comments below I have looked back at the book and it specifically says "Here is a simple function for comparing floats for equality to the limit of the machines accuracy". I believe this was just an example for comparing floats to extreme precision but the fact that error is introduced with many float calculations this should rarely if ever be used. I characterized it as the "most accurate" way to compare in my answer, which in some sense is true, but rarely what is intended when comparing floats or integers to floats. Choosing a value (ex: 0.00000000001) based on the "problem domain" of the function instead of using sys.float_info.epsilon is the correct approach.
Thanks to S.Lott and Sven Marnach for their corrections, and I apologize if I led anyone down the wrong path.
Python does have a Decimal class (in the decimal module), which you could use to avoid the imprecision of floats.
floats can exactly represent all integers in their range - floating-point equality is only tricky if you care about the bit after the point. So, as long as all of the calculations in your formula return whole numbers for the cases you're interested in, int(num) == num is perfectly safe.
So, we need to prove that for any triangular number, every piece of maths you do can be done with integer arithmetic (and anything coming out as a non-integer must imply that x is not triangular):
To start with, we can assume that x must be an integer - this is required in the definition of 'triangular number'.
This being the case, 8*x + 1 will also be an integer, since the integers are closed under + and * .
math.sqrt() returns float; but if x is triangular, then the square root will be a whole number - ie, again exactly represented.
So, for all x that should return true in your functions, int(num) == num will be true, and so your istriangular1 will always work. The only sticking point, as mentioned in the comments to the question, is that Python 2 by default does integer division in the same way as C - int/int => int, truncating if the result can't be represented exactly as an int. So, 1/2 == 0. This is fixed in Python 3, or by having the line
from __future__ import division
near the top of your code.
I think the module decimal is what you need
You can round your number to e.g. 14 decimal places or less:
>>> round(4.999999999999997, 14)
5.0
PS: double precision is about 15 decimal places
It is hard to argue with standards.
In C99 and POSIX, the standard for rounding a float to an int is defined by nearbyint() The important concept is the direction of rounding and the locale specific rounding convention.
Assuming the convention is common rounding, this is the same as the C99 convention in Python:
#!/usr/bin/python
import math
infinity = math.ldexp(1.0, 1023) * 2
def nearbyint(x):
"""returns the nearest int as the C99 standard would"""
# handle NaN
if x!=x:
return x
if x >= infinity:
return infinity
if x <= -infinity:
return -infinity
if x==0.0:
return x
return math.floor(x + 0.5)
If you want more control over rounding, consider using the Decimal module and choose the rounding convention you wish to employ. You may want to use Banker's Rounding for example.
Once you have decided on the convention, round to an int and compare to the other int.
Consider using NumPy, they take care of everything under the hood.
import numpy as np
result_bool = np.isclose(float1, float2)
Python has unlimited integer precision, but only 53 bits of float precision. When you square a number, you double the number of bits it requires. This means that the ULP of the original number is (approximately) twice the ULP of the square root.
You start running into issues with numbers around 50 bits or so, because the difference between the fractional representation of an irrational root and the nearest integer can be smaller than the ULP. Even in this case, checking if you are within tolerance will do more harm than good (by increasing the number of false positives).
For example:
>>> x = (1 << 26) - 1
>>> (math.sqrt(x**2)).is_integer()
True
>>> (math.sqrt(x**2 + 1)).is_integer()
False
>>> (math.sqrt(x**2 - 1)).is_integer()
False
>>> y = (1 << 27) - 1
>>> (math.sqrt(y**2)).is_integer()
True
>>> (math.sqrt(y**2 + 1)).is_integer()
True
>>> (math.sqrt(y**2 - 1)).is_integer()
True
>>> (math.sqrt(y**2 + 2)).is_integer()
False
>>> (math.sqrt(y**2 - 2)).is_integer()
True
>>> (math.sqrt(y**2 - 3)).is_integer()
False
You can therefore rework the formulation of your problem slightly. If an integer x is a triangular number, there exists an integer n such that x = n * (n + 1) // 2. The resulting quadratic is n**2 + n - 2 * x = 0. All you need to know is if the discriminant 1 + 8 * x is a perfect square. You can compute the integer square root of an integer using math.isqrt starting with python 3.8. Prior to that, you could use one of the algorithms from Wikipedia, implemented on SO here.
You can therefore stay entirely in python's infinite-precision integer domain with the following one-liner:
def is_triangular(x):
return math.isqrt(k := 8 * x + 1)**2 == k
Now you can do something like this:
>>> x = 58686775177009424410876674976531835606028390913650409380075
>>> math.isqrt(k := 8 * x + 1)**2 == k
True
>>> math.isqrt(k := 8 * (x + 1) + 1)**2 == k
False
>>> math.sqrt(k := 8 * x + 1)**2 == k
False
The first result is correct: x in this example is a triangular number computed with n = 342598234604352345342958762349.
Python still uses the same floating point representation and operations C does, so the second one is the correct way.
Under the hood, Python's float type is a C double.
The most robust way would be to get the nearest integer to num, then test if that integers satisfies the property you're after:
import math
def is_triangular1(x):
num = (1/2) * (math.sqrt(8*x+1)-1 )
inum = int(round(num))
return inum*(inum+1) == 2*x # This line uses only integer arithmetic