Logicals PROLOG vs Python
- pillmuncher
- User
- Beiträge: 1484
- Registriert: Samstag 21. März 2009, 22:59
- Wohnort: Pfaffenwinkel
@ALSO: Entweder wir kommunizieren öffentlich oder über PMs. Bitte entscheide dich. Und ich weiß nicht, was du mit Modul meinst. Yogic? Oder dein Modul?
In specifications, Murphy's Law supersedes Ohm's.
- pillmuncher
- User
- Beiträge: 1484
- Registriert: Samstag 21. März 2009, 22:59
- Wohnort: Pfaffenwinkel
Hier ist noch eine Lösung, ganz ohne Prolog:
Code: Alles auswählen
from pprint import pprint
def find_solutions(candidates, solution, tally):
if not candidates:
yield solution
else:
variable, numbers = candidates.popitem()
for number in numbers - tally:
solution[variable] = number
tally.add(number)
yield from find_solutions(candidates, solution, tally)
tally.remove(number)
candidates[variable] = numbers
def solutions(equations):
candidates = {}
for variables, numbers in equations:
for variable in variables:
if variable not in candidates:
candidates[variable] = set(numbers)
else:
candidates[variable].intersection_update(numbers)
return find_solutions(candidates, {}, set())
def main():
equations = ([
(['a', 'd', 'e', 'f', 'j', 'k', 'l'], [2, 8, 6, 9, 1, 7, 4]),
(['a', 'b', 'c', 'e', 'h', 'i', 'j'], [11, 1, 12, 8, 4, 5, 10]),
(['b', 'c', 'd', 'e', 'f', 'g', 'h'], [5, 2, 9, 8, 11, 3, 10]),
(['a', 'd', 'f', 'g', 'i', 'j', 'k'], [4, 6, 12, 1, 2, 9, 3]),
(['b', 'c', 'g', 'h', 'j', 'l'], [3, 4, 7, 11, 5, 10]),
])
for each in solutions(equations):
print()
pprint(list(sorted(each.items())))
if __name__ == '__main__':
main()
In specifications, Murphy's Law supersedes Ohm's.