Best Python code snippet using ATX
test_eggmodels.py
Source:test_eggmodels.py  
1#!/usr/bin/env python32import random3from typing import List4import click5import pytest6from hopla.hoplalib.errors import YouFoundABugRewardError7from hopla.hoplalib.hatchery.eggmodels import Egg, EggCollection, EggException8from hopla.hoplalib.hatchery.egg_data import EggData9from hopla.hoplalib.hatchery.hatchpotion_data import HatchPotionData10from hopla.hoplalib.hatchery.hatchpotionmodels import HatchPotion11_SAMPLE_SIZE = 912class TestEgg:13    def test__init__invalid_name_fail(self):14        name = "InvalidName"15        with pytest.raises(EggException) as exec_info:16            Egg(name)17        assert str(exec_info.value).startswith(f"{name} is not a valid egg name.")18        assert exec_info.errisinstance((YouFoundABugRewardError, click.ClickException))19    @pytest.mark.parametrize(20        "egg_name,quantity",21        list(zip(random.sample(EggData.egg_names, k=_SAMPLE_SIZE),22                 range(-_SAMPLE_SIZE, 0)))23    )24    def test__init__invalid_quantity_fail(self, egg_name: str, quantity: int):25        with pytest.raises(EggException) as exec_info:26            Egg(egg_name, quantity=quantity)27        assert str(exec_info.value).startswith(f"{quantity} is below 0.")28        assert exec_info.errisinstance((YouFoundABugRewardError, click.ClickException))29    @pytest.mark.parametrize("egg1,egg2,expected_equals", [30        (Egg("Horse"), Egg("Horse"), True),31        (Egg("Seahorse", quantity=1), Egg("Seahorse"), True),32        (Egg("Snake", quantity=1), Egg("Snake", quantity=2), False),33        (Egg("Whale"), Egg("Rat"), False),34        (Egg("Rooster", quantity=0), Egg("TRex", quantity=0), False),35        (Egg("Penguin", quantity=1), Egg("Owl", quantity=4), False),36    ])37    def test__eq__(self, egg1: Egg, egg2: Egg, expected_equals: bool):38        assert (egg1 == egg2) is expected_equals39    def test__repr__(self):40        name, quantity = "Dolphin", 941        egg = Egg(name, quantity=quantity)42        result: str = repr(egg)43        assert result == f"Egg({name}: {quantity})"44    @pytest.mark.parametrize("standard_egg_name", ["Wolf", "Fox", "FlyingPig", "Dragon"])45    def test_is_standard_egg(self, standard_egg_name: str):46        egg = Egg(standard_egg_name)47        assert egg.is_standard_egg() is True48        assert egg.is_quest_egg() is False49    @pytest.mark.parametrize("quest_egg_name", [50        "Dolphin", "Gryphon", "Deer", "Egg", "Seahorse", "Parrot"51    ])52    def test_is_quest_egg(self, quest_egg_name: str):53        egg = Egg(quest_egg_name)54        assert egg.is_standard_egg() is False55        assert egg.is_quest_egg() is True56    @pytest.mark.parametrize(57        "egg_name,potion_name",58        list(zip(EggData.drop_egg_names,59                 HatchPotionData.hatch_potion_names))60    )61    def test_can_be_hatched_by_standard_egg_true(self, egg_name: str,62                                                 potion_name: str):63        egg = Egg(egg_name)64        potion = HatchPotion(potion_name)65        # standard eggs can be hatched by any potion66        assert egg.can_be_hatched_by(potion) is True67    @pytest.mark.parametrize(68        "egg_name,potion_name",69        list(zip(EggData.quest_egg_names,70                 HatchPotionData.drop_hatch_potion_names))71    )72    def test_can_be_hatched_by_magic_egg_drop_potion_true(self,73                                                          egg_name: str,74                                                          potion_name: str):75        egg = Egg(egg_name)76        potion = HatchPotion(potion_name)77        # quest eggs can be hatched by standard potion78        assert egg.can_be_hatched_by(potion) is True79    @pytest.mark.parametrize(80        "egg_name,potion_name",81        list(zip(82            random.sample(EggData.quest_egg_names, k=_SAMPLE_SIZE),83            random.sample(HatchPotionData.non_drop_hatch_potion_names, k=_SAMPLE_SIZE)84        ))85    )86    def test_can_be_hatched_by_magic_egg_non_drop_potion_false(self,87                                                               egg_name: str,88                                                               potion_name: str):89        egg = Egg(egg_name)90        potion = HatchPotion(potion_name)91        # quest eggs cannot be hatched by non standard potion92        assert egg.can_be_hatched_by(potion) is False93class TestEggCollection:94    def test__init__empty__ok(self):95        collection = EggCollection()96        assert collection == EggCollection({})97        assert len(collection) == 098    def test__init__ok(self):99        collection = EggCollection({"Wolf": 0, "Whale": 42, "Horse": 2})100        assert len(collection) == 3101        assert collection["Wolf"] == Egg("Wolf", quantity=0)102        assert collection["Whale"] == Egg("Whale", quantity=42)103        assert collection["Horse"] == Egg("Horse", quantity=2)104    def test__eq__(self):105        assert EggCollection() == EggCollection()106        assert EggCollection() == EggCollection({})107        assert EggCollection({"Cow": 1}) == EggCollection({"Cow": 1})108        assert EggCollection({"Cow": 1}) != EggCollection({"Cow": 2})109        assert EggCollection({"Cow": 1}) != EggCollection({"Rat": 1})110        assert EggCollection() != EggCollection({"Ferret": 1})111    def test_values_ok(self):112        collection = EggCollection({"Wolf": 1, "Whale": 41, "Horse": 2})113        generator = collection.values()114        assert next(generator) == Egg("Wolf", quantity=1)115        assert next(generator) == Egg("Whale", quantity=41)116        assert next(generator) == Egg("Horse", quantity=2)117        with pytest.raises(StopIteration):118            _ = next(generator)119    def test_values_as_list_ok(self):120        collection = EggCollection({"Wolf": 1, "Whale": 41, "Horse": 2})121        result: List[Egg] = list(collection.values())122        expected: List[Egg] = [123            Egg("Wolf", quantity=1), Egg("Whale", quantity=41), Egg("Horse", quantity=2)124        ]125        assert result == expected126    def test__iter__ok(self):127        collection = EggCollection({"Wolf": 1, "Whale": 42, "Horse": 2})128        iterator = iter(collection)129        assert next(iterator) == "Wolf"130        assert next(iterator) == "Whale"131        assert next(iterator) == "Horse"132        with pytest.raises(StopIteration):133            next(iterator)134    def test_remove_egg_not_available_faile(self):135        collection = EggCollection({"Whale": 1})136        not_found_egg = "Unicorn"137        with pytest.raises(EggException) as exec_info:138            collection.remove_egg(Egg(not_found_egg))139        expected_msg = f"{not_found_egg} was not in the collection "140        assert str(exec_info.value).startswith(expected_msg)141    def test_remove_egg_ok(self):142        egg1_name, egg1_quantity = "Wolf", 1143        egg2_name, egg2_quantity = "Whale", 42144        egg3_name, egg3_quantity = "Horse", 2145        collection = EggCollection(146            {egg1_name: egg1_quantity, egg2_name: egg2_quantity, egg3_name: egg3_quantity}147        )148        collection.remove_egg(Egg(egg1_name))149        collection.remove_egg(Egg(egg2_name))150        collection.remove_egg(Egg(egg3_name))151        assert collection[egg1_name] == Egg(egg1_name, quantity=egg1_quantity - 1)152        assert collection[egg2_name] == Egg(egg2_name, quantity=egg2_quantity - 1)153        assert collection[egg3_name] == Egg(egg3_name, quantity=egg3_quantity - 1)154    def test_get_standard_egg_collection_ok(self):155        egg1_name, egg1_quantity = "Wolf", 1156        egg2_name, egg2_quantity = "Whale", 42  # quest egg157        egg3_name, egg3_quantity = "Fox", 0158        egg4_name, egg4_quantity = "PandaCub", 69159        collection = EggCollection({160            egg1_name: egg1_quantity,161            egg2_name: egg2_quantity,162            egg3_name: egg3_quantity,163            egg4_name: egg4_quantity164        })165        result: EggCollection = collection.get_standard_egg_collection()166        expected = EggCollection({167            egg1_name: egg1_quantity, egg3_name: egg3_quantity, egg4_name: egg4_quantity168        })169        assert result == expected170    def test_get_quest_egg_collection_ok(self):171        egg1_name, egg1_quantity = "Wolf", 1  # not quest egg172        egg2_name, egg2_quantity = "Whale", 42173        egg3_name, egg3_quantity = "Horse", 0174        egg4_name, egg4_quantity = "Axolotl", 69175        collection = EggCollection({176            egg1_name: egg1_quantity,177            egg2_name: egg2_quantity,178            egg3_name: egg3_quantity,179            egg4_name: egg4_quantity180        })181        result: EggCollection = collection.get_quest_egg_collection()182        expected = EggCollection({183            egg2_name: egg2_quantity, egg3_name: egg3_quantity, egg4_name: egg4_quantity184        })...egg_catcher.py
Source:egg_catcher.py  
1import turtle as t2import random3height = 3604width = 3605screen = t.Screen()6screen.screensize(height, width)7n=08t.bgpic("sunshine 360.png")9bask=t.Turtle()10bask.penup()11bask.color('black')12bask.setpos(-250,-250)13bask.shape('square')14bask.shapesize(1,6,1)15bask.speed('slow')16colours=['sky blue','green','blue','pink','yellow','grey','orange','magenta']17scoreb=t.Turtle()18scoreb.hideturtle()19scoreb.penup()20scoreb.setpos(250,210)21score=022end=t.Turtle()23end.hideturtle()24#scoreb.write(score,font=('Lucida',16,'bold'))25started=False26def right_move():27    bask.forward(40)28def left_move():29    bask.forward(-40)30def create(egg):31    egg.hideturtle()32    egg.speed('fastest')33    egg.color(colours[random.randint(0,7)])34    egg.penup()35    egg.sety(300)36    egg.shape('circle')37    egg.shapesize(2,4,1)38    egg.setheading(270)39    egg.speed('normal')40    41def catch(egg,c):42    global score43    c=c+144    egg.hideturtle()45    egg.right(90)46    score=score+147    scoreb.clear()48    scoreb.write(score,font=('Lucida',16,'bold'))49    return c50def finish():51    end.setpos(0,0)52    end.write('Game over',align='center',font=('Lucida',25,'bold'))53    end.penup()54    end.setpos(0,-50)55    end.write('Your score is '+ str(score),align='center',font=('Lucida',25,'bold'))56    started=False57    global n58    n=059def create_n_move():60    end.clear()61    global started62    global n63    n=n+164    started=True65    if started==True and n==1:66        global score67        score=068        scoreb.clear()69    if started:70        egg=t.Turtle()71        create(egg)72        egg.setx(random.randint(-320, 0))73        egg.showturtle()74        75        egg1=t.Turtle()76        create(egg1)77        egg1.setx(random.randint(0, 320))78        egg1.showturtle()79        80        c=081        while(c!=2):82            egg.forward(50)83            if(egg.distance(bask)<55):84                c=catch(egg,c)85                86            screen.delay(20)87            egg1.forward(30)88            if(egg1.distance(bask)<55):89                c=catch(egg1,c)90            91            if(egg.position()[1]<-250):92                egg1.hideturtle()93                finish()94                return95            96            elif(egg1.position()[1]<-250):97                egg.hideturtle()98                finish()99                return100                   101        create_n_move()102   103#create_n_move()104end.write('Press space to start',align='center',font=('Lucida',25,'bold'))105t.onkey(right_move,'Right')106t.onkey(left_move,'Left')107t.onkey(create_n_move,'space')108t.listen()...6.8.py
Source:6.8.py  
1# 6.8 The Egg Drop Problem: There is a building of 100 floors. If an egg drops2# from the Nth floor or above, it will break. If it's dropped from any floor3# below, it will not break. You're given two eggs. Find N, while minimizing the4# number of drops for the worst case.5# Here I denote floors from 0 to 996import random7import math8import pdb9def brute_force():10	n = random.randint(0, 100)11	for i in range(100):12		if i == n:13			return i 14drops = 015break_floor = 2016def drop(floor):17	global drops18	drops += 119	return floor >= break_floor20def find_breaking_floor(k):21	""" When we use egg1, we could skip floors each time and reduce the range, like when we drop egg1 from 10th floor it is Ok,22	but broken from 20th floor, then we should search from 11th floor through 19th floor using egg2. Because egg2 is our last choice,23	we should use the safest linear search. Then how should we minimize the total number of drops for the worst case?24	The idea to keep drops(egg1) + drops(egg2) steady, meaning to keep the worst case almost the same as the best case. Then each time25	we drop egg1 one more time adding drop(egg1) by 1, we should reduce the increment by 1 thus reducing drop(egg2) by 1.26	>>> find_breaking_floor(30)27	3028	>>> find_breaking_floor(50)29	5030	>>> find_breaking_floor(70)31	7032	"""33	global break_floor34	global drops35	break_floor = k36	interval = 1437	previous = 038	egg1 = interval39	drops += 140	# drop egg141	while not drop(egg1) and egg1 <= 100:42		interval -= 143		previous = egg144		egg1 += interval45	# drop egg246	egg2 = previous + 147	while egg2 < egg1 and egg2 <= 100 and not drop(egg2):48		egg2 += 149	return -1 if egg2 > 100 else egg250if __name__ == "__main__":51	import doctest...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
