Reverse digits of an integer in Python [duplicate] - python

This question already has answers here:
Using Python, reverse an integer, and tell if palindrome
(14 answers)
Closed 4 years ago.
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
I am trying to solve the reversing int problem, but following solution failed with the following input.
Input:
1534236469
Output:
9646324351
Expected:
0
In my solution, I am checking whether or not given int is bigger than max or min value, and then checking whether or not it is negative.
My solution
import sys
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x <sys.maxsize-1 or x > -sys.minsize:
if str(x)[0] == '-':
list_mod = list(str(x))
list_mod.pop(0)
list_mod.append('-')
list_mod.reverse()
join_list = ''.join(list_mod[:])
return int(join_list)
else:
return int(str(x)[::-1])
else:
return 0

Try converting the int to string, then reverse and then convert it to int.
Ex:
a = 1534236469
print(int(str(a)[::-1]))
Output:
9646324351
To handle the negative number:
if str(a).startswith("-"):
a = a[1:]
print("-{0}".format(int(str(a)[::-1])))
else:
print(int(str(a)[::-1]))

Related

Math.sqrt giving floating values in python [duplicate]

This question already has answers here:
Check if a number is a perfect square
(24 answers)
Closed 1 year ago.
I am solving this question:
Given a positive integer num, write a function that returns True if
num is a perfect square else False.
Input: num = 16
Output: true
My solution:
import math
class Solution:
def isPerfectSquare(self, num: int) -> bool:
return type(math.sqrt(16))=='int' //4.0=='int'
I know there are a lot of different solutions which are easier but I want to know how we can get this right as I can't use int to make it integer as 4.5 will also be the correct answer.
math.sqrt's default return type is float so you should check if the square root and floor of square root are equal or not to identify a perfect square...
This will work...
import math
class Solution:
def isPerfectSquare(self, num: int) -> bool:
sqroot = math.sqrt(num)
return sqroot == math.floor(sqroot)

Syntax error when casting string to int [duplicate]

This question already has answers here:
Convert integer to string in Python
(14 answers)
Closed 6 years ago.
My code:
def digit_sum(n):
result = 0
s = str(n)
for c in s:
result += (int)c # invalid syntax??????????
return result
print digit_sum(1234)
Result:
result += (int)c # invalid syntax??????????
^
SyntaxError: invalid syntax
The function is supposed to return the sum of each digit of the argument "n".
Why do I get SyntaxError in the commented line? The variable c is of type string so it shouldn´t be an issue to apply a type cast to int.
In Python you do not cast that way. You use:
result += int(c)
Technically speaking this is not casting: you call the int(..) builtin function which takes as input the string and produces its equivalent as int. You do not cast in Python since it is a dynamically typed language.
Note that it is of course possible that c contains text that is not an integer. Like 'the number fifteen whohaa'. Of course int(..) cannot make sense out of that. In that case it will raise a ValueError. You can use try-except to handle these:
try:
result += int(c)
except ValueError:
# ... (do something to handle the error)
pass
In Python, you cast a string to an integer by using a function int().
result += int(c)
def digit_sum(n):
numsum=[]
add_up=str(n)
for n in add_up[0: len(add_up)]:
numsum.append(int(n))
return sum(numsum)
print digit_sum(1234)
Basically, you need to cast string to integer using int(n)

sum of two number using def function in python [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
feed function using raw_input of sys.argv for sum of two number goes just showing in list
def sum_double(a, b):
sum = a+b
if a == b:
sum = sum*2
print sum
return sum
else :
print sum
return sum
sum_double(a = raw_input("a"),b = raw_input("b"))
if we feed input are 1 and 2 then it will showing 12 instead of 3
raw_input returns a string and not a number. With string inputs, + simply concatenates the two strings together.
'1' + '2'
# '12'
If you want to perform numeric operations (such as addition), you need to first convert the output of raw_input to a number using int (for integers) or float (for floating point numbers).
sum_double(a = int(raw_input("a")),b = int(raw_input("b")))
raw_input returns a string ('1' and '2'). Summing them gives you '12'.
In order to sum numbers, not strings, convert the strings to numbers:
sum_double(a = int(raw_input("a")),b = int(raw_input("b")))

How to check if result is integer in Python? [duplicate]

This question already has an answer here:
How to check if a numeric value is an integer?
(1 answer)
Closed 7 years ago.
I have simple task to count number, for example:
a = 7
b = 9
result = 0
for _ in (0:100):
result = a / b
b += 1
How I can stop the for loop when result is an integer?
Checking if method is_integer() wasn't meet my expectations.
I have to use Python 2.6
Use % 1. Modular arithmetic returns the remainder, so if you try to divide by 1 and the remainder is 0, it must be an integer.
if result % 1 == 0:
print "result is an integer!"
OR use the method mentioned in this post or this post:
if result.is_integer():
As mentioned in the comments, you can use:
while result % 1 != 0:
to make the loop repeat until you get an integer.
If you're using python 2.6 you could use:
isinstance(result, (int, long))
to check if your result is an integer.
You could use the type method:
if type(a/b) == int:
break
You could also use the while loop approach as suggested by other answers:
while type(a/b) != int:
# your code

Need help to understand code in python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
first = int(input('first int: '))
second = int (input('second int: '))
result =0
if first and second:
result =1
elif not first:
result =2
elif first or second:
result=3
else:
result=4
print(result)
when I enter 1 and 0, the result is 3. I would appreciate if anyone could add some explanation.
You are using or- it means the statement will return True when it first finds True.
When you say 5 or 9, both 5 and 9 represent truism (as does any non-zero value). So it returns the first - 5 in this case. When you say 9 or 5, it returns 9.
EDIT: k = 1 or 0 would evaluate to True since 1 represents truism. Thus, as per your code, result is 3
In many program languages, the boolean operations only evaluate their second argument if needed for their outcome. These called short-circuit operator. And in python, according the docs, it returns:
x or y : if x is false, then y, else x
x and y : if x is false, then x, else y

Categories

Resources