Is there a function for “forall” in python?

658 views Asked by At

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.

2

There are 2 answers

1
Blckknght On BEST ANSWER

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)]
0
InsertCheesyLine On

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