@denum999

Как составить грамотное условие выполнения?

Всем привет!

Помогите пожалуйста составить грамотное условия для выполнения, задача следующая:

Человеку предлагается случайное животное и список отрядов животных. Человек должен написать, к какому отряду относится животное, которое ему выпало. Если правильно - надпись " Верно" если нет, - соответственно" Не верно". Спасибо!
вот код:

import random
allanimals = ["Lion","Zebra","Tiger","Horse","Elephant","Lamb","Raven","Parrot","Dove","Wolf","Hyena"]

cats = ["Tiger","Lion"]
horses = ["Zebra","Horse","Lamb"]
birds = ["Raven","Parrot","Dove"]
elephants = ["Elephant"]
dogs = ["Wolf","Hyena"]

allclasses = [cats,horses,birds,elephants,dogs]
classes = ["cats","horses","birds","elephants","dogs"]
randomanimal = (random.choice(allanimals))

print("animal:",(randomanimal))

print("classes:",classes)

classofanimal = input("What class does this animal belong to?:")


Что дальше? :)
  • Вопрос задан
  • 168 просмотров
Решения вопроса 1
@anerev
Я бы сделал так:
dictanimal = {'cats' : ["Tiger","Lion"], 'horses' :  ["Zebra","Horse","Lamb"], 
'birds' : ["Raven","Parrot","Dove"], 'elephants' : ["Elephant"], 'dogs' : ["Wolf","Hyena"]}

d = random.choice(list(dictanimal.keys()))
rand = random.choice(dictanimal[d])
print("animal:", rand)

classofanimal = input("What class does this animal belong to?:")

if classofanimal in list(dictanimal.keys()) and rand in dictanimal[classofanimal]:
    #code
Ответ написан
Пригласить эксперта
Ответы на вопрос 3
Rsa97
@Rsa97
Для правильного вопроса надо знать половину ответа
classes = [...]
...
if classofanimal in clases:
Ответ написан
@extroot
Вот простое решение, не самое оптимальное:
import random
animals = {'Lion': 'cats',
           'Zebra': 'horses',
           'Tiger': 'cats',
           'Horse': 'horses',
           'Elephant': 'elephant',
           'Lamb': 'horses',
           'Raven': 'birds',
           'Parrot': 'birds',
           'Wolf': 'dogs',
           'Hyena': 'dogs',
           'Dove': 'birds'}

animal = (random.choice(list(animals.keys())))
print("classes:", *set(animals.values()))
print("animal:", animal)

inp = input("What class does this animal belong to?: ")
print("Верно" if inp == animals[animal] else "Не верно")
Ответ написан
Комментировать
adugin
@adugin Куратор тега Python
import random
from collections import defaultdict


class mydefaultdict(defaultdict):
    
    def __getattr__(self, attr):
        return self[attr]
    
    def __setattr__(self, attr, val):
        self[attr] = val
    
    def classify(self, animal, unknown='Unknown'):
        for subclass, species in self.items():
            if animal in species:
                return subclass
        return unknown
    
    @property
    def all(self):
        all_animals = []
        for subclass, species in self.items():
            all_animals.extend(species)
        return all_animals
            
    @property
    def random(self):
        return random.choice(self.all)
        

def taxonomy():
    return mydefaultdict(taxonomy)


animals = tree()
animals.cats.Tiger
animals.cats.Lion
animals.horses.Zebra
animals.horses.Horse
animals.horses.Lamb
animals.birds.Raven
animals.birds.Parrot
animals.birds.Dove
animals.elephants.Elephant
animals.dogs.Wolf
animals.dogs.Hyena

random_animal = animals.random
answer = input(f'What class does {random_animal} animal belong to? ')
correct_answer = animals.classify(random_animal)
print(['Не верно', 'Верно'][answer == correct_answer])
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы