diff --git a/02_Amazing/python/amazing.py b/02_Amazing/python/amazing.py index 9d7ab4195..22f141c9f 100644 --- a/02_Amazing/python/amazing.py +++ b/02_Amazing/python/amazing.py @@ -47,7 +47,7 @@ def display(self) -> None: print(" ", end="") print() for col in range(self.width): - if self.walls[row][col] == 0 or self.walls[row][col] == 2: + if self.walls[row][col] in [0, 2]: print(":--", end="") else: print(": ", end="") @@ -148,7 +148,7 @@ def make_opening( maze.walls[pos.row][pos.col] = maze.walls[pos.row][pos.col] + EXIT_DOWN pos.row = pos.row + 1 maze.used[pos.row][pos.col] = count - count = count + 1 + count += 1 return pos, count diff --git a/03_Animal/python/animal.py b/03_Animal/python/animal.py index 618ef7d64..077b93d7f 100644 --- a/03_Animal/python/animal.py +++ b/03_Animal/python/animal.py @@ -104,17 +104,13 @@ def parse_input(message: str, check_list: bool, root_node: Optional[Node]) -> st list_known_animals(root_node) print("\n") - if len(inp) > 0: - token = inp[0].lower() - else: - token = "" - + token = inp[0].lower() if len(inp) > 0 else "" return token def avoid_void_input(message: str) -> str: answer = "" - while answer == "": + while not answer: answer = input(message) return answer @@ -134,8 +130,12 @@ def main() -> None: # Main loop of game print_intro() - keep_playing = parse_input("Are you thinking of an animal? ", True, root) == "y" - while keep_playing: + while ( + keep_playing := parse_input( + "Are you thinking of an animal? ", True, root + ) + == "y" + ): keep_asking = True # Start traversing the tree by the root actual_node: Node = root @@ -170,17 +170,13 @@ def main() -> None: f"for a {new_animal} the answer would be: ", False, None ) - actual_node.update_node( - new_question + "?", answer_new_question, new_animal - ) + actual_node.update_node(f"{new_question}?", answer_new_question, new_animal) else: print("Why not try another animal?") keep_asking = False - keep_playing = parse_input("Are you thinking of an animal? ", True, root) == "y" - ######################################################## # Porting Notes diff --git a/04_Awari/python/awari.py b/04_Awari/python/awari.py index 85669cee5..df4906f58 100644 --- a/04_Awari/python/awari.py +++ b/04_Awari/python/awari.py @@ -83,11 +83,10 @@ def draw_pit(line: str, board, pit_index) -> str: val = board[pit_index] - line = line + " " + line += " " if val < 10: - line = line + " " - line = line + str(val) + " " - return line + line += " " + return line + str(val) + " " def draw_board(board) -> None: @@ -148,7 +147,7 @@ def play_game(board: List[int]) -> None: print(msg) break if landing_spot == home: - landing_spot, is_still_going, home, msg = computer_move(msg + " , ", board) + landing_spot, is_still_going, home, msg = computer_move(f"{msg} , ", board) if not is_still_going: print(msg) break @@ -248,7 +247,7 @@ def computer_move(msg: str, board) -> Tuple[int, bool, int, str]: move_str = chr(42 + selected_move) if msg: - msg += ", " + move_str + msg += f", {move_str}" else: msg = move_str @@ -323,10 +322,7 @@ def execute_move(move, home: int, board) -> Tuple[int, bool, int]: # losses. losing_book[game_number] = losing_book[game_number] * 6 + move_digit - if player_has_stones(board) and computer_has_stones(board): - is_still_going = True - else: - is_still_going = False + is_still_going = bool(player_has_stones(board) and computer_has_stones(board)) return last_location, is_still_going, home diff --git a/05_Bagels/python/bagels.py b/05_Bagels/python/bagels.py index c9c0ca844..e0662d18c 100644 --- a/05_Bagels/python/bagels.py +++ b/05_Bagels/python/bagels.py @@ -49,9 +49,8 @@ def pick_number() -> List[str]: # as separate strings, not a single integer or string numbers = list(range(10)) random.shuffle(numbers) - num = numbers[0:3] - num_str = [str(i) for i in num] - return num_str + num = numbers[:3] + return [str(i) for i in num] def get_valid_guess(guesses: int) -> str: diff --git a/06_Banner/python/banner.py b/06_Banner/python/banner.py index ad85b807a..d42a7763d 100644 --- a/06_Banner/python/banner.py +++ b/06_Banner/python/banner.py @@ -74,9 +74,7 @@ def print_banner() -> None: except ValueError: print("Please enter a number greater than zero") - g1 = 0 - if input("Centered ").lower().startswith("y"): - g1 = 1 + g1 = 1 if input("Centered ").lower().startswith("y") else 0 character = input( "Character (type 'ALL' if you want character being printed) " ).upper() @@ -87,7 +85,7 @@ def print_banner() -> None: for statement_char in statement: s = letters[statement_char].copy() x_str = character - if character == "ALL": + if x_str == "ALL": x_str = statement_char if x_str == " ": print("\n" * (7 * horizontal)) diff --git a/07_Basketball/python/basketball.py b/07_Basketball/python/basketball.py index 758e5cb9e..e3a598628 100644 --- a/07_Basketball/python/basketball.py +++ b/07_Basketball/python/basketball.py @@ -122,32 +122,30 @@ def dartmouth_jump_shot(self) -> None: if random.random() > 0.782 * self.defense / 8: if random.random() > 0.843 * self.defense / 8: print("Charging foul. Dartmouth loses ball.\n") - self.opponent_ball() else: # player is fouled self.foul_shots(1) - self.opponent_ball() + self.opponent_ball() + elif random.random() > 0.5: + print( + "Shot is blocked. Ball controlled by " + + self.opponent + + ".\n" + ) + self.opponent_ball() else: - if random.random() > 0.5: - print( - "Shot is blocked. Ball controlled by " - + self.opponent - + ".\n" - ) - self.opponent_ball() - else: - print("Shot is blocked. Ball controlled by Dartmouth.") - self.dartmouth_ball() + print("Shot is blocked. Ball controlled by Dartmouth.") + self.dartmouth_ball() else: print("Shot is off target.") if self.defense / 6 * random.random() > 0.45: - print("Rebound to " + self.opponent + "\n") + print(f"Rebound to {self.opponent}" + "\n") self.opponent_ball() else: print("Dartmouth controls the rebound.") if random.random() > 0.4: if self.defense == 6 and random.random() > 0.6: - print("Pass stolen by " + self.opponent + ", easy lay up") + print(f"Pass stolen by {self.opponent}, easy lay up") self.add_points(0, 2) self.dartmouth_ball() else: @@ -186,13 +184,11 @@ def dartmouth_non_jump_shot(self) -> None: if 7 / self.defense * random.random() > 0.875: if 7 / self.defense * random.random() > 0.925: print("Charging foul. Dartmouth loses the ball.\n") - self.opponent_ball() else: - print("Shot blocked. " + self.opponent + "'s ball.\n") - self.opponent_ball() + print(f"Shot blocked. {self.opponent}" + "'s ball.\n") else: self.foul_shots(1) - self.opponent_ball() + self.opponent_ball() else: print("Shot is off the rim.") if random.random() > 2 / 3: @@ -216,35 +212,35 @@ def dartmouth_ball(self) -> None: self.shot = shot if self.time < 100 or random.random() < 0.5: - if self.shot == 1 or self.shot == 2: + if self.shot in [1, 2]: self.dartmouth_jump_shot() else: self.dartmouth_non_jump_shot() + elif self.score[0] == self.score[1]: + print("\n ***** End Of Second Half *****") + print("Score at end of regulation time:") + print( + " Dartmouth: " + + str(self.score[1]) + + " " + + self.opponent + + ": " + + str(self.score[0]) + ) + print("Begin two minute overtime period") + self.time = 93 + self.start_of_period() + else: - if self.score[0] != self.score[1]: - print("\n ***** End Of Game *****") - print( - "Final Score: Dartmouth: " - + str(self.score[1]) - + " " - + self.opponent - + ": " - + str(self.score[0]) - ) - else: - print("\n ***** End Of Second Half *****") - print("Score at end of regulation time:") - print( - " Dartmouth: " - + str(self.score[1]) - + " " - + self.opponent - + ": " - + str(self.score[0]) - ) - print("Begin two minute overtime period") - self.time = 93 - self.start_of_period() + print("\n ***** End Of Game *****") + print( + "Final Score: Dartmouth: " + + str(self.score[1]) + + " " + + self.opponent + + ": " + + str(self.score[0]) + ) def opponent_jumpshot(self) -> None: """Simulate the opponents jumpshot""" @@ -253,32 +249,35 @@ def opponent_jumpshot(self) -> None: if 8 / self.defense * random.random() > 0.75: if 8 / self.defense * random.random() > 0.9: print("Offensive foul. Dartmouth's ball.\n") - self.dartmouth_ball() else: self.foul_shots(0) - self.dartmouth_ball() + self.dartmouth_ball() else: print("Shot is off the rim.") if self.defense / 6 * random.random() > 0.5: - print(self.opponent + " controls the rebound.") - if self.defense == 6: - if random.random() > 0.75: - print("Ball stolen. Easy lay up for Dartmouth.") - self.add_points(1, 2) - self.opponent_ball() - else: - if random.random() > 0.5: - print() - self.opponent_non_jumpshot() - else: - print("Pass back to " + self.opponent + " guard.\n") - self.opponent_ball() + print(f"{self.opponent} controls the rebound.") + if ( + self.defense == 6 + and random.random() <= 0.75 + and random.random() > 0.5 + ): + print() + self.opponent_non_jumpshot() + elif ( + self.defense == 6 + and random.random() <= 0.75 + and random.random() <= 0.5 + or self.defense != 6 + and random.random() <= 0.5 + ): + print(f"Pass back to {self.opponent}" + " guard.\n") + self.opponent_ball() + elif self.defense == 6 and random.random() > 0.75: + print("Ball stolen. Easy lay up for Dartmouth.") + self.add_points(1, 2) + self.opponent_ball() else: - if random.random() > 0.5: - self.opponent_non_jumpshot() - else: - print("Pass back to " + self.opponent + " guard.\n") - self.opponent_ball() + self.opponent_non_jumpshot() else: print("Dartmouth controls the rebound.\n") self.dartmouth_ball() @@ -296,26 +295,30 @@ def opponent_non_jumpshot(self) -> None: if 7 / self.defense * random.random() > 0.413: print("Shot is missed.") if self.defense / 6 * random.random() > 0.5: - print(self.opponent + " controls the rebound.") - if self.defense == 6: - if random.random() > 0.75: - print("Ball stolen. Easy lay up for Dartmouth.") - self.add_points(1, 2) - self.opponent_ball() - else: - if random.random() > 0.5: - print() - self.opponent_non_jumpshot() - else: - print("Pass back to " + self.opponent + " guard.\n") - self.opponent_ball() + print(f"{self.opponent} controls the rebound.") + if ( + self.defense == 6 + and random.random() <= 0.75 + and random.random() > 0.5 + or self.defense != 6 + and random.random() > 0.5 + ): + print() + self.opponent_non_jumpshot() + elif ( + self.defense == 6 + and random.random() <= 0.75 + and random.random() <= 0.5 + ): + print(f"Pass back to {self.opponent}" + " guard.\n") + self.opponent_ball() + elif self.defense == 6 and random.random() > 0.75: + print("Ball stolen. Easy lay up for Dartmouth.") + self.add_points(1, 2) + self.opponent_ball() else: - if random.random() > 0.5: - print() - self.opponent_non_jumpshot() - else: - print("Pass back to " + self.opponent + " guard\n") - self.opponent_ball() + print(f"Pass back to {self.opponent}" + " guard\n") + self.opponent_ball() else: print("Dartmouth controls the rebound.\n") self.dartmouth_ball() diff --git a/08_Batnum/python/batnum.py b/08_Batnum/python/batnum.py index 3a54ee49b..bb41d8619 100644 --- a/08_Batnum/python/batnum.py +++ b/08_Batnum/python/batnum.py @@ -153,11 +153,8 @@ def computer_pick( q = pile_size - 1 if win_option == WinOptions.AvoidLast else pile_size c = min_select + max_select computer_pick = q - (c * int(q / c)) - if computer_pick < min_select: - computer_pick = min_select - if computer_pick > max_select: - computer_pick = max_select - return computer_pick + computer_pick = max(computer_pick, min_select) + return min(computer_pick, max_select) def computer_move( @@ -184,7 +181,7 @@ def computer_move( # Otherwise, we determine how many the computer selects curr_sel = computer_pick(pile_size, min_select, max_select, win_option) - pile_size = pile_size - curr_sel + pile_size -= curr_sel print(f"COMPUTER TAKES {curr_sel} AND LEAVES {pile_size}") return (False, pile_size) diff --git a/09_Battle/python/battle.py b/09_Battle/python/battle.py index 993b9f458..2418b35d5 100755 --- a/09_Battle/python/battle.py +++ b/09_Battle/python/battle.py @@ -40,8 +40,8 @@ def place_ship(sea: SeaType, size: int, code: int) -> None: point = add_vector(point, vector) points.append(point) - if not all([is_within_sea(point, sea) for point in points]) or any( - [value_at(point, sea) for point in points] + if not all(is_within_sea(point, sea) for point in points) or any( + value_at(point, sea) for point in points ): # ship out of bounds or crosses other ship, trying again continue diff --git a/10_Blackjack/python/blackjack.py b/10_Blackjack/python/blackjack.py index a2c38260c..615aec79b 100644 --- a/10_Blackjack/python/blackjack.py +++ b/10_Blackjack/python/blackjack.py @@ -58,10 +58,7 @@ def add_card(self, card: Card) -> None: def get_total(self) -> int: """returns the total points of the cards in this hand""" - total: int = 0 - for card in self.cards: - total += int(card.value) - + total: int = sum(int(card.value) for card in self.cards) # if there is an ACE, and the hand would otherwise bust, # treat the ace like it's worth 1 if total > 21 and any(card.name == "ACE" for card in self.cards): @@ -109,24 +106,21 @@ def draw_card(self) -> Card: draw card from deck, and return it if deck is empty, shuffles discard pile into it and tries again """ - if len(self.deck) == 0: - _len = len(self.discard_pile) - - if _len > 0: - # deck is empty, shuffle discard pile into deck and try again - print("deck is empty, shuffling") - for _i in range(_len): - if len(self.discard_pile) == 0: - raise ValueError("discard pile is empty") - self.deck.append(self.discard_pile.pop()) - self.shuffle() - return self.draw_card() - else: - # discard pile and deck are empty, should never happen - raise Exception("discard pile empty") - else: - card = self.deck.pop() - return card + if len(self.deck) != 0: + return self.deck.pop() + _len = len(self.discard_pile) + + if _len <= 0: + # discard pile and deck are empty, should never happen + raise Exception("discard pile empty") + # deck is empty, shuffle discard pile into deck and try again + print("deck is empty, shuffling") + for _i in range(_len): + if len(self.discard_pile) == 0: + raise ValueError("discard pile is empty") + self.deck.append(self.discard_pile.pop()) + self.shuffle() + return self.draw_card() @dataclass @@ -171,24 +165,19 @@ def hand_as_string(self, hide_dealer: bool) -> str: by *'s for every other card if player is a player, returns every card and the total """ - if not hide_dealer: - s = "" - for cards_in_hand in self.hand.cards[::-1]: - s += f"{cards_in_hand.name}\t" + if hide_dealer and self.player_type == PlayerType.Dealer: + return "".join(f"{c.name}\t" for c in self.hand.cards[1::-1]) + elif ( + hide_dealer + and self.player_type == PlayerType.Player + or not hide_dealer + ): + s = "".join( + f"{cards_in_hand.name}\t" + for cards_in_hand in self.hand.cards[::-1] + ) s += f"total points = {self.hand.get_total()}" return s - else: - if self.player_type == PlayerType.Dealer: - s = "" - for c in self.hand.cards[1::-1]: - s += f"{c.name}\t" - return s - elif self.player_type == PlayerType.Player: - s = "" - for cards_in_hand in self.hand.cards[::-1]: - s += f"{cards_in_hand.name}\t" - s += f"total points = {self.hand.get_total()}" - return s raise Exception("This is unreachable") def get_play(self) -> Play: @@ -197,10 +186,7 @@ def get_play(self) -> Play: # if it's a dealer, use an algorithm to determine the play # if it's a player, ask user for input if self.player_type == PlayerType.Dealer: - if self.hand.get_total() > 16: - return Play.Stand - else: - return Play.Hit + return Play.Stand if self.hand.get_total() > 16 else Play.Hit elif self.player_type == PlayerType.Player: valid_results: List[str] if len(self.hand.cards) > 2: @@ -232,15 +218,11 @@ class Game: @classmethod def new(cls, num_players: int) -> "Game": - players: List[Player] = [] + players: List[Player] = [Player.new(PlayerType.Dealer, 0)] - # add dealer - players.append(Player.new(PlayerType.Dealer, 0)) # create human player(s) (at least one) players.append(Player.new(PlayerType.Player, 1)) - for i in range(2, num_players): # one less than num_players players - players.append(Player.new(PlayerType.Player, i)) - + players.extend(Player.new(PlayerType.Player, i) for i in range(2, num_players)) if get_char_from_user_input("Do you want instructions", ["y", "n"]) == "y": print_instructions() print() @@ -322,9 +304,6 @@ def play_game(self) -> None: else: player.bet = player.balance player.hand.add_card(self.decks.draw_card()) - elif play == Play.Split: - pass - # add player to score cache thing player_hands_message += ( f"{player.get_name()} Hand:\t{player.hand_as_string(True)}\n" @@ -460,7 +439,7 @@ def get_number_from_user_input(prompt: str, min_value: int, max_value: int) -> i # input loop user_input = None while user_input is None or user_input < min_value or user_input > max_value: - raw_input = input(prompt + f" ({min_value}-{max_value})? ") + raw_input = input(f"{prompt} ({min_value}-{max_value})? ") try: user_input = int(raw_input) @@ -475,7 +454,7 @@ def get_char_from_user_input(prompt: str, valid_results: List[str]) -> str: """returns the first character they type""" user_input = None while user_input not in valid_results: - user_input = input(prompt + f" {valid_results}? ").lower() + user_input = input(f"{prompt} {valid_results}? ").lower() if user_input not in valid_results: print("Invalid input, please try again") assert user_input is not None diff --git a/13_Bounce/python/bounce.py b/13_Bounce/python/bounce.py index f36acc94f..e454183b0 100644 --- a/13_Bounce/python/bounce.py +++ b/13_Bounce/python/bounce.py @@ -83,7 +83,7 @@ def run_simulation(delta_t: float, v0: float, coeff_rest: float) -> None: if -16 * tm**2 + v0 * coeff_rest ** (i - 1) * tm < h: break print(line) - h = h - 0.5 + h -= 0.5 print("." * (int((total_time + 1) / delta_t) + 1)) print diff --git a/14_Bowling/python/bowling.py b/14_Bowling/python/bowling.py index c7773978d..fc923ddbc 100644 --- a/14_Bowling/python/bowling.py +++ b/14_Bowling/python/bowling.py @@ -57,10 +57,9 @@ def play_frame(self, frame: int) -> None: break # cannot roll more than once in a frame else: print(f"next roll {self.name}") - else: - if score == 10: - print("SPARE!") - extra = 1 + elif score == 10: + print("SPARE!") + extra = 1 prev_score = score # remember previous pins to distinguish ... if frame == 9 and extra > 0: @@ -112,12 +111,12 @@ def main() -> None: print("SCORES.") total_players = int(input("FIRST OF ALL...HOW MANY ARE PLAYING? ")) - player_names = [] print() print("VERY GOOD...") - for index in range(total_players): - player_names.append(Player(input(f"Enter name for player {index + 1}: "))) - + player_names = [ + Player(input(f"Enter name for player {index + 1}: ")) + for index in range(total_players) + ] for frame in range(10): for player in player_names: player.play_frame(frame) diff --git a/15_Boxing/python/boxing.py b/15_Boxing/python/boxing.py index 1943e74ec..9d8c87d58 100755 --- a/15_Boxing/python/boxing.py +++ b/15_Boxing/python/boxing.py @@ -39,12 +39,11 @@ class Player: def get_punch_choice(self) -> Literal[1, 2, 3, 4]: if self.is_computer: return random.randint(1, 4) # type: ignore - else: - punch = -1 - while punch not in [1, 2, 3, 4]: - print(f"{self.name}'S PUNCH", end="? ") - punch = int(input()) - return punch # type: ignore + punch = -1 + while punch not in [1, 2, 3, 4]: + print(f"{self.name}'S PUNCH", end="? ") + punch = int(input()) + return punch # type: ignore KNOCKOUT_THRESHOLD = 35 @@ -55,8 +54,7 @@ def get_punch_choice(self) -> Literal[1, 2, 3, 4]: def get_vulnerability() -> int: print("WHAT IS HIS VULNERABILITY", end=QUESTION_PROMPT) - vulnerability = int(input()) - return vulnerability + return int(input()) def get_opponent_stats() -> Tuple[int, int]: @@ -71,10 +69,10 @@ def get_opponent_stats() -> Tuple[int, int]: def read_punch_profiles(filepath: Path) -> Dict[Literal[1, 2, 3, 4], PunchProfile]: with open(filepath) as f: punch_profile_dict = json.load(f) - result = {} - for key, value in punch_profile_dict.items(): - result[int(key)] = PunchProfile(**value) - return result # type: ignore + return { + int(key): PunchProfile(**value) + for key, value in punch_profile_dict.items() + } def main() -> None: diff --git a/17_Bullfight/python/bullfight.py b/17_Bullfight/python/bullfight.py index 2bb789e2a..32a6ac107 100644 --- a/17_Bullfight/python/bullfight.py +++ b/17_Bullfight/python/bullfight.py @@ -29,11 +29,8 @@ def determine_player_kills( print(f"THE {player_type}{plural_form} DID A {job_qualities[job_quality]} JOB.") if job_quality >= 4: if job_quality == 5: - player_was_killed = random.choice([True, False]) - if player_was_killed: + if player_was_killed := random.choice([True, False]): print(f"ONE OF THE {player_type}{plural_form} WAS KILLED.") - elif player_was_killed: - print(f"NO {player_type}{plural_form} WERE KILLED.") else: if player_type != "TOREAD": killed_horses = random.randint(1, 2) @@ -177,12 +174,13 @@ def handle_bullkill_attempt( * job_quality_by_round[3] ) ) - if kill_method == 4: - if kill_probability > 0.8: - gore = 1 - else: - if kill_probability > 0.2: - gore = 1 + if ( + kill_method == 4 + and kill_probability > 0.8 + or kill_method != 4 + and kill_probability > 0.2 + ): + gore = 1 if gore == 0: print("YOU KILLED THE BULL!") job_quality_by_round[5] = 2 @@ -254,7 +252,7 @@ def main() -> None: # Round 3 job_quality_by_round[3] = 0 while True: - job_quality_by_round[3] = job_quality_by_round[3] + 1 + job_quality_by_round[3] += 1 print(f"PASS NUMBER {job_quality_by_round[3]}") if job_quality_by_round[3] >= 3: run_from_ring = ask_bool("HERE COMES THE BULL. TRY FOR A KILL? ") @@ -299,8 +297,13 @@ def main() -> None: print("YOU ARE STILL ALIVE.") print() print("DO YOU RUN FROM THE RING? ", end="") - run_from_ring = ask_bool("DO YOU RUN FROM THE RING? ") - if not run_from_ring: + if run_from_ring := ask_bool("DO YOU RUN FROM THE RING? "): + print("COWARD") + job_quality_by_round[4] = 0 + death = True + break + + else: print("YOU ARE BRAVE. STUPID, BUT BRAVE.") if random.randint(1, 2) == 1: job_quality_by_round[4] = 2 @@ -308,12 +311,6 @@ def main() -> None: break else: print("YOU ARE GORED AGAIN!") - else: - print("COWARD") - job_quality_by_round[4] = 0 - death = True - break - if death: break diff --git a/18_Bullseye/python/bullseye.py b/18_Bullseye/python/bullseye.py index 490a08984..df931f35c 100644 --- a/18_Bullseye/python/bullseye.py +++ b/18_Bullseye/python/bullseye.py @@ -54,7 +54,7 @@ def main() -> None: players.append(Player(player_name)) round_number = 0 - while len(winners) == 0: + while not winners: round_number += 1 print() print(f"ROUND {round_number}---------") @@ -62,10 +62,10 @@ def main() -> None: print() while True: throw = int(input(f"{player.name}'S THROW? ")) - if throw not in [1, 2, 3]: - print("INPUT 1, 2, OR 3!") - else: + if throw in {1, 2, 3}: break + else: + print("INPUT 1, 2, OR 3!") if throw == 1: probability_1 = 0.65 probability_2 = 0.55 @@ -99,10 +99,11 @@ def main() -> None: points = 0 player.score += points print(f"TOTAL SCORE = {player.score}") - for player_index, player in enumerate(players): - if player.score > 200: - winners.append(player_index) - + winners.extend( + player_index + for player_index, player in enumerate(players) + if player.score > 200 + ) print_outro(players, winners) diff --git a/21_Calendar/python/calendar.py b/21_Calendar/python/calendar.py index 922e348e6..5c59e37e3 100644 --- a/21_Calendar/python/calendar.py +++ b/21_Calendar/python/calendar.py @@ -44,7 +44,7 @@ def parse_input() -> Tuple[int, bool]: while not correct_day_input: weekday = input("INSERT THE STARTING DAY OF THE WEEK OF THE YEAR:") - for day_k in days_mapping.keys(): + for day_k in days_mapping: if weekday.lower() in day_k: day = days_mapping[day_k] correct_day_input = True diff --git a/23_Checkers/python/checkers.py b/23_Checkers/python/checkers.py index 7ae2b7e55..42ae48c8b 100644 --- a/23_Checkers/python/checkers.py +++ b/23_Checkers/python/checkers.py @@ -64,7 +64,7 @@ def is_legal_board_coordinate(x: int, y: int) -> bool: class Board: def __init__(self) -> None: - self.spaces = [[0 for y in range(8)] for x in range(8)] + self.spaces = [[0 for _ in range(8)] for _ in range(8)] for x in range(8): if (x % 2) == 0: self.spaces[x][6] = COMPUTER_PIECE @@ -114,11 +114,10 @@ def get_spaces_with_human_pieces(self) -> Iterator[Tuple[int, int]]: def get_legal_deltas_for_space(self, x: int, y: int) -> Iterator[Tuple[int, int]]: contents = self.spaces[x][y] - if contents == COMPUTER_PIECE: - for delta_x in (-1, 1): + for delta_x in (-1, 1): + if contents == COMPUTER_PIECE: yield (delta_x, -1) - else: - for delta_x in (-1, 1): + else: for delta_y in (-1, 1): yield (delta_x, delta_y) @@ -183,7 +182,7 @@ def evaluate_move( if start_y == 7: # prefer to defend back row quality -= 2 - if dest_x in (0, 7): + if dest_x in {0, 7}: # moving to edge column quality += 1 for delta_x in (-1, 1): @@ -272,9 +271,8 @@ def play_computer_move(self, move_record: MoveRecord) -> None: if best_move is None: return - else: - print(f"TO {best_move.dest_x} {best_move.dest_y}") - move_record = best_move + print(f"TO {best_move.dest_x} {best_move.dest_y}") + move_record = best_move def try_extend( self, start_x: int, start_y: int, delta_x: int, delta_y: int @@ -352,10 +350,10 @@ def play_human_move( self.spaces[dest_x][dest_y] = HUMAN_KING def check_pieces(self) -> bool: - if len(list(self.get_spaces_with_computer_pieces())) == 0: + if not list(self.get_spaces_with_computer_pieces()): print_human_won() return False - if len(list(self.get_spaces_with_computer_pieces())) == 0: + if not list(self.get_spaces_with_computer_pieces()): print_computer_won() return False return True diff --git a/25_Chief/python/chief.py b/25_Chief/python/chief.py index d8af319b5..050e281f3 100644 --- a/25_Chief/python/chief.py +++ b/25_Chief/python/chief.py @@ -39,7 +39,6 @@ def game() -> None: print("\nHuh, I Knew I was unbeatable") print("And here is how i did it") print_solution(comp_guess) - input() else: original_number = float(input("\nHUH!! what was you original number? ")) @@ -50,7 +49,6 @@ def game() -> None: ) print("Here is how i did it") print_solution(comp_guess) - input() else: print("\nSo you think you're so smart, EH?") print("Now, Watch") @@ -60,14 +58,14 @@ def game() -> None: if believe_me.lower() == "yes": print("\nOk, Lets play again sometime bye!!!!") - input() else: print("\nYOU HAVE MADE ME VERY MAD!!!!!") print("BY THE WRATH OF THE MATHEMATICS AND THE RAGE OF THE GODS") print("THERE SHALL BE LIGHTNING!!!!!!!") print_lightning_bolt() print("\nI Hope you believe me now, for your own sake") - input() + + input() if __name__ == "__main__": diff --git a/26_Chomp/python/chomp.py b/26_Chomp/python/chomp.py index 69810a5fd..d7b67950e 100755 --- a/26_Chomp/python/chomp.py +++ b/26_Chomp/python/chomp.py @@ -13,16 +13,16 @@ class Canvas: def __init__(self, width=9, height=9, fill="*") -> None: self._buffer = [] for _ in range(height): - line = [] - for _ in range(width): - line.append(fill) + line = [fill for _ in range(width)] self._buffer.append(line) self._buffer[0][0] = "P" def render(self) -> str: lines = [" 1 2 3 4 5 6 7 8 9"] - for row, line in enumerate(self._buffer, start=1): - lines.append(" " + str(row) + " " * 5 + " ".join(line)) + lines.extend( + f" {str(row)}" + " " * 5 + " ".join(line) + for row, line in enumerate(self._buffer, start=1) + ) return "\n".join(lines) def chomp(self, r, c) -> str: diff --git a/27_Civil_War/python/Civilwar.py b/27_Civil_War/python/Civilwar.py index 14b88e017..309a35172 100644 --- a/27_Civil_War/python/Civilwar.py +++ b/27_Civil_War/python/Civilwar.py @@ -46,10 +46,7 @@ class PlayerStat: excessive_losses = False def set_available_money(self): - if self.is_player: - factor = 1 + (self.r - self.q) / (self.r + 1) - else: - factor = 1 + factor = 1 + (self.r - self.q) / (self.r + 1) if self.is_player else 1 self.available_money = 100 * math.floor( (self.army_m * (100 - self.inflation) / 2000) * factor + 0.5 ) @@ -70,8 +67,7 @@ def simulate_losses(player1: PlayerStat, player2: PlayerStat) -> float: 1 + 1 / (2 * (abs(player1.strategy - player2.strategy) + 1)) ) tmp = tmp * (1.28 + (5 * player1.army_m / 6) / (player1.ammunition + 1)) - tmp = math.floor(tmp * (1 + 1 / player1.morale) + 0.5) - return tmp + return math.floor(tmp * (1 + 1 / player1.morale) + 0.5) def update_army(player: PlayerStat, enemy: PlayerStat, use_factor=False) -> None: diff --git a/28_Combat/python/combat.py b/28_Combat/python/combat.py index f8a7a5de3..0543b205a 100644 --- a/28_Combat/python/combat.py +++ b/28_Combat/python/combat.py @@ -15,7 +15,7 @@ def show_intro() -> None: print(" " * 14 + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY") print("\n\n") print("I AM AT WAR WITH YOU.") - print("WE HAVE " + str(MAX_UNITS) + " SOLDIERS APIECE.") + print(f"WE HAVE {str(MAX_UNITS)} SOLDIERS APIECE.") def get_forces() -> None: @@ -24,11 +24,11 @@ def get_forces() -> None: while True: print("DISTRIBUTE YOUR FORCES.") print(" ME YOU") - print("ARMY " + str(cpu_army) + " ? ", end="") + print(f"ARMY {str(cpu_army)} ? ", end="") usr_army = int(input()) - print("NAVY " + str(cpu_navy) + " ? ", end="") + print(f"NAVY {str(cpu_navy)} ? ", end="") usr_navy = int(input()) - print("A. F. " + str(cpu_air) + " ? ", end="") + print(f"A. F. {str(cpu_air)} ? ", end="") usr_air = int(input()) if (usr_army + usr_navy + usr_air) <= MAX_UNITS: break @@ -38,7 +38,6 @@ def attack_first() -> None: global usr_army, usr_navy, usr_air global cpu_army, cpu_navy, cpu_air - num_units = 0 unit_type = 0 while True: @@ -46,32 +45,28 @@ def attack_first() -> None: print("AND (3) FOR AIR FORCE.") print("?", end=" ") unit_type = int(input()) - if not (unit_type < 1 or unit_type > 3): + if unit_type >= 1 and unit_type <= 3: break + num_units = 0 while True: print("HOW MANY MEN") print("?", end=" ") num_units = int(input()) - if not ( - (num_units < 0) - or ((unit_type == 1) and (num_units > usr_army)) - or ((unit_type == 2) and (num_units > usr_navy)) - or ((unit_type == 3) and (num_units > usr_air)) + if ( + num_units >= 0 + and (unit_type != 1 or num_units <= usr_army) + and (unit_type != 2 or num_units <= usr_navy) + and (unit_type != 3 or num_units <= usr_air) ): break if unit_type == 1: if num_units < (usr_army / 3): - print("YOU LOST " + str(num_units) + " MEN FROM YOUR ARMY.") + print(f"YOU LOST {str(num_units)} MEN FROM YOUR ARMY.") usr_army = usr_army - num_units elif num_units < (2 * usr_army / 3): - print( - "YOU LOST " - + str(int(num_units / 3)) - + " MEN, BUT I LOST " - + str(int(2 * cpu_army / 3)) - ) + print(f"YOU LOST {int(num_units / 3)} MEN, BUT I LOST {int(2 * cpu_army / 3)}") usr_army = int(usr_army - (num_units / 3)) cpu_army = 0 else: @@ -85,7 +80,7 @@ def attack_first() -> None: print("YOUR ATTACK WAS STOPPED!") usr_navy = usr_navy - num_units elif num_units < 2 * cpu_navy / 3: - print("YOU DESTROYED " + str(int(2 * cpu_navy / 3)) + " OF MY ARMY.") + print(f"YOU DESTROYED {int(2 * cpu_navy / 3)} OF MY ARMY.") cpu_navy = int(cpu_navy / 3) else: print("YOU SUNK ONE OF MY PATROL BOATS, BUT I WIPED OUT TWO") @@ -113,7 +108,6 @@ def attack_first() -> None: def attack_second() -> None: global usr_army, usr_navy, usr_air, cpu_army, cpu_navy, cpu_air global plane_crash_win - num_units = 0 unit_type = 0 print() @@ -130,18 +124,19 @@ def attack_second() -> None: print("ARMY=1 NAVY=2 AIR FORCE=3") print("? ", end="") unit_type = int(input()) - if not ((unit_type < 1) or (unit_type > 3)): + if unit_type >= 1 and unit_type <= 3: break + num_units = 0 while True: print("HOW MANY MEN") print("? ", end="") num_units = int(input()) - if not ( - (num_units < 0) - or ((unit_type == 1) and (num_units > usr_army)) - or ((unit_type == 2) and (num_units > usr_navy)) - or ((unit_type == 3) and (num_units > usr_air)) + if ( + num_units >= 0 + and (unit_type != 1 or num_units <= usr_army) + and (unit_type != 2 or num_units <= usr_navy) + and (unit_type != 3 or num_units <= usr_air) ): break diff --git a/30_Cube/python/cube.py b/30_Cube/python/cube.py index 4928b08e9..260882dd1 100755 --- a/30_Cube/python/cube.py +++ b/30_Cube/python/cube.py @@ -31,7 +31,11 @@ def play_game() -> None: for _ in range(5): while True: mine = mine_position() - if not (mine in mines or mine == (1, 1, 1) or mine == (3, 3, 3)): + if ( + mine not in mines + and mine != (1, 1, 1) + and mine != (3, 3, 3) + ): break mines.append(mine) wager = -1 diff --git a/31_Depth_Charge/python/depth_charge.py b/31_Depth_Charge/python/depth_charge.py index a177af9ab..6134f8ce9 100644 --- a/31_Depth_Charge/python/depth_charge.py +++ b/31_Depth_Charge/python/depth_charge.py @@ -14,7 +14,7 @@ def show_welcome() -> None: # Clear screen. chr(27) is `Esc`, and the control sequence is # initiated by Ctrl+[ # `J` is "Erase in Display" and `2J` means clear the entire screen - print(chr(27) + "[2J") + print(f"{chr(27)}[2J") # Show the intro text, centered print("DEPTH CHARGE".center(45)) diff --git a/32_Diamond/python/diamond.py b/32_Diamond/python/diamond.py index 5ebcd2aab..3b261d36c 100644 --- a/32_Diamond/python/diamond.py +++ b/32_Diamond/python/diamond.py @@ -16,10 +16,7 @@ def print_diamond(begin_width, end_width, step, width, count) -> None: line_buffer = " " * ((width - n) // 2) for across in range(count): for a in range(n): - if a >= len(edge_string): - line_buffer += fill - else: - line_buffer += edge_string[a] + line_buffer += fill if a >= len(edge_string) else edge_string[a] line_buffer += " " * ( (width * (across + 1) + (width - n) // 2) - len(line_buffer) ) @@ -39,7 +36,7 @@ def main() -> None: PAGE_WIDTH = 60 - count = int(PAGE_WIDTH / width) + count = PAGE_WIDTH // width for _down in range(count): print_diamond(1, width, 2, width, count) diff --git a/35_Even_Wins/python/evenwins.py b/35_Even_Wins/python/evenwins.py index 066c7d57b..b5a198298 100644 --- a/35_Even_Wins/python/evenwins.py +++ b/35_Even_Wins/python/evenwins.py @@ -46,9 +46,7 @@ def print_intro() -> None: def marbles_str(n: int) -> str: - if n == 1: - return "1 marble" - return f"{n} marbles" + return "1 marble" if n == 1 else f"{n} marbles" def choose_first_player() -> PlayerType: @@ -66,10 +64,7 @@ def choose_first_player() -> PlayerType: def toggle_player(whose_turn: PlayerType) -> PlayerType: - if whose_turn == "human": - return "computer" - else: - return "human" + return "computer" if whose_turn == "human" else "human" def to_int(s: str) -> Tuple[bool, int]: @@ -132,11 +127,7 @@ def computer_turn(marbles: MarbleCounts) -> None: r = marbles.middle - 6 * int(marbles.middle / 6) if int(marbles.human / 2) == marbles.human / 2: - if r < 1.5 or r > 5.3: - marbles_to_take = 1 - else: - marbles_to_take = r - 1 - + marbles_to_take = 1 if r < 1.5 or r > 5.3 else r - 1 elif marbles.middle < 4.2: marbles_to_take = marbles.middle elif r > 3.4: diff --git a/37_Football/python/football.py b/37_Football/python/football.py index 748bc997a..c84c8df61 100644 --- a/37_Football/python/football.py +++ b/37_Football/python/football.py @@ -49,8 +49,7 @@ def ask_int(prompt: str) -> int: while True: answer = input(prompt) try: - int_answer = int(answer) - return int_answer + return int(answer) except Exception: pass diff --git a/38_Fur_Trader/python/furtrader.py b/38_Fur_Trader/python/furtrader.py index 190b7c3fd..0755c4100 100755 --- a/38_Fur_Trader/python/furtrader.py +++ b/38_Fur_Trader/python/furtrader.py @@ -82,7 +82,7 @@ def show_fort_comment(which_fort) -> None: print("FOR YOUR FURS. THE COST OF YOUR SUPPLIES") print("WILL BE LOWER THAN AT ALL THE OTHER FORTS.") else: - print("Internal error #1, fort " + str(which_fort) + " does not exist") + print(f"Internal error #1, fort {str(which_fort)} does not exist") sys.exit(1) # you have a bug print() @@ -109,7 +109,7 @@ def get_furs_purchase() -> List[int]: Accept numeric inputs, re-prompting on incorrect input values""" results: List[int] = [] - print("YOUR " + str(MAX_FURS) + " FURS ARE DISTRIBUTED AMONG THE FOLLOWING") + print(f"YOUR {str(MAX_FURS)} FURS ARE DISTRIBUTED AMONG THE FOLLOWING") print("KINDS OF PELTS: MINK, BEAVER, ERMINE AND FOX.") print() @@ -130,9 +130,9 @@ def main() -> None: print(" " * 15 + "(Ported to Python Oct 2012 krt@krt.com.au)") print("\n\n\n") - game_state = "starting" fox_price = None # sometimes this takes the "last" price (probably this was a bug) + game_state = "starting" while True: if game_state == "starting": @@ -150,7 +150,7 @@ def main() -> None: elif game_state == "trading": print() print("YOU HAVE $ %1.2f IN SAVINGS" % (player_funds)) - print("AND " + str(MAX_FURS) + " FURS TO BEGIN THE EXPEDITION") + print(f"AND {str(MAX_FURS)} FURS TO BEGIN THE EXPEDITION") player_furs = get_furs_purchase() if sum(player_furs) > MAX_FURS: @@ -221,10 +221,7 @@ def main() -> None: print("NO ONE WILL BUY THEM.") player_furs[FUR_FOX] = 0 else: - print( - "Internal Error #3, Out-of-bounds event_picker" - + str(event_picker) - ) + print(f"Internal Error #3, Out-of-bounds event_picker{str(event_picker)}") sys.exit(1) # you have a bug print() @@ -268,10 +265,7 @@ def main() -> None: print("YOUR MINK AND BEAVER WERE DAMAGED ON YOUR TRIP.") print("YOU RECEIVE ONLY HALF THE CURRENT PRICE FOR THESE FURS.") else: - print( - "Internal Error #4, Out-of-bounds event_picker" - + str(event_picker) - ) + print(f"Internal Error #4, Out-of-bounds event_picker{str(event_picker)}") sys.exit(1) # you have a bug print() @@ -280,7 +274,7 @@ def main() -> None: player_funds -= 105 else: - print("Internal error #2, fort " + str(which_fort) + " does not exist") + print(f"Internal error #2, fort {str(which_fort)} does not exist") sys.exit(1) # you have a bug # Calculate sales diff --git a/39_Golf/python/golf.py b/39_Golf/python/golf.py index 9132da2e6..d60bb60bb 100644 --- a/39_Golf/python/golf.py +++ b/39_Golf/python/golf.py @@ -565,13 +565,9 @@ def tee_up(self) -> None: ): self.putt = 10 print("[PUTTER: average 10 yards]") - if odds(20): - msg = "Keep your head down.\n" - else: - msg = "" - + msg = "Keep your head down.\n" if odds(20) else "" self.ask( - msg + "Choose your putt potency. (1-10)", + f"{msg}Choose your putt potency. (1-10)", 1, 10, self.set_putter_and_stroke, @@ -599,7 +595,7 @@ def stroke(self, club_amt: float, club_index: int) -> None: self.is_in_rough(self.ball) or self.is_in_hazard(self.ball, GameObjType.SAND) ) - and not (club_index == 8 or club_index == 9) + and club_index not in {8, 9} and odds(40) ): flags |= dub @@ -637,11 +633,10 @@ def stroke(self, club_amt: float, club_index: int) -> None: flags |= slice_ else: flags |= hook + elif odds(50): + flags |= hook else: - if odds(50): - flags |= hook - else: - flags |= slice_ + flags |= slice_ # beginner's luck ! # If handicap is greater than 15, there's a 10% chance of avoiding all errors @@ -664,21 +659,14 @@ def stroke(self, club_amt: float, club_index: int) -> None: distance: float rnd = random.randint(1, 101) - if self.handicap < 15: - if rnd <= 25: - distance = club_amt - (club_amt * (self.handicap / 100.0)) - elif rnd > 25 and rnd <= 75: - distance = club_amt - else: - distance = club_amt + (club_amt * 0.10) + if self.handicap < 15 and rnd <= 25 or self.handicap >= 15 and rnd <= 75: + distance = club_amt - (club_amt * (self.handicap / 100.0)) + elif self.handicap < 15 and rnd <= 75 or self.handicap >= 15: + distance = club_amt else: - if rnd <= 75: - distance = club_amt - (club_amt * (self.handicap / 100.0)) - else: - distance = club_amt - + distance = club_amt + (club_amt * 0.10) if self.player_difficulty == 3 and odds(80): # poor distance - distance = distance * 0.80 + distance *= 0.80 if (flags & luck) == luck: distance = club_amt @@ -755,7 +743,7 @@ def interpret_results(self, plot: Plot, flags: int) -> None: msg = "Your ball has gone to a watery grave." else: msg = "Your ball is lost in the water." - print(msg + " Take a penalty stroke.") + print(f"{msg} Take a penalty stroke.") self.score_card_record_stroke(self.ball) self.tee_up() return @@ -773,27 +761,18 @@ def interpret_results(self, plot: Plot, flags: int) -> None: return if (flags & in_cup) == in_cup: - if odds(50): - msg = "You holed it." - else: - msg = "It's in!" + msg = "You holed it." if odds(50) else "It's in!" print(msg) self.score_card_record_stroke(Ball(plot.x, plot.y, 0, GameObjType.BALL)) self.report_current_score() return - if ((flags & slice_) == slice_) and not ((flags & on_green) == on_green): - if (flags & out_of_bounds) == out_of_bounds: - bad = "badly" - else: - bad = "" + if (flags & slice_) == slice_ and flags & on_green != on_green: + bad = "badly" if (flags & out_of_bounds) == out_of_bounds else "" print(f"You sliced{bad}: {plot.offline} yards offline.") - if ((flags & hook) == hook) and not ((flags & on_green) == on_green): - if (flags & out_of_bounds) == out_of_bounds: - bad = "badly" - else: - bad = "" + if (flags & hook) == hook and flags & on_green != on_green: + bad = "badly" if (flags & out_of_bounds) == out_of_bounds else "" print(f"You hooked{bad}: {plot.offline} yards offline.") if self.stroke_num > 1: @@ -814,7 +793,7 @@ def interpret_results(self, plot: Plot, flags: int) -> None: if (flags & on_green) == on_green: if cup_distance < 4: - pd = str(cup_distance * 3) + " feet" + pd = f"{str(cup_distance * 3)} feet" else: pd = f"{cup_distance} yards" print(f"You're on the green. It's {pd} from the pin.") @@ -844,16 +823,10 @@ def report_current_score(self) -> None: if len(self.score_card[self.hole_num]) == (par - 3): print("Double Eagle! Unbelievable.") - total_par: int = 0 - for i in range(1, self.hole_num + 1): - total_par += CourseInfo[i].par - + total_par: int = sum(CourseInfo[i].par for i in range(1, self.hole_num + 1)) print(" ") print("-----------------------------------------------------") - if self.hole_num > 1: - hole_str = "holes" - else: - hole_str = "hole" + hole_str = "holes" if self.hole_num > 1 else "hole" print( f" Total par for {self.hole_num} {hole_str} is: {total_par}. " f"Your total is: {self.score_card_get_total()}." @@ -908,10 +881,7 @@ def is_on_green(self, ball: Ball) -> bool: def hazard_hit(self, h: Hazard, ball: Ball, hazard: GameObjType) -> bool: d = get_distance(Point(ball.X, ball.Y), Point(h.X, h.Y)) - result = False - if (d < h.Radius) and h.Type == hazard: - result = True - return result + return d < h.Radius and h.Type == hazard def is_in_hazard(self, ball: Ball, hazard: GameObjType) -> bool: result: bool = False @@ -938,9 +908,7 @@ def score_card_get_previous_stroke(self) -> Ball: return self.score_card[self.hole_num][len(self.score_card[self.hole_num]) - 1] def score_card_get_total(self) -> int: - total: int = 0 - for h in self.score_card: - total += len(h) + total: int = sum(len(h) for h in self.score_card) return total def ask( @@ -963,11 +931,8 @@ def ask( success = False n = 0 - if success: - if n >= min_ and n <= max_: - callback(n) - else: - self.ask(question, min_, max_, callback) + if success and n >= min_ and n <= max_: + callback(n) else: self.ask(question, min_, max_, callback) diff --git a/40_Gomoko/python/Gomoko.py b/40_Gomoko/python/Gomoko.py index 7036d7f22..cc4930a3e 100644 --- a/40_Gomoko/python/Gomoko.py +++ b/40_Gomoko/python/Gomoko.py @@ -13,9 +13,7 @@ def print_board(A: List[List[Any]], n: int) -> None: def check_move(_I, _J, _N) -> bool: # 910 - if _I < 1 or _I > _N or _J < 1 or _J > _N: - return False - return True + return _I >= 1 and _I <= _N and _J >= 1 and _J <= _N def print_banner() -> None: @@ -36,11 +34,10 @@ def get_board_dimensions() -> int: n = 0 while True: n = int(input("WHAT IS YOUR BOARD SIZE (MIN 7/ MAX 19)? ")) - if n < 7 or n > 19: - print("I SAID, THE MINIMUM IS 7, THE MAXIMUM IS 19.") - print() - else: + if n >= 7 and n <= 19: break + print("I SAID, THE MINIMUM IS 7, THE MAXIMUM IS 19.") + print() return n @@ -62,9 +59,7 @@ def initialize_board(n: int) -> List[List[int]]: # Initialize the board board = [] for _x in range(n): - sub_a = [] - for _y in range(n): - sub_a.append(0) + sub_a = [0 for _y in range(n)] board.append(sub_a) return board @@ -87,51 +82,49 @@ def main() -> None: break elif not check_move(x, y, n): print("ILLEGAL MOVE. TRY AGAIN...") - else: - if board[x - 1][y - 1] != 0: - print("SQUARE OCCUPIED. TRY AGAIN...") - else: - board[x - 1][y - 1] = 1 - # COMPUTER TRIES AN INTELLIGENT MOVE - skip_ef_loop = False - for E in range(-1, 2): - for F in range(-1, 2): - if E + F - E * F == 0 or skip_ef_loop: - continue - X = x + F - Y = y + F - if not check_move(X, Y, n): - continue - if board[X - 1][Y - 1] == 1: - skip_ef_loop = True - X = x - E - Y = y - F - if not check_move(X, Y, n): # 750 - while True: # 610 - X = random.randint(1, n) - Y = random.randint(1, n) - if ( - check_move(X, Y, n) - and board[X - 1][Y - 1] == 0 - ): - board[X - 1][Y - 1] = 2 - print_board(board, n) - break - else: - if board[X - 1][Y - 1] != 0: - while True: - X = random.randint(1, n) - Y = random.randint(1, n) - if ( - check_move(X, Y, n) - and board[X - 1][Y - 1] == 0 - ): - board[X - 1][Y - 1] = 2 - print_board(board, n) - break - else: + elif board[x - 1][y - 1] == 0: + board[x - 1][y - 1] = 1 + # COMPUTER TRIES AN INTELLIGENT MOVE + skip_ef_loop = False + for E in range(-1, 2): + for F in range(-1, 2): + if E + F - E * F == 0 or skip_ef_loop: + continue + X = x + F + Y = y + F + if not check_move(X, Y, n): + continue + if board[X - 1][Y - 1] == 1: + skip_ef_loop = True + X = x - E + Y = y - F + if not check_move(X, Y, n): # 750 + while True: # 610 + X = random.randint(1, n) + Y = random.randint(1, n) + if ( + check_move(X, Y, n) + and board[X - 1][Y - 1] == 0 + ): board[X - 1][Y - 1] = 2 print_board(board, n) + break + elif board[X - 1][Y - 1] == 0: + board[X - 1][Y - 1] = 2 + print_board(board, n) + else: + while True: + X = random.randint(1, n) + Y = random.randint(1, n) + if ( + check_move(X, Y, n) + and board[X - 1][Y - 1] == 0 + ): + board[X - 1][Y - 1] = 2 + print_board(board, n) + break + else: + print("SQUARE OCCUPIED. TRY AGAIN...") print() print("THANKS FOR THE GAME!!") repeat = int(input("PLAY AGAIN (1 FOR YES, 0 FOR NO)? ")) diff --git a/42_Gunner/python/gunner.py b/42_Gunner/python/gunner.py index 06d55d188..6c6d19c72 100644 --- a/42_Gunner/python/gunner.py +++ b/42_Gunner/python/gunner.py @@ -50,21 +50,19 @@ def gunner() -> None: print("\n\nTOTAL ROUNDS EXPENDED WERE: ", S1) if S1 > 18: print("BETTER GO BACK TO FORT SILL FOR REFRESHER TRAINING!") - return else: print("NICE SHOOTING !!") - return + return else: killed_enemies += 1 print( "\nTHE FORWARD OBSERVER HAS SIGHTED MORE ENEMY ACTIVITY..." ) break + elif shot_proximity_int > 100: + print("SHORT OF TARGET BY", abs(shot_proximity_int), "YARDS.") else: - if shot_proximity_int > 100: - print("SHORT OF TARGET BY", abs(shot_proximity_int), "YARDS.") - else: - print("OVER TARGET BY", abs(shot_proximity_int), "YARDS.") + print("OVER TARGET BY", abs(shot_proximity_int), "YARDS.") else: print("\nBOOM !!!! YOU HAVE JUST BEEN DESTROYED BY THE ENEMY.\n\n\n") print("BETTER GO BACK TO FORT SILL FOR REFRESHER TRAINING!") diff --git a/43_Hammurabi/python/hamurabi.py b/43_Hammurabi/python/hamurabi.py index c259ec802..46ef975d6 100644 --- a/43_Hammurabi/python/hamurabi.py +++ b/43_Hammurabi/python/hamurabi.py @@ -62,7 +62,7 @@ def main() -> None: while year < 11: # line 270. main loop. while the year is less than 11 print("\n\n\nHAMURABI: I BEG TO REPORT TO YOU") - year = year + 1 # year + year += 1 print( "IN YEAR", year, @@ -97,9 +97,7 @@ def main() -> None: elif bushels_per_acre * plague > grain_stores: # can't afford it bad_input_710(grain_stores) plague = -99 # give'm a second change to get it right - elif ( - bushels_per_acre * plague <= grain_stores - ): # normal case, can afford it + else: acres = acres + plague # increase the number of acres by Q grain_stores = ( grain_stores - bushels_per_acre * plague @@ -169,15 +167,8 @@ def main() -> None: # REM *** A BOUNTIFUL HARVEST! bushels_per_acre = C H = people * bushels_per_acre - eaten_rats = 0 - C = gen_random() - if int(C / 2) == C / 2: # even number. 50/50 chance - # REM *** RATS ARE RUNNING WILD!! - eaten_rats = int( - grain_stores / C - ) # calc losses due to rats, based on previous random number - + eaten_rats = int(grain_stores / C) if int(C / 2) == C / 2 else 0 grain_stores = grain_stores - eaten_rats + H # deduct losses from stores C = gen_random() diff --git a/44_Hangman/python/hangman.py b/44_Hangman/python/hangman.py index 3e84ce8d6..59d443dbc 100755 --- a/44_Hangman/python/hangman.py +++ b/44_Hangman/python/hangman.py @@ -16,9 +16,7 @@ class Canvas: def __init__(self, width: int = 12, height: int = 12, fill: str = " ") -> None: self._buffer = [] for _ in range(height): - line = [] - for _ in range(width): - line.append("") + line = ["" for _ in range(width)] self._buffer.append(line) self.clear() @@ -29,11 +27,7 @@ def clear(self, fill: str = " ") -> None: row[x] = fill def render(self) -> str: - lines = [] - for line in self._buffer: - # Joining by the empty string ("") smooshes all of the - # individual characters together as one line. - lines.append("".join(line)) + lines = ["".join(line) for line in self._buffer] return "\n".join(lines) def put(self, s: str, x: int, y: int) -> None: @@ -192,7 +186,7 @@ def play_game(guess_target: str) -> None: print("".join(guess_progress) + "\n") guess_letter = "" guess_word = "" - while guess_letter == "": + while not guess_letter: guess_letter = input("What is your guess? ").upper()[0] if not guess_letter.isalpha(): @@ -215,7 +209,7 @@ def play_game(guess_target: str) -> None: break else: print("\n" + "".join(guess_progress) + "\n") - while guess_word == "": + while not guess_word: guess_word = input("What is your guess for the word? ").upper() if not guess_word.isalpha(): guess_word = "" @@ -234,7 +228,7 @@ def play_game(guess_target: str) -> None: print("Sorry, that letter isn't in the word.") if wrong_guesses == 10: - print("Sorry, you lose. The word was " + guess_target) + print(f"Sorry, you lose. The word was {guess_target}") break diff --git a/45_Hello/python/hello.py b/45_Hello/python/hello.py index ccf0501c1..661ea60a1 100644 --- a/45_Hello/python/hello.py +++ b/45_Hello/python/hello.py @@ -47,8 +47,7 @@ def prompt_for_problems(user_name: str) -> str: print("THOSE DEALING WITH GREECE. WHAT KIND OF PROBLEMS DO") print("YOU HAVE? (ANSWER SEX, HEALTH, MONEY, OR JOB)") - problem_type = input().upper() - return problem_type + return input().upper() def prompt_too_much_or_too_little() -> Tuple[bool, Optional[bool]]: @@ -122,11 +121,10 @@ def ask_question_loop(user_name: str) -> None: valid, value, msg = get_yes_or_no() if valid: - if value: - print("WHAT KIND (SEX, MONEY, HEALTH, JOB)") - break - else: + if not value: return + print("WHAT KIND (SEX, MONEY, HEALTH, JOB)") + break print(f"JUST A SIMPLE 'YES' OR 'NO' PLEASE, {user_name}.") @@ -184,10 +182,7 @@ def main() -> None: ask_for_fee(user_name) - if False: - happy_goodbye(user_name) - else: - unhappy_goodbye(user_name) + unhappy_goodbye(user_name) if __name__ == "__main__": diff --git a/46_Hexapawn/python/hexapawn.py b/46_Hexapawn/python/hexapawn.py index 9a2801c35..f5cac438b 100644 --- a/46_Hexapawn/python/hexapawn.py +++ b/46_Hexapawn/python/hexapawn.py @@ -278,14 +278,7 @@ def is_legal_human_move(board: List[int], m1: int, m2: int) -> bool: # Destination is not open return False - if m2 - m1 < -4: - # too far - return False - - if m1 == 7 and m2 == 3: - # can't jump corner to corner (wrapping around the board) - return False - return True + return False if m2 - m1 < -4 else m1 != 7 or m2 != 3 def player_piece_on_back_row(board: List[int]) -> bool: @@ -297,11 +290,11 @@ def computer_piece_on_front_row(board: List[int]) -> bool: def all_human_pieces_captured(board: List[int]) -> bool: - return len(list(get_human_spaces(board))) == 0 + return not list(get_human_spaces(board)) def all_computer_pieces_captured(board: List[int]) -> bool: - return len(list(get_computer_spaces(board))) == 0 + return not list(get_computer_spaces(board)) def human_win(last_computer_move: ComputerMove) -> None: @@ -312,11 +305,7 @@ def human_win(last_computer_move: ComputerMove) -> None: def computer_win(has_moves: bool) -> None: - if not has_moves: - msg = "YOU CAN'T MOVE, SO " - else: - msg = "" - msg += "I WIN" + msg = ("YOU CAN'T MOVE, SO " if not has_moves else "") + "I WIN" print(msg) global wins wins += 1 @@ -340,14 +329,14 @@ def human_has_move(board: List[int]) -> bool: else: continue elif i < 7: - assert (i == 4) or (i == 6) + assert i in [4, 6] if board_contents(board, 2) == COMPUTER_PIECE: # can capture computer piece at 2 return True else: continue elif board_contents(board, 5) == COMPUTER_PIECE: - assert (i == 7) or (i == 9) + assert i in [7, 9] # can capture computer piece at 5 return True else: @@ -391,20 +380,16 @@ def has_computer_move(board: List[int]) -> bool: board_contents(board, i + 4) == HUMAN_PIECE ): return True - else: - if i > 3: - # beyond the first row - if board_contents(board, 8) == HUMAN_PIECE: - # can capture on 8 - return True - else: - continue - else: - if board_contents(board, 5) == HUMAN_PIECE: - # can capture on 5 - return True - else: - continue + elif ( + i > 3 + and board_contents(board, 8) == HUMAN_PIECE + or i <= 3 + and board_contents(board, 5) == HUMAN_PIECE + ): + # can capture on 8 + return True + elif i <= 3 or board_contents(board, 8) == HUMAN_PIECE: + continue return False diff --git a/48_High_IQ/python/High_IQ.py b/48_High_IQ/python/High_IQ.py index 6dcceaf5e..5b8c2204f 100644 --- a/48_High_IQ/python/High_IQ.py +++ b/48_High_IQ/python/High_IQ.py @@ -121,13 +121,8 @@ def play_game() -> None: while not move(board): print("ILLEGAL MOVE! TRY AGAIN") - # Check peg count and print the user's score - peg_count = 0 - for key in board.keys(): - if board[key] == "!": - peg_count += 1 - - print("YOU HAD " + str(peg_count) + " PEGS REMAINING") + peg_count = sum(1 for key in board.keys() if board[key] == "!") + print(f"YOU HAD {str(peg_count)} PEGS REMAINING") if peg_count == 1: print("BRAVO! YOU MADE A PERFECT SCORE!") @@ -158,11 +153,7 @@ def move(board: Dict[int, str]) -> bool: difference = abs(start - end) center = int((end + start) / 2) - if ( - (difference == 2 or difference == 18) - and board[end] == "O" - and board[center] == "!" - ): + if difference in [2, 18] and board[center] == "!": board[start] = "O" board[center] = "O" board[end] = "!" @@ -187,9 +178,10 @@ def is_game_finished(board) -> bool: next_to_peg = ((pos + space) in board) and board[pos + space] == "!" # Checks both going forward (+ location) or backwards (-location) has_movable_space = ( - not ((pos - space) in board and board[pos - space] == "!") - ) or ( - not ((pos + space * 2) in board and board[pos + space * 2] == "!") + pos - space not in board + or board[pos - space] != "!" + or pos + space * 2 not in board + or board[pos + space * 2] != "!" ) if next_to_peg and has_movable_space: return False diff --git a/49_Hockey/python/hockey.py b/49_Hockey/python/hockey.py index f18766194..c65d889e4 100644 --- a/49_Hockey/python/hockey.py +++ b/49_Hockey/python/hockey.py @@ -127,8 +127,9 @@ def print_header() -> None: def instructions() -> None: - wants_it = ask_binary("WOULD YOU LIKE THE INSTRUCTIONS? ", "ANSWER YES OR NO!!") - if wants_it: + if wants_it := ask_binary( + "WOULD YOU LIKE THE INSTRUCTIONS? ", "ANSWER YES OR NO!!" + ): print() print("THIS IS A SIMULATED HOCKEY GAME.") print("QUESTION RESPONSE") @@ -228,9 +229,7 @@ def team2_action( z1 = 3 elif pass_value == 2: print("IT'S A ' 3 ON 2 '!\n") - print( - "ONLY " + team_a.players[3] + " AND " + team_a.players[4] + " ARE BACK.\n" - ) + print(f"ONLY {team_a.players[3]} AND {team_a.players[4]}" + " ARE BACK.\n") print( team_b.players[player_index[j - 2]] + " GIVES OFF TO " @@ -290,7 +289,7 @@ def final_message(team_a: Team, team_b: Team, player_index: List[int]) -> None: print("\n") print("SHOTS ON NET\n") print(f"{team_a.name}: {team_a.shots_on_net}\n") - print(team_b.name + f": {team_b.shots_on_net}\n") + print(f"{team_b.name}: {team_b.shots_on_net}\n") def main() -> None: @@ -374,11 +373,8 @@ def handle_hit( print(f"{team_a.name}: {team_a.score}\t{team_b.name}: {team_b.score}\n") else: print(f"{team_b.name}: {team_b.score}\t{team_a.name}: {team_a.score}\n") - if controlling_team == 1: - team = team_a - else: - team = team_b - print("GOAL SCORED BY: " + team.players[goal_player] + "\n") + team = team_a if controlling_team == 1 else team_b + print(f"GOAL SCORED BY: {team.players[goal_player]}" + "\n") if goal_assistant1 != 0: if goal_assistant2 != 0: print( @@ -406,16 +402,16 @@ def handle_miss( saving_player = randint(1, 7) if controlling_team == 1: if saving_player == 1: - print("KICK SAVE AND A BEAUTY BY " + team_b.players[5] + "\n") - print("CLEARED OUT BY " + team_b.players[3] + "\n") + print(f"KICK SAVE AND A BEAUTY BY {team_b.players[5]}" + "\n") + print(f"CLEARED OUT BY {team_b.players[3]}" + "\n") remaining_time -= 1 return ("continue", remaining_time) if saving_player == 2: - print("WHAT A SPECTACULAR GLOVE SAVE BY " + team_b.players[5] + "\n") - print("AND " + team_b.players[5] + " GOLFS IT INTO THE CROWD\n") + print(f"WHAT A SPECTACULAR GLOVE SAVE BY {team_b.players[5]}" + "\n") + print(f"AND {team_b.players[5]}" + " GOLFS IT INTO THE CROWD\n") return ("break", remaining_time) if saving_player == 3: - print("SKATE SAVE ON A LOW STEAMER BY " + team_b.players[5] + "\n") + print(f"SKATE SAVE ON A LOW STEAMER BY {team_b.players[5]}" + "\n") remaining_time -= 1 return ("continue", remaining_time) if saving_player == 4: @@ -451,22 +447,20 @@ def handle_miss( print("ON THE LOOSE PUCK!\n") return ("break", remaining_time) if saving_player == 3: - print("SKATE SAVE BY " + team_a.players[5] + "\n") + print(f"SKATE SAVE BY {team_a.players[5]}" + "\n") print(team_a.players[5] + " WHACKS THE LOOSE PUCK INTO THE STANDS\n") return ("break", remaining_time) if saving_player == 4: - print( - "STICK SAVE BY " + team_a.players[5] + " AND HE CLEARS IT OUT HIMSELF\n" - ) + print(f"STICK SAVE BY {team_a.players[5]}" + " AND HE CLEARS IT OUT HIMSELF\n") remaining_time -= 1 return ("continue", remaining_time) if saving_player == 5: - print("KICKED OUT BY " + team_a.players[5] + "\n") + print(f"KICKED OUT BY {team_a.players[5]}" + "\n") print("AND IT REBOUNDS ALL THE WAY TO CENTER ICE\n") remaining_time -= 1 return ("continue", remaining_time) if saving_player == 6: - print("GLOVE SAVE " + team_a.players[5] + " AND HE HANGS ON\n") + print(f"GLOVE SAVE {team_a.players[5]}" + " AND HE HANGS ON\n") return ("break", remaining_time) return ("continue", remaining_time) @@ -488,8 +482,9 @@ def simulate_game_round( j = 0 for j in range(1, (pass_value + 2) + 1): player_index[j] = randint(1, 5) - if player_index[j - 1] == player_index[j - 2] or ( - pass_value + 2 >= 3 + if ( + player_index[j - 1] == player_index[j - 2] + or pass_value >= 1 and ( player_index[j - 1] == player_index[j - 3] or player_index[j - 2] == player_index[j - 3] @@ -511,7 +506,7 @@ def simulate_game_round( ) while True: shot_type = int(input("SHOT? ")) - if not (shot_type < 1 or shot_type > 4): + if shot_type >= 1 and shot_type <= 4: break if controlling_team == 1: print(team_a.players[goal_player], end="") @@ -521,21 +516,21 @@ def simulate_game_round( print(" LET'S A BIG SLAP SHOT GO!!\n") z = 4 z += z1 - if shot_type == 2: + elif shot_type == 2: print(" RIPS A WRIST SHOT OFF\n") z = 2 z += z1 - if shot_type == 3: + elif shot_type == 3: print(" GETS A BACKHAND OFF\n") z = 3 z += z1 - if shot_type == 4: + elif shot_type == 4: print(" SNAPS OFF A SNAP SHOT\n") z = 2 z += z1 while True: goal_area = int(input("AREA? ")) - if not (goal_area < 1 or goal_area > 4): + if goal_area >= 1 and goal_area <= 4: break if controlling_team == 1: team_a.shots_on_net += 1 diff --git a/50_Horserace/python/horserace.py b/50_Horserace/python/horserace.py index b00a63165..075c4573a 100644 --- a/50_Horserace/python/horserace.py +++ b/50_Horserace/python/horserace.py @@ -73,12 +73,8 @@ def setup_players() -> List[str]: # ensure we get an integer value from the user number_of_players = basic_input("HOW MANY WANT TO BET", int) - # for each user query their name and return the list of names - player_names = [] basic_print("WHEN ? APPEARS,TYPE NAME") - for _ in range(number_of_players): - player_names.append(basic_input("")) - return player_names + return [basic_input("") for _ in range(number_of_players)] def setup_horses() -> List[float]: diff --git a/53_King/python/king.py b/53_King/python/king.py index 4bca76fac..0bf85016c 100644 --- a/53_King/python/king.py +++ b/53_King/python/king.py @@ -179,7 +179,7 @@ def handle_foreign_workers( sm_sell_to_industry + (random() * 10) - (random() * 20) ) if self.foreign_workers <= 0: - foreign_workers_influx = foreign_workers_influx + 20 + foreign_workers_influx += 20 print(f"{foreign_workers_influx} WORKERS CAME TO THE COUNTRY AND") surplus_distributed = distributed_rallods / COST_OF_LIVING - self.countrymen @@ -196,7 +196,7 @@ def handle_foreign_workers( print("CAME TO ", end="") print("THE ISLAND") self.countrymen += population_change - self.foreign_workers += int(foreign_workers_influx) + self.foreign_workers += foreign_workers_influx def handle_too_many_deaths(self) -> None: print(f"\n\n\n{self.died_contrymen} COUNTRYMEN DIED IN ONE YEAR!!!!!") @@ -430,8 +430,9 @@ def main() -> None: if state.countrymen < 343: state.handle_third_died() elif ( - state.rallods / 100 - ) > 5 and state.died_contrymen - state.pollution_deaths >= 2: + state.rallods > 500 + and state.died_contrymen - state.pollution_deaths >= 2 + ): state.handle_money_mismanagement() if state.foreign_workers > state.countrymen: state.handle_too_many_foreigners() diff --git a/55_Life/python/life.py b/55_Life/python/life.py index 5a71dfa88..8707d5015 100644 --- a/55_Life/python/life.py +++ b/55_Life/python/life.py @@ -44,7 +44,7 @@ def get_pattern() -> Dict[int, str]: # staying in. if line[0] == ".": - line = " " + line[1:] + line = f" {line[1:]}" pattern[c] = line c += 1 @@ -64,7 +64,7 @@ def main() -> None: max_x = MAX_HEIGHT - 1 max_y = MAX_WIDTH - 1 - a = [[0 for y in range(MAX_WIDTH)] for x in range(MAX_HEIGHT)] + a = [[0 for _ in range(MAX_WIDTH)] for _ in range(MAX_HEIGHT)] p = 0 g = 0 invalid = False @@ -81,11 +81,7 @@ def main() -> None: print() print() while True: - if invalid: - inv_str = "INVALID!" - else: - inv_str = "" - + inv_str = "INVALID!" if invalid else "" print(f"GENERATION: {g}\tPOPULATION: {p} {inv_str}") next_min_x = MAX_HEIGHT - 1 @@ -151,7 +147,7 @@ def main() -> None: count = 0 for i in range(x - 1, x + 2): for j in range(y - 1, y + 2): - if a[i][j] == 1 or a[i][j] == 2: + if a[i][j] in [1, 2]: count += 1 if a[x][y] == 0: if count == 3: diff --git a/56_Life_for_Two/python/life_for_two.py b/56_Life_for_Two/python/life_for_two.py index da4e16195..c9910f994 100644 --- a/56_Life_for_Two/python/life_for_two.py +++ b/56_Life_for_Two/python/life_for_two.py @@ -5,11 +5,12 @@ Ported by Sajid Sarker (2022). ''' + # Global Variable Initialisation # Initialise the board -gn = [[0 for i in range(6)] for j in range(6)] -gx = [0 for x in range(3)] -gy = [0 for x in range(3)] +gn = [[0 for _ in range(6)] for _ in range(6)] +gx = [0 for _ in range(3)] +gy = [0 for _ in range(3)] gk = [0, 3, 102, 103, 120, 130, 121, 112, 111, 12, 21, 30, 1020, 1030, 1011, 1021, 1003, 1002, 1012] @@ -27,9 +28,9 @@ def tab(number) -> str: def display_header() -> None: - print("{}LIFE2".format(tab(33))) - print("{}CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n".format(tab(15))) - print("{}U.B. LIFE GAME".format(tab(10))) + print(f"{tab(33)}LIFE2") + print(f"{tab(15)}CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n") + print(f"{tab(10)}U.B. LIFE GAME") # Board Functions @@ -37,7 +38,7 @@ def setup_board() -> None: # Players add symbols to initially setup the board for b in range(1, 3): p1 = 3 if b != 2 else 30 - print("\nPLAYER {} - 3 LIVE PIECES.".format(b)) + print(f"\nPLAYER {b} - 3 LIVE PIECES.") for _ in range(1, 4): query_player(b) gn[gx[b]][gy[b]] = p1 @@ -46,7 +47,7 @@ def setup_board() -> None: def modify_board() -> None: # Players take turns to add symbols and modify the board for b in range(1, 3): - print("PLAYER {} ".format(b)) + print(f"PLAYER {b} ") query_player(b) if b == 99: break @@ -72,36 +73,32 @@ def display_board() -> None: for j in range(7): print("") for k in range(7): - if j == 0 or j == 6: + if j in [0, 6]: if k != 6: - print(" " + str(k) + " ", end="") + print(f" {str(k)} ", end="") else: print(" 0 ", end="") - elif k == 0 or k == 6: - if j != 6: - print(" " + str(j) + " ", end="") - else: - print(" 0\n") + elif k in [0, 6]: + print(f" {str(j)} ", end="") + elif gn[j][k] < 3: + gn[j][k] = 0 + print(" ", end="") else: - if gn[j][k] < 3: + for o1 in range(1, 19): + if gn[j][k] == gk[o1]: + break + if o1 <= 18: + if o1 > 9: + gn[j][k] = 1000 + m3 += 1 + print(" # ", end="") + else: + gn[j][k] = 100 + m2 += 1 + print(" * ", end="") + else: gn[j][k] = 0 print(" ", end="") - else: - for o1 in range(1, 19): - if gn[j][k] == gk[o1]: - break - if o1 <= 18: - if o1 > 9: - gn[j][k] = 1000 - m3 += 1 - print(" # ", end="") - else: - gn[j][k] = 100 - m2 += 1 - print(" * ", end="") - else: - gn[j][k] = 0 - print(" ", end="") # Player Functions @@ -113,8 +110,8 @@ def query_player(b) -> None: b_ = input("???") x_ = [int(num) for num in a_.split() if num.isdigit()] y_ = [int(num) for num in b_.split() if num.isdigit()] - x_ = [0] if len(x_) == 0 else x_ - y_ = [0] if len(y_) == 0 else y_ + x_ = [0] if not x_ else x_ + y_ = [0] if not y_ else y_ gx[b] = y_[0] gy[b] = x_[0] if gx[b] in range(1, 6)\ diff --git a/59_Lunar_LEM_Rocket/python/lunar.py b/59_Lunar_LEM_Rocket/python/lunar.py index 46a066746..228093e91 100644 --- a/59_Lunar_LEM_Rocket/python/lunar.py +++ b/59_Lunar_LEM_Rocket/python/lunar.py @@ -64,7 +64,7 @@ def add_rjust(line: str, s: Any, pos: int) -> str: def add_ljust(line: str, s: str, pos: int) -> str: """Add a new field to a line left justified starting at pos""" - s = str(s) + s = s if len(line) > pos: line = line[:pos] if len(line) < pos: @@ -324,10 +324,7 @@ def run_simulation() -> None: return if capsule.velocity > 0 and new_state.velocity < 0: - # moving away from the moon - - landed = handle_flyaway(sim_clock, capsule) - if landed: + if landed := handle_flyaway(sim_clock, capsule): process_final_tick(delta_t, sim_clock, capsule) return diff --git a/60_Mastermind/python/mastermind.py b/60_Mastermind/python/mastermind.py index cc77153c4..8fcecc624 100644 --- a/60_Mastermind/python/mastermind.py +++ b/60_Mastermind/python/mastermind.py @@ -77,11 +77,7 @@ def human_turn() -> None: print_score() return # from human turn, triumphant else: - print( - "You have {} blacks and {} whites".format( - guess_results[1], guess_results[2] - ) - ) + print(f"You have {guess_results[1]} blacks and {guess_results[2]} whites") guesses.append(guess_results) num_moves += 1 @@ -193,16 +189,14 @@ def possibility_to_color_code(possibility: int) -> str: def compare_two_positions(guess: str, answer: str) -> List[Union[str, int]]: """Returns blacks (correct color and position) and whites (correct color only) for candidate position (guess) versus reference position (answer).""" - increment = 0 blacks = 0 whites = 0 initial_guess = guess + increment = 0 for pos in range(0, NUM_POSITIONS): if guess[pos] != answer[pos]: for pos2 in range(0, NUM_POSITIONS): - if not ( - guess[pos] != answer[pos2] or guess[pos2] == answer[pos2] - ): # correct color but not correct place + if guess[pos] == answer[pos2] and guess[pos2] != answer[pos2]: # correct color but not correct place whites = whites + 1 answer = answer[:pos2] + chr(increment) + answer[pos2 + 1:] guess = guess[:pos] + chr(increment + 1) + guess[pos + 1:] diff --git a/61_Math_Dice/python/mathdice.py b/61_Math_Dice/python/mathdice.py index 99220e713..4081e0cca 100644 --- a/61_Math_Dice/python/mathdice.py +++ b/61_Math_Dice/python/mathdice.py @@ -22,23 +22,23 @@ def print_2() -> None: print(" ----- ") - if n in [4, 5, 6]: + if n in {4, 5, 6}: print_2() - elif n in [2, 3]: + elif n in {2, 3}: print("| * |") else: print_0() - if n in [1, 3, 5]: + if n in {1, 3, 5}: print("| * |") - elif n in [2, 4]: + elif n in {2, 4}: print_0() else: print_2() - if n in [4, 5, 6]: + if n in {4, 5, 6}: print_2() - elif n in [2, 3]: + elif n in {2, 3}: print("| * |") else: print_0() diff --git a/62_Mugwump/python/mugwump.py b/62_Mugwump/python/mugwump.py index d1e3f7c3d..cc719c172 100644 --- a/62_Mugwump/python/mugwump.py +++ b/62_Mugwump/python/mugwump.py @@ -35,8 +35,7 @@ def reveal_mugwumps(mugwumps: List[List[int]]) -> None: def calculate_distance(guess: Tuple[int, int], mugwump: List[int]) -> float: - d = sqrt(((mugwump[0] - guess[0]) ** 2) + ((mugwump[1] - guess[1]) ** 2)) - return d + return sqrt(((mugwump[0] - guess[0]) ** 2) + ((mugwump[1] - guess[1]) ** 2)) def play_again() -> None: diff --git a/63_Name/python/name.py b/63_Name/python/name.py index 3d7eeb1c0..94b8170d6 100644 --- a/63_Name/python/name.py +++ b/63_Name/python/name.py @@ -9,9 +9,7 @@ def is_yes_ish(answer: str) -> bool: cleaned = answer.strip().upper() - if cleaned in ["Y", "YES"]: - return True - return False + return cleaned in {"Y", "YES"} def main() -> None: diff --git a/64_Nicomachus/python/nicomachus.py b/64_Nicomachus/python/nicomachus.py index 84f477032..e5d1c8253 100644 --- a/64_Nicomachus/python/nicomachus.py +++ b/64_Nicomachus/python/nicomachus.py @@ -43,9 +43,7 @@ def play_game() -> None: print(f"YOUR NUMBER WAS {d}, RIGHT?") - response = get_yes_or_no() - - if response: + if response := get_yes_or_no(): print("HOW ABOUT THAT!!") else: print("I FEEL YOUR ARITHMETIC IS IN ERROR.") diff --git a/65_Nim/python/Traditional_NIM.py b/65_Nim/python/Traditional_NIM.py index bd1470c50..ead90b2d0 100644 --- a/65_Nim/python/Traditional_NIM.py +++ b/65_Nim/python/Traditional_NIM.py @@ -30,11 +30,7 @@ def remove_pegs(self, command) -> None: print("\nInvalid value of either Peg or Pile\n") def get_ai_move(self) -> Tuple[int, int]: - possible_pile = [] - for k, v in self.piles.items(): - if v != 0: - possible_pile.append(k) - + possible_pile = [k for k, v in self.piles.items() if v != 0] pile = random.choice(possible_pile) num = random.randint(1, self.piles[pile]) @@ -46,7 +42,7 @@ def _command_integrity(self, num, pile) -> bool: def print_pegs(self) -> None: for pile, peg in self.piles.items(): - print("Pile {} : {}".format(pile, "O " * peg)) + print(f'Pile {pile} : {"O " * peg}') def help(self) -> None: print("-" * 10) @@ -89,8 +85,7 @@ def main() -> None: # Players Move command = input("\nYOUR MOVE - Number of PILE, Number of Object? ") game.remove_pegs(command) - end = game.check_for_win() - if end: + if end := game.check_for_win(): print("\nPlayer Wins the Game, Congratulations!!") input("\nPress any key to exit") break @@ -98,13 +93,10 @@ def main() -> None: # Computers Move ai_command = game.get_ai_move() print( - "\nA.I MOVE - A.I Removed {} pegs from Pile {}".format( - ai_command[1], ai_command[0] - ) + f"\nA.I MOVE - A.I Removed {ai_command[1]} pegs from Pile {ai_command[0]}" ) - game.remove_pegs(str(ai_command[0]) + "," + str(ai_command[1])) - end = game.check_for_win() - if end: + game.remove_pegs(f"{str(ai_command[0])},{str(ai_command[1])}") + if end := game.check_for_win(): print("\nComputer Wins the Game, Better Luck Next Time\n") input("Press any key to exit") break diff --git a/68_Orbit/python/orbit.py b/68_Orbit/python/orbit.py index f0ce1637e..cfca3c93b 100644 --- a/68_Orbit/python/orbit.py +++ b/68_Orbit/python/orbit.py @@ -107,9 +107,7 @@ def play_game() -> bool: rom_angle = random.randint(0, 359) rom_distance = random.randint(100, 300) rom_angular_velocity = random.randint(10, 30) - hour = 0 - while hour < 7: - hour += 1 + for hour in range(1, 8): print() print() print(f"THIS IS HOUR {hour}, AT WHAT ANGLE DO YOU WISH TO SEND") diff --git a/69_Pizza/python/pizza.py b/69_Pizza/python/pizza.py index e4e36beac..aa4a01e93 100644 --- a/69_Pizza/python/pizza.py +++ b/69_Pizza/python/pizza.py @@ -155,9 +155,7 @@ def main() -> None: player_name = print_instructions() - more_directions = yes_no_prompt("DO YOU NEED MORE DIRECTIONS?") - - if more_directions: + if more_directions := yes_no_prompt("DO YOU NEED MORE DIRECTIONS?"): print_more_directions(player_name) understand = yes_no_prompt("UNDERSTAND?") @@ -171,8 +169,8 @@ def main() -> None: print("GOOD LUCK!!") print() + num_turns = 5 while True: - num_turns = 5 play_game(num_turns, player_name) print() diff --git a/70_Poetry/python/poetry.py b/70_Poetry/python/poetry.py index 302126301..f261db375 100644 --- a/70_Poetry/python/poetry.py +++ b/70_Poetry/python/poetry.py @@ -49,7 +49,7 @@ def process_phrase_2(state: State) -> None: ] words, u_modifier = line_2_options[state.i] state.line += words - if not (u_modifier is None): + if u_modifier is not None: state.u = u_modifier diff --git a/72_Queen/python/queen.py b/72_Queen/python/queen.py index 94f377a1c..285174c49 100755 --- a/72_Queen/python/queen.py +++ b/72_Queen/python/queen.py @@ -82,10 +82,7 @@ def loc_to_num(location: Tuple[int, int], fix_align: bool = False) -> str: """Convert a position given by row, column into a space number.""" row, col = location out_str: str = f"{row + 8 - col}{row + 1}" - if not fix_align or len(out_str) == 3: - return out_str - else: - return out_str + " " + return out_str if not fix_align or len(out_str) == 3 else f"{out_str} " GAME_BOARD: Final[str] = ( @@ -173,15 +170,14 @@ def get_move(current_loc: Optional[Tuple[int, int]]) -> Tuple[int, int]: "YOU HAVE BEGUN ILLEGALLY.\n\n" "WHERE WOULD YOU LIKE TO START? " ) - else: - if ( + elif ( (new_row == row and new_col < col) # move left or (new_col == col and new_row > row) # move down or (new_row - row == col - new_col) # move diag left and down ) and (not FIX_BOARD_BUG or (new_col >= 0 and new_row < 8)): - return new_row, new_col - else: - prompt = "Y O U C H E A T . . . TRY AGAIN? " + return new_row, new_col + else: + prompt = "Y O U C H E A T . . . TRY AGAIN? " except ValueError: prompt = "!NUMBER EXPECTED - RETRY INPUT LINE\n? " @@ -256,12 +252,12 @@ def ask(prompt: str) -> bool: inpt: str while True: # Normalize input to uppercase, no whitespace, then get first character - inpt = input(prompt + "? ").upper().strip()[0] + inpt = input(f"{prompt}? ").upper().strip()[0] print() - if inpt == "Y": - return True - elif inpt == "N": + if inpt == "N": return False + elif inpt == "Y": + return True print("PLEASE ANSWER 'YES' OR 'NO'.") return False diff --git a/73_Reverse/python/reverse.py b/73_Reverse/python/reverse.py index f75ece2f8..e34378406 100755 --- a/73_Reverse/python/reverse.py +++ b/73_Reverse/python/reverse.py @@ -52,7 +52,7 @@ def game_loop() -> None: turns += 1 # Reverse as many items as requested. - newnums = numbers[0:howmany] + newnums = numbers[:howmany] newnums.reverse() newnums.extend(numbers[howmany:]) numbers = newnums diff --git a/74_Rock_Scissors_Paper/python/rockscissors.py b/74_Rock_Scissors_Paper/python/rockscissors.py index 898f709cc..3d150bd4f 100644 --- a/74_Rock_Scissors_Paper/python/rockscissors.py +++ b/74_Rock_Scissors_Paper/python/rockscissors.py @@ -44,22 +44,27 @@ def play_game() -> None: print("...Scissors") elif guess_computer == 3: print("...Rock") - if guess_computer == guess_human: + if ( + guess_computer != guess_human + and guess_computer > guess_human + and (guess_human != 1 or guess_computer != 3) + or guess_computer != guess_human + and guess_computer <= guess_human + and guess_computer == 1 + and guess_human == 3 + ): + print("Wow! I win!!!") + won_computer = won_computer + 1 + elif ( + guess_computer != guess_human + and guess_computer > guess_human + or guess_computer != guess_human + and guess_computer == 1 + ): + print("You win!!!") + won_human = won_human + 1 + elif guess_computer == guess_human: print("Tie Game. No winner") - elif guess_computer > guess_human: - if guess_human != 1 or guess_computer != 3: - print("Wow! I win!!!") - won_computer = won_computer + 1 - else: - print("You win!!!") - won_human = won_human + 1 - elif guess_computer == 1: - if guess_human != 3: - print("You win!!!") - won_human = won_human + 1 - else: - print("Wow! I win!!!") - won_computer = won_computer + 1 print("\nHere is the final game score:") print("I have won", won_computer, "game(s).") print("You have won", won_human, "game(s).") diff --git a/75_Roulette/python/roulette.py b/75_Roulette/python/roulette.py index 7a21d36dc..eec68bed7 100644 --- a/75_Roulette/python/roulette.py +++ b/75_Roulette/python/roulette.py @@ -75,7 +75,7 @@ def query_bets() -> Tuple[List[int], List[int]]: for i in range(bet_count): while bet_ids[i] == -1: try: - in_string = input("NUMBER " + str(i + 1) + "? ").split(",") + in_string = input(f"NUMBER {str(i + 1)}? ").split(",") id_, val = int(in_string[0]), int(in_string[1]) # check other bet_IDs @@ -126,9 +126,9 @@ def get_modifier(id_: int, num: int) -> int: total_winnings += winnings if winnings >= 0: - print("YOU WIN " + str(winnings) + " DOLLARS ON BET " + str(i + 1)) + print(f"YOU WIN {str(winnings)} DOLLARS ON BET {str(i + 1)}") else: - print("YOU LOSE " + str(winnings * -1) + " DOLLARS ON BET " + str(i + 1)) + print(f"YOU LOSE {str(winnings * -1)} DOLLARS ON BET {str(i + 1)}") return winnings @@ -142,7 +142,7 @@ def print_check(amount: int) -> None: print(" " * 40 + "CHECK NO. " + str(random.randint(0, 100))) print(" " * 40 + str(date.today())) print() - print("PAY TO THE ORDER OF -----" + name + "----- $" + str(amount)) + print(f"PAY TO THE ORDER OF -----{name}----- ${amount}") print() print(" " * 40 + "THE MEMORY BANK OF NEW YORK") print(" " * 40 + "THE COMPUTER") @@ -176,9 +176,9 @@ def main() -> None: elif val == 37: print("00") elif val in RED_NUMBERS: - print(str(val) + " RED") + print(f"{val} RED") else: - print(str(val) + " BLACK") + print(f"{val} BLACK") print() total_winnings = bet_results(bet_ids, bet_values, val) @@ -209,7 +209,7 @@ def main() -> None: def string_to_bool(string: str) -> bool: """Converts a string to a bool""" - return string.lower() in ("yes", "y", "true", "t", "yes") + return string.lower() in {"y", "true", "t", "yes"} if __name__ == "__main__": diff --git a/76_Russian_Roulette/python/russianroulette.py b/76_Russian_Roulette/python/russianroulette.py index f402fb03c..71e0ee129 100644 --- a/76_Russian_Roulette/python/russianroulette.py +++ b/76_Russian_Roulette/python/russianroulette.py @@ -29,8 +29,7 @@ def initial_message() -> None: def parse_input() -> int: while True: try: - i = int(input("? ")) - return i + return int(input("? ")) except ValueError: print("Number expected...") @@ -61,13 +60,12 @@ def main() -> None: print("BANG!!!!! You're Dead!") print("Condolences will be sent to your relatives.\n\n\n") print("...Next victim...") + elif n > NUMBER_OF_ROUNDS: + print("You win!!!!!") + print("Let someone else blow his brain out.\n") else: - if n > NUMBER_OF_ROUNDS: - print("You win!!!!!") - print("Let someone else blow his brain out.\n") - else: - print(" Chicken!!!!!\n\n\n") - print("...Next victim....") + print(" Chicken!!!!!\n\n\n") + print("...Next victim....") if __name__ == "__main__": diff --git a/77_Salvo/python/salvo.py b/77_Salvo/python/salvo.py index 368b15da9..417bebc14 100644 --- a/77_Salvo/python/salvo.py +++ b/77_Salvo/python/salvo.py @@ -169,7 +169,7 @@ def generate_ship_coordinates(ship: int) -> List[CoordinateType]: # clockwise. a vector of valid directions where the # ship does not go off the board is determined ship_len = SHIPS[ship][1] - 1 - dirs = [False for x in range(8)] + dirs = [False for _ in range(8)] dirs[0] = (start_x - ship_len) >= 1 dirs[2] = (start_y + ship_len) <= BOARD_WIDTH dirs[1] = dirs[0] and dirs[2] @@ -261,11 +261,7 @@ def generate_board() -> Tuple[BoardType, List[List[CoordinateType]]]: coords = [] while not placed: coords = generate_ship_coordinates(ship) - clear = True - for coord in coords: - if board[coord[0] - 1][coord[1] - 1] is not None: - clear = False - break + clear = all(board[coord[0] - 1][coord[1] - 1] is None for coord in coords) if clear: placed = True place_ship(board, coords, ship) @@ -291,18 +287,17 @@ def execute_shot( def calculate_shots(board: BoardType) -> int: """Examine each board and determine how many shots remaining""" - ships_found = [0 for x in range(len(SHIPS))] + ships_found = [0 for _ in range(len(SHIPS))] for x in range(BOARD_HEIGHT): for y in range(BOARD_WIDTH): square = board[x - 1][y - 1] if square is not None and square >= 0 and square < len(SHIPS): ships_found[square] = 1 - shots = 0 - for ship in range(len(ships_found)): - if ships_found[ship] == 1: - shots += SHIPS[ship][2] - - return shots + return sum( + SHIPS[ship][2] + for ship in range(len(ships_found)) + if ships_found[ship] == 1 + ) def initialize_game() -> None: @@ -413,10 +408,7 @@ def execute_turn(turn: bool, current_turn: int) -> int: # computer, we randomly pick a shot. for the # player we request shots while not valid_shot: - if turn == COMPUTER: - x, y = random_x_y() - else: - x, y = input_coord() + x, y = random_x_y() if turn == COMPUTER else input_coord() square = board[x - 1][y - 1] if square is not None and square > 10: if turn == PLAYER: diff --git a/79_Slalom/python/slalom.py b/79_Slalom/python/slalom.py index a6833331b..e3387e6f6 100644 --- a/79_Slalom/python/slalom.py +++ b/79_Slalom/python/slalom.py @@ -97,7 +97,7 @@ def run(gates, lvl, max_speeds) -> None: case 7: speed -= int(random() * (10 - 5) + 5) - print(f" {int(speed)} M.P.H.") + print(f" {speed} M.P.H.") if speed > max_speeds[i]: if random() < ((speed - max_speeds[i]) * 0.1) + 0.2: print( @@ -184,7 +184,7 @@ def main() -> None: run(gates, lvl, max_speeds) while True: answer = ask("Do you want to play again?") - if answer == "YES" or answer == "NO": + if answer in ["YES", "NO"]: break else: print('Please type "YES" or "NO"') diff --git a/80_Slots/python/slots.py b/80_Slots/python/slots.py index 22c2b3a3f..6464458b6 100644 --- a/80_Slots/python/slots.py +++ b/80_Slots/python/slots.py @@ -59,7 +59,7 @@ def input_betting() -> int: elif b < 1: print("Minium bet is $1") beeping() - return int(b) + return b def beeping() -> None: @@ -113,7 +113,7 @@ def adjust_profits(wheel: List[str], m: int, profits: int) -> int: else: # three different fruits print("\nYou Lost.") - profits = profits - m + profits -= m return profits diff --git a/81_Splat/python/splat.py b/81_Splat/python/splat.py index 30ec74b5d..f521f3a23 100644 --- a/81_Splat/python/splat.py +++ b/81_Splat/python/splat.py @@ -311,9 +311,9 @@ def main() -> None: z = yes_no_input("DO YOU WANT TO PLAY AGAIN") if not z: z = yes_no_input("PLEASE") - if not z: - print("SSSSSSSSSS.") - break + if not z: + print("SSSSSSSSSS.") + break if __name__ == "__main__": diff --git a/82_Stars/python/stars.py b/82_Stars/python/stars.py index d2024d6b4..5a5f9fed0 100644 --- a/82_Stars/python/stars.py +++ b/82_Stars/python/stars.py @@ -40,10 +40,7 @@ def print_instructions() -> None: def print_stars(secret_number, guess) -> None: diff = abs(guess - secret_number) - stars = "" - for i in range(8): - if diff < 2**i: - stars += "*" + stars = "".join("*" for i in range(8) if diff < 2**i) print(stars) @@ -51,8 +48,7 @@ def get_guess(prompt: str) -> int: while True: guess_str = input(prompt) if guess_str.isdigit(): - guess = int(guess_str) - return guess + return int(guess_str) def main() -> None: diff --git a/83_Stock_Market/python/Stock_Market.py b/83_Stock_Market/python/Stock_Market.py index e32572ca6..38d8442a1 100644 --- a/83_Stock_Market/python/Stock_Market.py +++ b/83_Stock_Market/python/Stock_Market.py @@ -35,10 +35,9 @@ def total_assets(self) -> float: def _generate_day_change(self) -> None: self.changes = [] - for _ in range(len(self.data)): - self.changes.append( - round(random.uniform(-5, 5), 2) - ) # Random % Change b/w -5 and 5 + self.changes.extend( + round(random.uniform(-5, 5), 2) for _ in range(len(self.data)) + ) def update_prices(self) -> None: self._generate_day_change() @@ -65,9 +64,9 @@ def print_first_day(self) -> None: print("\nSTOCK\t\t\t\t\tINITIALS\tPRICE/SHARE($)") for stock, data in self.data.items(): if stock != "LBJ": - print("{}\t\t\t{}\t\t{}".format(data["Name"], stock, data["Price"])) + print(f'{data["Name"]}\t\t\t{stock}\t\t{data["Price"]}') else: - print("{}\t\t{}\t\t{}".format(data["Name"], stock, data["Price"])) + print(f'{data["Name"]}\t\t{stock}\t\t{data["Price"]}') self.print_exchange_average() self.print_assets() diff --git a/84_Super_Star_Trek/python/superstartrek.py b/84_Super_Star_Trek/python/superstartrek.py index 805c9d93a..892988c76 100644 --- a/84_Super_Star_Trek/python/superstartrek.py +++ b/84_Super_Star_Trek/python/superstartrek.py @@ -26,8 +26,7 @@ def get_user_float(prompt: str) -> float: while True: answer = input(prompt) try: - answer_float = float(answer) - return answer_float + return float(answer) except ValueError: pass @@ -202,7 +201,7 @@ def quadrant_name(cls, row: int, col: int, region_only: bool = False) -> str: quadrant = region1[row] if col < 4 else region2[row] if not region_only: - quadrant += " " + modifier[col % 4] + quadrant += f" {modifier[col % 4]}" return quadrant @@ -622,7 +621,7 @@ def short_range_scan(self) -> None: for x in range(8): line = "" for y in range(8): - line = line + " " + self.world.quadrant.data[x][y].value + line = f"{line} {self.world.quadrant.data[x][y].value}" if x == 0: line += f" STARDATE {round(int(self.world.stardate * 10) * 0.1, 1)}" @@ -882,8 +881,7 @@ def damage_control(self) -> None: return for i in range(8): - if ship.damage_stats[i] < 0: - ship.damage_stats[i] = 0 + ship.damage_stats[i] = max(ship.damage_stats[i], 0) self.world.stardate += damage_sum + 0.1 def computer(self) -> None: @@ -909,7 +907,7 @@ def computer(self) -> None: print() - if com in [0, 5]: + if com in {0, 5}: if com == 5: print(" THE GALAXY") else: @@ -923,7 +921,7 @@ def computer(self) -> None: print(sep) for i in range(8): - line = " " + str(i + 1) + " " + line = f" {str(i + 1)} " if com == 5: g2s = Quadrant.quadrant_name(i, 0, True) @@ -1121,12 +1119,11 @@ def print_direction(source: Point, to: Point) -> None: else: base = 1 delta1, delta2 = delta2, delta1 + elif delta1 > 0: + base = 3 else: - if delta1 > 0: - base = 3 - else: - base = 5 - delta1, delta2 = delta2, delta1 + base = 5 + delta1, delta2 = delta2, delta1 delta1, delta2 = abs(delta1), abs(delta2) diff --git a/84_Super_Star_Trek/python/superstartrekins.py b/84_Super_Star_Trek/python/superstartrekins.py index 59a8a61bd..6060ad9d4 100644 --- a/84_Super_Star_Trek/python/superstartrekins.py +++ b/84_Super_Star_Trek/python/superstartrekins.py @@ -17,13 +17,13 @@ def print_header() -> None: for _ in range(12): print() t10 = " " * 10 - print(t10 + "*************************************") - print(t10 + "* *") - print(t10 + "* *") - print(t10 + "* * * SUPER STAR TREK * * *") - print(t10 + "* *") - print(t10 + "* *") - print(t10 + "*************************************") + print(f"{t10}*************************************") + print(f"{t10}* *") + print(f"{t10}* *") + print(f"{t10}* * * SUPER STAR TREK * * *") + print(f"{t10}* *") + print(f"{t10}* *") + print(f"{t10}*************************************") for _ in range(8): print() diff --git a/88_3-D_Tic-Tac-Toe/python/qubit.py b/88_3-D_Tic-Tac-Toe/python/qubit.py index 3a8f1e096..e0dd531e8 100644 --- a/88_3-D_Tic-Tac-Toe/python/qubit.py +++ b/88_3-D_Tic-Tac-Toe/python/qubit.py @@ -137,10 +137,7 @@ def move(self, m, player) -> bool: if self.board[m] > 1: return False - if player == Player.MACHINE: - self.board[m] = 40 - else: - self.board[m] = 8 + self.board[m] = 40 if player == Player.MACHINE else 8 return True def get_3d_position(self, m) -> Tuple[int, int, int]: @@ -152,9 +149,7 @@ def get_3d_position(self, m) -> Tuple[int, int, int]: def evaluate_lines(self) -> None: self.lineValues = [0] * 76 for j in range(76): - value = 0 - for k in range(4): - value += self.board[self.lines[j][k]] + value = sum(self.board[self.lines[j][k]] for k in range(4)) self.lineValues[j] = value def strategy_mark_line(self, i) -> None: @@ -174,9 +169,7 @@ def mark_and_move(self, vlow, vhigh, vmove) -> Optional[Tuple[Move, int]]: or the machine and choose best place to play """ for i in range(76): - value = 0 - for j in range(4): - value += self.board[self.lines[i][j]] + value = sum(self.board[self.lines[i][j]] for j in range(4)) self.lineValues[i] = value if vlow <= value < vhigh: if value > vlow: @@ -186,7 +179,7 @@ def mark_and_move(self, vlow, vhigh, vmove) -> Optional[Tuple[Move, int]]: for i in range(76): value = self.lineValues[i] - if value == 4 or value == vmove: + if value in [4, vmove]: return self.move_diagonals(i, 1) return None @@ -232,11 +225,10 @@ def machine_move(self) -> Union[None, Tuple[Move, int], Tuple[Move, int, int]]: if self.board[y] == 0: return (Move.MOVES, y) - for i in range(64): - if self.board[i] == 0: - return (Move.LIKES, i) - - return (Move.DRAW, -1) + return next( + ((Move.LIKES, i) for i in range(64) if self.board[i] == 0), + (Move.DRAW, -1), + ) def human_win(self, i) -> Tuple[Move, int, int]: return (Move.HUMAN_WIN, -1, i) @@ -260,18 +252,12 @@ def move_triple(self, i) -> Tuple[Move, int]: for j in range(4): m = self.lines[i][j] if self.board[m] == 1: - if self.lineValues[i] < 40: - return (Move.YOU_FOX, m) - else: - return (Move.GET_OUT, m) + return (Move.YOU_FOX, m) if self.lineValues[i] < 40 else (Move.GET_OUT, m) return (Move.CONCEDES, -1) # choose move in corners or center boxes of square 4x4 def move_diagonals(self, i, s) -> Optional[Tuple[Move, int]]: - if 0 < (i % 4) < 3: - jrange = [1, 2] - else: - jrange = [0, 3] + jrange = [1, 2] if 0 < (i % 4) < 3 else [0, 3] for j in jrange: m = self.lines[i][j] if self.board[m] == s: @@ -379,11 +365,7 @@ def play(self) -> None: self.show_win(board, m[2]) # type: ignore break elif m[0] == Move.MACHINE_WIN: - print( - "Machine moves to {}, and wins as follows".format( - self.move_code(board, m[1]) - ) - ) + print(f"Machine moves to {self.move_code(board, m[1])}, and wins as follows") self.show_win(board, m[2]) # type: ignore break elif m[0] == Move.DRAW: diff --git a/89_Tic-Tac-Toe/python/TicTacToe_Hard.py b/89_Tic-Tac-Toe/python/TicTacToe_Hard.py index b5708d802..8b3e50ab9 100644 --- a/89_Tic-Tac-Toe/python/TicTacToe_Hard.py +++ b/89_Tic-Tac-Toe/python/TicTacToe_Hard.py @@ -8,9 +8,7 @@ def __init__(self, pick, sz=3) -> None: self.board = self.clear_board() def clear_board(self) -> List[List[str]]: - board = [["blur" for i in range(self.dim_sz)] for j in range(self.dim_sz)] - # made a 3x3 by-default board - return board + return [["blur" for _ in range(self.dim_sz)] for _ in range(self.dim_sz)] def move_record(self, r, c) -> Union[str, bool]: if r > self.dim_sz or c > self.dim_sz: @@ -86,17 +84,12 @@ def check_win(self) -> int: # 1 you won, 0 computer won, -1 tie if flag11 or flag12: return 1 - if flag21 or flag22: - return 0 - - return -1 + return 0 if flag21 or flag22 else -1 def next_move(self) -> Union[Tuple[int, int], Tuple[List[int], List[int]]]: available_moves = [] # will carry all available moves player_win_spot = [] # if player (user Wins) - comp_pick = "O" - if self.pick == "O": - comp_pick = "X" + comp_pick = "X" if self.pick == "O" else "O" for i in range(0, self.dim_sz): for j in range(0, self.dim_sz): @@ -113,13 +106,13 @@ def next_move(self) -> Union[Tuple[int, int], Tuple[List[int], List[int]]]: player_win_spot.append(t) self.board[i][j] = "blur" - if len(player_win_spot) != 0: + if player_win_spot: self.board[player_win_spot[0][0]][player_win_spot[0][1]] = comp_pick return player_win_spot[0][0], player_win_spot[0][1] if len(available_moves) == 1: self.board[available_moves[0][0]][available_moves[0][1]] = comp_pick return [available_moves[0][0]], [available_moves[0][1]] - if len(available_moves) == 0: + if not available_moves: return -1, -1 c1, c2 = self.dim_sz // 2, self.dim_sz // 2 @@ -172,22 +165,19 @@ def display(game: TicTacToe) -> None: for i in range(0, game.dim_sz): for j in range(0, game.dim_sz - 1): if game.board[i][j] == "blur": - line1 = line1 + " |" + line1 = f"{line1} |" else: - line1 = line1 + " " + game.board[i][j] + " |" + line1 = f"{line1} {game.board[i][j]} |" if game.board[i][game.dim_sz - 1] == "blur": line1 = line1 + " \n" else: - line1 = line1 + " " + game.board[i][game.dim_sz - 1] + " \n" + line1 = f"{line1} {game.board[i][game.dim_sz - 1]}" + " \n" print(line1, "\n\n") def main() -> None: pick = input("Pick 'X' or 'O' ").strip().upper() - if pick == "O": - game = TicTacToe("O") - else: - game = TicTacToe("X") + game = TicTacToe("O") if pick == "O" else TicTacToe("X") display(game=game) while True: temp: Union[bool, str] = False diff --git a/89_Tic-Tac-Toe/python/tictactoe2.py b/89_Tic-Tac-Toe/python/tictactoe2.py index 210ff2e7c..e6fce18a2 100755 --- a/89_Tic-Tac-Toe/python/tictactoe2.py +++ b/89_Tic-Tac-Toe/python/tictactoe2.py @@ -52,14 +52,15 @@ def line_170(board, g, h, j, k): def line_150(board, g, h, j, k): if board[k] != g: # line 150 - if ( - board[k] == h # line 160 - or board[k + 6] != g # line 161 - or board[k + 3] != g - ): # line 162 - return -1 # Goto 170 - else: - return k + 3 # Line 163 + return ( + -1 + if ( + board[k] == h # line 160 + or board[k + 6] != g # line 161 + or board[k + 3] != g + ) + else k + 3 + ) elif board[k + 6] != g: # line 152 if board[k + 6] != 0 or board[k + 3] != g: # line 165 return -1 # Goto 170 @@ -70,16 +71,7 @@ def line_150(board, g, h, j, k): def line_120(board, g, h, j, k): - if board[j] != g: - if board[j] == h or board[j + 2] != g or board[j + 1] != g: - if board[k] != g: - if board[k + 6] != g and (board[k + 6] != 0 or board[k + 3] != g): - # 450 IF G=1 THEN 465 - pass - elif board[j + 2] is not g: # Line 122 - pass - elif board[j + 1] is not OccupiedBy.EMPTY: - pass + pass def line_118(board, g, h): @@ -123,12 +115,13 @@ def think(board, g, h, moves): def render_board(board, space_mapping): vertical_divider = "!" horizontal_divider = "---+---+---" - lines = [] - lines.append(vertical_divider.join(space_mapping[space] for space in board[0:3])) - lines.append(horizontal_divider) - lines.append(vertical_divider.join(space_mapping[space] for space in board[3:6])) - lines.append(horizontal_divider) - lines.append(vertical_divider.join(space_mapping[space] for space in board[6:9])) + lines = [ + vertical_divider.join(space_mapping[space] for space in board[:3]), + horizontal_divider, + vertical_divider.join((space_mapping[space] for space in board[3:6])), + horizontal_divider, + vertical_divider.join((space_mapping[space] for space in board[6:9])), + ] return "\n".join(lines) diff --git a/90_Tower/python/tower.py b/90_Tower/python/tower.py index 7d30c9ebb..d0059e86f 100644 --- a/90_Tower/python/tower.py +++ b/90_Tower/python/tower.py @@ -10,7 +10,7 @@ def size(self) -> int: return self.__size def print(self) -> None: - print("[ %s ]" % self.size()) + print(f"[ {self.size()} ]") class Tower: @@ -21,10 +21,7 @@ def empty(self) -> bool: return len(self.__disks) == 0 def top(self) -> Optional[Disk]: - if self.empty(): - return None - else: - return self.__disks[-1] + return None if self.empty() else self.__disks[-1] def add(self, disk: Disk) -> None: if not self.empty(): @@ -42,7 +39,7 @@ def pop(self) -> Disk: return self.__disks.pop() def print(self) -> None: - r = "Needle: [%s]" % (", ".join([str(x.size()) for x in self.__disks])) + r = f'Needle: [{", ".join([str(x.size()) for x in self.__disks])}]' print(r) @@ -87,7 +84,7 @@ def pick_disk(self) -> Optional[Tower]: print("ILLEGAL ENTRY... YOU MAY ONLY TYPE 3,5,7,9,11,13, OR 15.\n") valids = [t for t in self.__towers if t.top() and t.top().size() == which] - assert len(valids) in (0, 1) + assert len(valids) in {0, 1} if not valids: print("THAT DISK IS BELOW ANOTHER ONE. MAKE ANOTHER CHOICE.\n") return None diff --git a/92_Trap/python/trap.py b/92_Trap/python/trap.py index 64220234d..a85be68e6 100644 --- a/92_Trap/python/trap.py +++ b/92_Trap/python/trap.py @@ -24,11 +24,10 @@ def play_game() -> None: int(item) for item in input("\nGuess # " + str(turn) + " ? ").split(",") ] - if len(user_input) == 2: - if sum(1 < x < number_max for x in user_input) == 2: - user_guess = user_input - else: - raise ValueError + if len(user_input) != 2: + raise ValueError + if sum(1 < x < number_max for x in user_input) == 2: + user_guess = user_input else: raise ValueError except (ValueError, IndexError): diff --git a/93_23_Matches/python/23matches.py b/93_23_Matches/python/23matches.py index 5375a176e..293cfa1f3 100755 --- a/93_23_Matches/python/23matches.py +++ b/93_23_Matches/python/23matches.py @@ -35,7 +35,7 @@ def play_game() -> None: except ValueError: print("Please enter a number.") prompt_human = "How many do you wish to remove " - matches = matches - choice_human + matches -= choice_human if matches == 0: print("You poor boob! You took the last match! I gotcha!!") print("Ha ! Ha ! I beat you !!\n") @@ -48,7 +48,7 @@ def play_game() -> None: choice_computer = 1 elif 1 < matches < 4: choice_computer = matches - 1 - matches = matches - choice_computer + matches -= choice_computer if matches == 0: print("You won, floppy ears !") print("Think you're pretty smart !") diff --git a/95_Weekday/python/weekday.py b/95_Weekday/python/weekday.py index 15cdae442..0a6b0aabd 100644 --- a/95_Weekday/python/weekday.py +++ b/95_Weekday/python/weekday.py @@ -29,11 +29,13 @@ def get_date_from_user(prompt: str) -> Tuple[int, int, int]: def get_date_from_system() -> Tuple[int, int, int]: - dt = datetime.datetime.today() + dt = datetime.datetime.now() return dt.month, dt.day, dt.year def get_day_of_week(weekday_index, day) -> str: + if weekday_index == 6 and day == 13: + return "FRIDAY THE THIRTEENTH---BEWARE!" day_names = { 1: "SUNDAY", 2: "MONDAY", @@ -44,8 +46,6 @@ def get_day_of_week(weekday_index, day) -> str: 7: "SATURDAY", } - if weekday_index == 6 and day == 13: - return "FRIDAY THE THIRTEENTH---BEWARE!" return day_names[weekday_index] @@ -58,11 +58,7 @@ def previous_day(b) -> int: def is_leap_year(year: int) -> bool: if (year % 4) != 0: return False - if (year % 100) != 0: - return True - if (year % 400) != 0: - return False - return True + return True if (year % 100) != 0 else year % 400 == 0 def adjust_day_for_leap_year(b, year): @@ -86,9 +82,9 @@ def calc_day_value(year, month, day): def deduct_time(frac, days, years_remain, months_remain, days_remain): # CALCULATE TIME IN YEARS, MONTHS, AND DAYS days_available = int(frac * days) - years_used = int(days_available / 365) + years_used = days_available // 365 days_available -= years_used * 365 - months_used = int(days_available / 30) + months_used = days_available // 30 days_used = days_available - (months_used * 30) years_remain = years_remain - years_used months_remain = months_remain - months_used @@ -238,7 +234,7 @@ def main() -> None: rem_years, rem_months, rem_days, used_years, used_months, used_days = deduct_time( 0.23, life_days, rem_years, rem_months, rem_days ) - time_report("YOU HAVE " + label, used_years, used_months, used_days) + time_report(f"YOU HAVE {label}", used_years, used_months, used_days) time_report("YOU HAVE RELAXED", rem_years, rem_months, rem_days) print() diff --git a/96_Word/python/word.py b/96_Word/python/word.py index 8b7f0d51f..5ff7604a0 100755 --- a/96_Word/python/word.py +++ b/96_Word/python/word.py @@ -35,7 +35,7 @@ def play_game() -> None: print("You are starting a new game...") while True: guess_word = "" - while guess_word == "": + while not guess_word: guess_word = input("\nGuess a five letter word. ").upper() if guess_word == "?": break