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
Related
This question already has answers here:
Is the shortcircuit behaviour of Python's any/all explicit? [duplicate]
(4 answers)
Closed 9 months ago.
Will python's all function exit as soon as it finds a False in the iterable? Or will it continue checking the rest?
For example, if i is not divisible by 20, will the below code continue checking if it is divisible by 19 and 18 and so on?
def min_divisible(target_n):
'''
Returns the smallest number that is divisible by all integers between 1 and n
'''
i = target_n
while not all((i%j == 0) for j in range(target_n,2,-1)):
i+=target_n
return f'{i:,}'
print(min_divisible(20))
all will stop the iteration as soon as it encounters a "falsey" object. You can see this with a simple example:
def produce_numbers():
for k in range(10):
yield k
print(k)
all(k < 3 for k in produce_numbers())
This prints
0
1
2
This is spelled out in Python's documentation. It states that the following is a functionally equivalent definition of all:
def all(iterable):
for element in iterable:
if not element:
return False
return True
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]))
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)
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
This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I'm just getting into Python and I really like the terseness of the syntax. However, is there an easier way of writing an if-then-else statement so it fits on one line?
For example:
if count == N:
count = 0
else:
count = N + 1
Is there a simpler way of writing this? I mean, in Objective-C I would write this as:
count = count == N ? 0 : count + 1;
Is there something similar for Python?
Update
I know that in this instance I can use count == (count + 1) % N.
I'm asking about the general syntax.
That's more specifically a ternary operator expression than an if-then, here's the python syntax
value_when_true if condition else value_when_false
Better Example: (thanks Mr. Burns)
'Yes' if fruit == 'Apple' else 'No'
Now with assignment and contrast with if syntax
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
vs
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True
Moreover, you can still use the "ordinary" if syntax and conflate it into one line with a colon.
if i > 3: print("We are done.")
or
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
count = 0 if count == N else N+1
- the ternary operator. Although I'd say your solution is more readable than this.
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>
with your code-snippet it would become,
count = 0 if count == N else N + 1