Python Program on Perfect Squares [duplicate] - python

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

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 = " ")

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)

Find element with maximum value recursively in python [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
I would write a recursive function that take a list of number as argument and return maximum element of the list. I don't want to use max() function.
a = [2,1,3,5]
def f(a, m=0):
if m<a[0]:
m = a[0]
if len(a) == 1:
return m
else:
f(a[1:])
print(f(a))
but it returns None! how can I fix it?
You should define m in your else statement and add a return in it:
a = [2,1,3,5]
def f(a, m=0):
if m<a[0]:
m = a[0]
if len(a) == 1:
return m
else:
m = f(a[1:], m)
return m
print(f(a))

I learned the high order function recently. I tried to write some codes using high order function but I got stucked [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 3 years ago.
Write a function that takes in a number and determines if the digits contain two adjacent 8s.
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR CODE HERE ***"
I tried to call double_eights by passing n//10 as an argument.
I kept encountering errors when 2882 was passed in as an argument. The double eights function returned nothing when that argument was passed in. I attached what I've tried so far.
if n < 10:
return False
elif (n % 10 == 8) and ((n // 10) % 10 == n % 10):
return True
double_eights(n //10)
Doctests for double_eights
>>> from lab01_extra import *
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
# Error: expected
# True
# but got
You need to return that last recursive call, otherwise None will be returned by default on inputs that don't satisfy the conditions of the if and elif statements:
def double_eights(n):
if n < 10:
return False
elif (n % 10 == 8) and ((n // 10) % 10 == 8): # 8 instead of n % 10
return True
return double_eights(n // 10)
# Output:
print(double_eights(8)) # False
print(double_eights(88)) # True
print(double_eights(2882)) # True
print(double_eights(880088)) # True
print(double_eights(12345)) # False
print(double_eights(80808080)) # False
The 8 instead of n % 10 is there because the and evaluates the second term only if the first one is True (in which case you know that n % 10 == 8 so why re-calculate it?).
note: double_eights is not a higher-order function, but it is a recursive function.

I am learning python. I am seeking insights for this program. Given an int array length 2, return True if it contains a 2 or a 3 [duplicate]

This question already has answers here:
Return True if array contains a 2 or a 3
(5 answers)
Closed 7 years ago.
def has23(nums):
if (2 or 3) in nums:
return True
else:
return False
result is coming out right for majority part.
but for has23[3,3] or [3,9] it is coming false.
I have 'or' argument in the code, shouldn't it mean that it will look for 2 and 3 more and n will give true if it finds any of it.
please tell me, what concept, I am missing over here?
def has23(nums):
return (2 in nums) or (3 in nums)
the expression (2 or 3) returns the value 2 so the list [3,3] would not pass.
2 or 3 evaluates to 2, so you're checking if 2 is in nums. Instead, say if 2 in nums or 3 in nums:. You don't really need the if statement, however, because you can just return the results of the expression:
return 2 in nums or 3 in nums
You can check each element explicitly if it is 2 or 3:
def has23(nums):
for i in nums:
if i in (2, 3):
return True
return False
Another way would be using generators:
def has23(nums):
return any(i in (2,3) for i in nums)
you should do this instead, it'll do the logic you want.
def has23(nums):
if 2 in nums or 3 in nums:
return True
else:
return False

Categories

Resources