Math.sqrt giving floating values in python [duplicate] - python

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)

Related

Getting a list of prime numbers upto n [duplicate]

This question already has answers here:
How to create the most compact mapping n → isprime(n) up to a limit N?
(29 answers)
Getting wrong answers for prime numbers
(4 answers)
Closed last year.
def primetest(n):
if n<=1:
return false
"""Test if N is prime"""
for i in range(2,int(n/2)+1):
if(n%i)==0:
return false
return true
Hello so above I have my code that tells you if n is prime or not by returning true or false. Now I need to write a method called primelist() which inputs a positive integer n and outputs an ordered list of primes 2 through p. Below I have added my code but when I go to test it, for example, I test primelist(7)==is_prime(7) I get false but I should be getting true.
def primelist(n):
for i in range(2,n+1):
if primetest(i):
print(I,end=" ")
In order to test if the number is prime you need to check all the integers from 2 to the square root of n. Only if for none of them, n is divisible can you be sure it's a prime number.
Also as pointed out in the comments there are some syntactic/indentation issues e.g. True and False need to be capitalized.
def primetest(n):
# Test if N is prime
if n <= 1:
return False
for i in range(2,int(n**(1/2))+1):
if(n%i)==0:
return False
return True
Edit: to work for integers less than 2 you have to treat these separately.
For the 2nd part of your question primelist(7)==is_prime(7) will always be False, because you're comparing a boolean with None type (since your 2nd function doesn't actually return anything).
Also the following might give a nicer output:
def primelist(n):
primes = []
for i in range(2,n+1):
if primetest(i):
primes.append(i)
print(*primes, sep = " ")

type(number) == (float or int) returns false python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
I'm checking if the argument of a function is a float or an int with this line and it keeps return false, can anyone explain why this happens?
def distance_from_zero(number):
if type(number) == (int or float):
return abs(number)
else:
return "Nope"
This is the shortest, most pythonic way.
Use isinstance:
if isinstance(number, (int, float)):
In the spirit of Easier to ask for forgiveness than permission you could use an exception instead of explicit type checking, like
def distance_from_zero(number):
try:
return abs(number)
except TypeError:
return 'Nope'
for x in [1, 1.1, 'a']:
print(x, distance_from_zero(x))
1 1
1.1 1.1
a Nope
IMO this is often clearer and more foolproof.

Reverse digits of an integer in Python [duplicate]

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]))

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

Python Program on Perfect Squares [duplicate]

This question already has answers here:
Check if a number is a perfect square
(25 answers)
Closed 9 years ago.
I wrote this python function which takes a list as a parameter and determines which elements of the list are perfect squares and then returns a new list of just those select elements.
Here is my function:
def square(n):
return n**2
def perfectSquares1(L):
import math
m=max(L)
for n in L:
if type(n) is int and n>0:
Result=map(square,range(1,math.floor(math.sqrt(m))))
L1=list(Result)
L2=list(set(L).intersection(set(L1)))
return L2
But now I'm trying to re-work it a little: I want to write a one-line Boolean function that takes n as a parameter and returns True if n is a perfect square and returns false otherwise.
Any advice? I can't figure out a way to make it only one line.
lambda n: math.sqrt(n) % 1 == 0
You can do:
import math
def perfect_sq(n):
return n == int(math.sqrt(n)) * int(math.sqrt(n))
Or you can use:
import math
def perfect_sq(n):
return n == int(math.sqrt(n)) ** 2
Could use the modulo operator:
>>> def perfectsquare(n):
... return not n % n**0.5
...
>>> perfectsquare(36)
True
>>> perfectsquare(37)
False
>>> perfectsquare(25)
True
>>> perfectsquare(4215378*4215378)
True

Categories

Resources