如何在这里使用集合避免重复?

发布于 2025-01-22 15:50:39 字数 1094 浏览 1 评论 0原文

该代码打算打印副本编号模型的总和和列表。我想在不重复的情况下打印Modulo号码,并尝试使用集合,但遇到了问题。这是原始代码。我该如何更改它以避免重复。

import math

def IsRelPrime(n):
    arr=[]
    for j in range(1,n+1):
        if math.gcd(n,j)==1:
            arr += [j]
    return(arr)

def Sums(n,mod):
    s=sum(IsRelPrime(n))
    l=len(IsRelPrime(n))
    num_range=list(range(1,n+1))
    res=[i % mod for i in IsRelPrime(n)]
    print ( "The sum of the first %d integers is %d" %(n,sum(num_range)))
    print("The sum of the %d coprime integers is %d:" % (l,s))
    print("The sum of the list modulo %d is %d " % (mod,sum(res)))
    print("The list of integers modulo %d is " % (mod))
    print(*res ,sep = ", ")
    print("The terms relatively prime to %d and %d are %a"  % (n,mod,IsRelPrime(n)))

Sums(15,4)

这是输出

The sum of the first 15 integers is 120
The sum of the 8 coprime integers is 60:
The sum of the list modulo 4 is 12 
The list of integers modulo 4 is 
1, 2, 0, 3, 0, 3, 1, 2
The terms relatively prime to 15 and 4 are [1, 2, 4, 7, 8, 11, 13, 14]

This code intends to print sums and lists of coprime numbers modulo. I would like to print the modulo numbers without repetition and have tried to use a set but have encountered problems. Here's the original code. How can I alter this to avoid the repetition.

import math

def IsRelPrime(n):
    arr=[]
    for j in range(1,n+1):
        if math.gcd(n,j)==1:
            arr += [j]
    return(arr)

def Sums(n,mod):
    s=sum(IsRelPrime(n))
    l=len(IsRelPrime(n))
    num_range=list(range(1,n+1))
    res=[i % mod for i in IsRelPrime(n)]
    print ( "The sum of the first %d integers is %d" %(n,sum(num_range)))
    print("The sum of the %d coprime integers is %d:" % (l,s))
    print("The sum of the list modulo %d is %d " % (mod,sum(res)))
    print("The list of integers modulo %d is " % (mod))
    print(*res ,sep = ", ")
    print("The terms relatively prime to %d and %d are %a"  % (n,mod,IsRelPrime(n)))

Sums(15,4)

Here's the output

The sum of the first 15 integers is 120
The sum of the 8 coprime integers is 60:
The sum of the list modulo 4 is 12 
The list of integers modulo 4 is 
1, 2, 0, 3, 0, 3, 1, 2
The terms relatively prime to 15 and 4 are [1, 2, 4, 7, 8, 11, 13, 14]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱花落人离去 2025-01-29 15:50:39

列出的两种方式使用它,

您可以以第一个

res={i % mod for i in IsRelPrime(n)}

第二秒

print(*set(res) ,sep = ", ")

请告诉我是否有其他问题

You can use it in any of the two ways listed below

First

res={i % mod for i in IsRelPrime(n)}

Second

print(*set(res) ,sep = ", ")

Please let me know if comments if you have further questions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文