Verfasst: Montag 13. April 2009, 11:21
@bremer
Nutz doch bitte ein Wörterbuch ... exec und eval sind hier völlig überflüssig.
Nutz doch bitte ein Wörterbuch ... exec und eval sind hier völlig überflüssig.
Seit 2002 Diskussionen rund um die Programmiersprache Python
https://www.python-forum.de/
Code: Alles auswählen
switch = True
players = {True: "1", False: "2"}
heaps = {"a": 3, "b": 4, "c": 5}
print("""Sizes of heaps:
A B C""")
while any((heaps["a"], heaps["b"], heaps["c"])):
print(heaps["a"], heaps["b"], heaps["c"])
print()
print("Turn of player", players[switch] + ".")
try:
number = int(input("How many? "))
heap = (input("Heap a, b or c? ")).lower()
if not (0 < number <= heaps[heap]) or heap not in heaps:
raise ValueError
else:
heaps[heap] -= number
switch = not switch
except (KeyError, ValueError):
print("Not possible.")
switch = not switch
print("Player", players[switch], "is the winner.")
Code: Alles auswählen
if heap not in heaps or not (0 < number <= heaps[heap]):
Code: Alles auswählen
while any(heaps.itervalues()):
Code: Alles auswählen
switch = True
players = {True: "1", False: "2"}
heaps = {"a": 3, "b": 4, "c": 5}
print("Sizes of heaps:", "A B C", sep="\n")
while any(heaps.values()):
print(*heaps.values())
print()
print("Turn of player", players[switch] + ".")
number = int(input("How many? "))
heap = input("Heap a, b or c? ").lower()
if heap in heaps and 0 < number <= heaps[heap]:
heaps[heap] -= number
switch = not switch
else:
print("Not possible.")
switch = not switch
print("Player", players[switch], "is the winner.")
Code: Alles auswählen
#!/usr/bin/env python3
def main():
heap_names = ["a", "b", "c"]
heaps = dict(zip(heap_names, [3, 4, 5]))
switch = True
players = {True: "1", False: "2"}
print("Sizes of heaps:\nA B C")
while any(heaps.values()):
assert all(count >= 0 for count in heaps.values())
print(" ".join(str(heaps[name]) for name in heap_names))
print()
print(f"Turn of player {players[switch]}.")
try:
number = int(input("How many? "))
except ValueError:
print("Please enter a number!")
else:
heap_name = input("Heap a, b or c? ").lower()
if heap_name in heaps:
if 0 < number <= heaps[heap_name]:
heaps[heap_name] -= number
switch = not switch
else:
print("Please enter valid number!")
else:
print("Please enter a valid heap name!")
print(f"Player {players[not switch]} is the winner.")
if __name__ == "__main__":
main()