查看: 1363| 回复: 4
跳转到指定楼层
上一主题 下一主题
收起左侧

[学Python/Perl] 新手学python求问一个关于prime的题目?

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
正在学习python,希望大家看贴海涵。 嘿嘿


正在疯狂练习function.. 现在碰到一个题:
A function is_prime that receives an integer as a parameter, check if this integer is a prime number and returns a boolean value depending on the result.

需要run后得出如下结果:
The following is a sample output. User inputs is displayed in bold
Enter a value: 5
Enter the next value: 8
Enter the next value: -6
Incorrect Value
Enter another value: 6
Enter the next value: 3
Enter the next value: 5
Enter the next value: 12
Enter the next value: 45
Enter the next value: 21
Enter the next value: 8
Enter the next value: -1
You entered the following values : [5, 8, 6, 3, 5, 12, 45, 21, 8] From you list, the prime numbers are : {3, 5, 6, 8, 12, 45, 21}

疯狂的写了之后只能得到:
inputs = []

while True:
    inp = int(input("Enter a value: "))
    if inp == -1:
        break
    elif inp >=0:
        inputs.append(int(inp))
    else:
        print("Incorrect value")

    print(inputs)

感觉不太对.... 求指导。好像需要好几个loop才能得到。轻拍谢谢大家~~~

上一篇:Alien Dictionary
下一篇:有没有人想一起合买 a collection of data science take home challenge
推荐
337845818 2019-9-27 12:17:18 | 只看该作者
全局:
6我合计也不是prime啊?
你这代码除了直接append也没干嘛啊
回复

使用道具 举报

全局:
本帖最后由 联氢人 于 2019-9-30 05:53 编辑

如果没有输入范围限制并且对复杂度要求没那么严格的话就一个一个看呗
def isPrime(k):
    for i in range(2, int(math.sqrt(k))):
        if not k%i:
            return False
    return True

如果有输入范围限制而且有复杂度要求的话就把范围内的prime提前找出来,用的时候看这个在不在prime那个set里(preprocess O(n), each operation O(1))
很可能还有更好的解法,不过暂时没有更多说明的情况下就先不展开想了(为自己懒找借口中)
回复

使用道具 举报

推荐
337845818 2019-9-28 02:36:58 | 只看该作者
全局:

def isPrime(k):
        if k < 2: return False;
        if k < 4: return True;
        for i in range(2, k):
                if i * i > k: break;
                if k % i == 0: return False;
        return True
回复

使用道具 举报

🔗
 楼主| helloconey09 2019-9-28 00:53:03 | 只看该作者
全局:
337845818 发表于 2019-9-27 12:17
6我合计也不是prime啊?
你这代码除了直接append也没干嘛啊

确实是。。。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表