'How can I use a set here to avoid duplication?
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]
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Akash garg |
