0

I am trying to write a code that finds the multiplicative identity of a finite ring with addition modulo n and multiplication modulo n as the operations. Basically it should return that element e such that e*y%n=y for all y in R

What I have tried is the following:

U=[e for e in R for y in R if e*y%10==y]
Unity=[x for x in U if U.count(x)==len(R)]
if Unity:
   print(“The given ring has multiplicative identity”,Unity[0])
else: 
   print(“The given ring has no multiplicative identity)

The problem with this is that the list U is not taking only that e which works for all y in R. That is the reason I’m creating another list that counts the number of times an e has occurred in U.

I was wondering if I could avoid having to create the second list by instead using some inbuilt function that works as “for all”? I checked online and found the .all() function but I am not sure how to use it here.

R_D
  • 103
  • 3
  • I'm curious why you'd use Python for this, rather than any of the several popular dedicated maths languages. – Mike 'Pomax' Kamermans Aug 07 '23 at 04:49
  • It’s one of the weird aspects of our mathematics syllabus. We have to learn python as a programming language and learn to write python codes based on the things we learn in theory. – R_D Aug 07 '23 at 06:46

2 Answers2

1

Python has an all function, which does most of what you want. Rather than having two nested for clauses in your list comprehension, you'll want a separate generator expression for the y loop, inside of all:

U = [e for e in R if all(e*y%10=y for y in R)]
Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • 1
    This is exactly what I am looking for. Thank you. I think there has to be a double equal to sign in the syntax though. – R_D Aug 07 '23 at 06:45
0

You can pass an iterable to all

U = [e for e in R for y in R if e*y%10==y]

Then pass U to all

all(U.count(x)==len(R) for x in U)

This works as a generator would, example

all returns True if all elements are True

InsertCheesyLine
  • 1,112
  • 2
  • 11
  • 19