[Tutor] tables and dictionaries
Tim Peters
tutor@python.org
Sat, 5 May 2001 01:56:11 -0400
[Julieta Rangel]
> I'm trying to write a program that given a finite set (say, up to 30
> elements) and a table, the program figures out whether the set is a
> group. I need to have the user enter the elements on the set and
> store them on a list. Once on this list, I want the user to enter
> a table, but for this, I need for python to pair each element with
> every element on the list so I can ask for the table.
Hmm! For a set with 30 elements, that's 30*30 == 900 "products". So you may
want to read this information from a file instead.
> Let's say that the set consists of elements
> [e,a,b,ab]. I need to ask the user
>
> e*e=? a*e=? b*e=? ab*e=?
> e*a=? a*a=? b*a=? ab*a=?
> e*b=? a*b=? b*b=? ab*b=?
> e*ab=? a*ab=? b*ab=? ab*ab=?
>
> Since I don't know what the set will consist of, I need to find a way
> so that once the user enters the set, the computer pairs the elements
> together as I did above, asks for the required input and stores it in
> a dictionary. Can this be done?
Yes, and quite easily (if you know how <wink>) -- I'll attach a small
program. Here's a sample run, where to *try* to make it clearer I've
artificially added "<>" brackets around the input I typed in; everything else
is program output:
Enter comma-separated list of elements, like a,b,c: <a,b>
a*a=? <a>
a*b=? <b>
b*a=? <c>
Oops! c is not in ['a', 'b'] -- try again.
b*a=? <b>
b*b=? <a>
a * a = a
a * b = b
b * a = b
b * b = a
> If so, how? If this can be done, it would be easier to check for
> the four properties of a group[closure under binary operation,
Note that the program above rejected my attempt to enter c, so the *input*
routine ensures closure.
> associativity : a*(a*b)=(a*a)*b; identity and inverses).
> ...
These are, of course, harder to check. I wouldn't call it "tedious", though!
It seems like a very nice exercise for learning how to use loops and logic.
oh-ok-it's-tedious<wink>-ly y'rs - tim
import string
elts = raw_input("Enter comma-separated list of elements, like a,b,c: ")
elts = string.split(elts, ",")
product = {}
for x in elts:
for y in elts:
prompt = "%s*%s=? " % (x, y)
need_good_result = 1
while need_good_result:
z = raw_input(prompt)
if z in elts:
need_good_result = 0
else:
print "Oops!", z, "is not in", elts, "-- try again."
product[x, y] = z
# Display the table.
items = product.items()
items.sort()
for (x, y), z in items:
print x, "*", y, "=", z