Created
April 19, 2019 20:58
-
-
Save Jordan-Cottle/f4cbe00a9e6511d291b99faf95566b00 to your computer and use it in GitHub Desktop.
Computes the set of positive even numbers with no reapted digits less than 1000 using cartesian products and unions of sets. Checks answer using less obtuse methods.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cartesianProduct(a, b, repeatDigit = False): | |
if repeatDigit: | |
return {f'{aItem}{bItem}' for aItem in a for bItem in b} | |
else: | |
return {f'{aItem}{bItem}' for aItem in a for bItem in b if all([char not in bItem for char in list(aItem)])} | |
odd = {'1','3','5','7','9'} | |
even = {'0','2','4','6','8'} | |
natEven = {'2','4','6','8'} | |
# odd X even | |
oe = cartesianProduct(odd, even) | |
#print(sorted(list(oe))) | |
# natEven X even | |
ee = cartesianProduct(natEven, even) | |
#print(sorted(list(ee))) | |
# odd X odd X even | |
ooe = cartesianProduct(cartesianProduct(odd, odd), even) | |
#print(sorted(list(ooe))) | |
# odd X even X even | |
oee = cartesianProduct(oe, even) | |
#print(sorted(list(oee))) | |
# even X odd X even | |
eoe = cartesianProduct(cartesianProduct(natEven, odd), even) | |
#print(sorted(list(eoe))) | |
# even X even X even | |
eee = cartesianProduct(ee, even) | |
#print(sorted(list(eee))) | |
evenWithNoRepeatedDigits = natEven.union(oe).union(ee).union(ooe).union(oee).union(eoe).union(eee) | |
nums = set() | |
for i in range(1, 1000): | |
num = str(i) | |
if len(num) == len(set(list(num))): | |
if i % 2 == 0: | |
nums.add(num) | |
print(f'Even numbers with no repeated digits in range [1, 999]:\n{sorted(list(nums), key=int)}') | |
print(f'Same set, but computed using unions oand cartesian products of smaller sets:\n{sorted(list(evenWithNoRepeatedDigits), key=int)}') | |
print('The two sets are the same: ', nums == evenWithNoRepeatedDigits) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment