1.内置模块math加filter函数

2.内置模块math加for,if循环

3.numpy 库加if循环

4. for,if 循环加表达式(只适合正数)

5. for,if 循环加内置函数

6. 负数和复数求平方根的方法:

7. filter 和lambda实现
>>> import math
>>> list(filter(lambda x:int(math.sqrt(x))*int(math.sqrt(x))==x,range(101)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#以下这个是不对的,做个比较
>>> a=range(1,101)
>>> list(filter(lambda x:math.sqrt(x)*math.sqrt(x)==x,a))
[1, 4, 9, 11, 14, 16, 17, 21, 22, 25, 27, 30, 33, 34, 35, 36, 39, 41, 42, 44, 46, 47, 49, 53, 54, 55, 56, 57, 62, 64, 67, 68, 69, 70, 71, 74, 79, 81, 83, 84, 85, 86, 88, 90, 91, 93, 98, 99, 100]
>>> list(filter(lambda x:math.sqrt(x)*math.sqrt(x)!=x,a))
[2, 3, 5, 6, 7, 8, 10, 12, 13, 15, 18, 19, 20, 23, 24, 26, 28, 29, 31, 32, 37, 38, 40, 43, 45, 48, 50, 51, 52, 58, 59, 60, 61, 63, 65, 66, 72, 73, 75, 76, 77, 78, 80, 82, 87, 89, 92, 94, 95, 96, 97]
>>>
方法一: 使用内置模块
>>> import math
>>> math.pow(12, 2) # 求平方
144.0
>>> math.sqrt(144) # 求平方根
12.0
方法二: 使用表达式
>>> 12 ** 2 # 求平方
144
>>> 144 ** 0.5 # 求平方根
12.0
>>>
方法三: 使用内置函数
>>> pow(12, 2) # 求平方
144
>>> pow(144, .5) # 求平方根
12.0
参考:https://blog.youkuaiyun.com/jerry_1126/article/details/82917405
本文介绍了如何使用Python找出1到100之间平方根为整数的数,包括结合内置模块math、filter函数、numpy库、for和if循环以及表达式的不同实现方式,同时也探讨了负数和复数的求平方根方法。
6272

被折叠的 条评论
为什么被折叠?



