diff --git a/1/summing.py b/1/summing.py index f1cbc8c..8df7e5c 100644 --- a/1/summing.py +++ b/1/summing.py @@ -1,6 +1,2 @@ def sum_numbers(numbers=None): - if numbers is not None: - return sum(numbers) - else: - lst_100 = list(range(1, 101)) - return sum(lst_100) \ No newline at end of file + return sum(numbers) if numbers is not None else sum(list(range(1, 101))) \ No newline at end of file diff --git a/130/cars.py b/130/cars.py index 8746797..cd6162a 100644 --- a/130/cars.py +++ b/130/cars.py @@ -16,7 +16,7 @@ def most_prolific_automaker(year): for entry in data: maker = entry['automaker'] if int(entry["year"]) == year: - if maker in maker_counts.keys(): + if maker in maker_counts: maker_counts[maker] += 1 else: maker_counts[maker] = 1 diff --git a/136/bt.py b/136/bt.py index b2c2a05..c4ca25a 100644 --- a/136/bt.py +++ b/136/bt.py @@ -50,11 +50,13 @@ def check_bt(donor, recipient): if donor_type is not recipient_type: raise TypeError if donor_type is str: - if donor not in blood_type_text.keys() or recipient not in blood_type_text.keys(): + if ( + donor not in blood_type_text.keys() + or recipient not in blood_type_text.keys() + ): raise ValueError - else: - donor_bt = blood_type_text[donor].value - recipient_bt = blood_type_text[recipient].value + donor_bt = blood_type_text[donor].value + recipient_bt = blood_type_text[recipient].value elif donor_type is int: if donor < 0 or donor > 7 or recipient < 0 or recipient > 7: raise ValueError diff --git a/14/table.py b/14/table.py index f06cc73..02cc1ce 100644 --- a/14/table.py +++ b/14/table.py @@ -10,9 +10,7 @@ def generate_table(*args): combined_lists = list(zip(*args)) final_list = [] for tuples in combined_lists: - temp_string = "" - for item in tuples: - temp_string += str(item) + SEPARATOR + temp_string = "".join(str(item) + SEPARATOR for item in tuples) final_list.append(temp_string.strip(" | ")) return final_list diff --git a/15/enumerate_data.py b/15/enumerate_data.py index 0a05751..6d85ca5 100644 --- a/15/enumerate_data.py +++ b/15/enumerate_data.py @@ -10,7 +10,7 @@ def enumerate_names_countries(): 4. Dante Argentina 5. Martin USA 6. Rodolfo Mexico""" - for i in range(0, len(names)): + for i in range(len(names)): print(f'{i+1}. {names[i]: <10} {countries[i]}') enumerate_names_countries() diff --git a/161/tree.py b/161/tree.py index 48f9a09..a6457b9 100644 --- a/161/tree.py +++ b/161/tree.py @@ -8,8 +8,6 @@ def count_dirs_and_files(directory='.'): dir_list = [] file_list = [] for root, dirs, files in os.walk(directory): - for dir in dirs: - dir_list.append(dir) - for file in files: - file_list.append(file) + dir_list.extend(iter(dirs)) + file_list.extend(iter(files)) return (len(dir_list), len(file_list)) diff --git a/167/test_user.py b/167/test_user.py index ec6f4c3..a80d244 100644 --- a/167/test_user.py +++ b/167/test_user.py @@ -6,10 +6,7 @@ def test_bob_lowercase(): assert bob.get_full_name == "Bob Belderbos" assert bob.username == "bbelderb" # lowercase! assert str(bob) == "Bob Belderbos (bbelderb)" - assert repr(bob) in [ - 'User("bob", "belderbos")', - "User('bob', 'belderbos')", - ] + assert repr(bob) in {'User("bob", "belderbos")', "User('bob', 'belderbos')"} def test_julian_mixed_case(): @@ -17,10 +14,10 @@ def test_julian_mixed_case(): assert bob.get_full_name == "Julian Sequeira" assert bob.username == "jsequeir" # lowercase! assert str(bob) == "Julian Sequeira (jsequeir)" - assert repr(bob) in [ + assert repr(bob) in { 'User("julian", "Sequeira")', "User('julian', 'Sequeira')", - ] + } def test_tania_title_name(): @@ -28,10 +25,10 @@ def test_tania_title_name(): assert bob.get_full_name == "Tania Courageous" # aka PyBites Ninja assert bob.username == "tcourage" # lowercase! assert str(bob) == "Tania Courageous (tcourage)" - assert repr(bob) in [ + assert repr(bob) in { 'User("Tania", "Courageous")', "User('Tania', 'Courageous')", - ] + } def test_noah_use_dunder_in_repr(): @@ -48,7 +45,7 @@ class SpecialUser(User): assert noah.username == "nkagan" # lowercase! assert str(noah) == "Noah Kagan (nkagan)" # it should show the subclass! - assert repr(noah) in [ + assert repr(noah) in { 'SpecialUser("Noah", "Kagan")', "SpecialUser('Noah', 'Kagan')", - ] \ No newline at end of file + } \ No newline at end of file diff --git a/167/user.py b/167/user.py index 2986e39..fd835cb 100644 --- a/167/user.py +++ b/167/user.py @@ -13,7 +13,7 @@ def get_full_name(self): """Return first separated by a whitespace and using title case for both. """ - return self.first_name.title() + ' ' + self.last_name.title() + return f'{self.first_name.title()} {self.last_name.title()}' @property def username(self): diff --git a/18/harry.py b/18/harry.py index 94b10c3..9ed4871 100644 --- a/18/harry.py +++ b/18/harry.py @@ -23,10 +23,7 @@ def _filter_list(source_list, filter_out_list): return [x for x in source_list if x not in filter_out_list and x != ''] def _remove_special_chars(word_list): - words = [] - for word in word_list: - words.append(''.join(e for e in word if e.isalnum())) - return words + return [''.join(e for e in word if e.isalnum()) for word in word_list] def _process_lists(): stop_list = _file_to_list(stopwords_file) diff --git a/180/names.py b/180/names.py index 406a54e..afd0d4a 100644 --- a/180/names.py +++ b/180/names.py @@ -16,8 +16,8 @@ def group_names_by_country(data: str = data) -> defaultdict: countries = defaultdict(list) - parsed_data = [line for line in data.split('\n')[1:]] + parsed_data = list(data.split('\n')[1:]) for line in parsed_data: last, first, country = line.split(',') - countries[country] += [first + ' ' + last] + countries[country] += [f'{first} {last}'] return countries diff --git a/189/control_flow.py b/189/control_flow.py index c4b36d3..314c7a9 100644 --- a/189/control_flow.py +++ b/189/control_flow.py @@ -8,10 +8,12 @@ def filter_names(names): for name in names: if name.startswith(QUIT_CHAR): break - if len(filtered_list) < MAX_NAMES: - if not name.startswith(IGNORE_CHAR): - if not _has_digit(name): - filtered_list.append(name) + if ( + len(filtered_list) < MAX_NAMES + and not name.startswith(IGNORE_CHAR) + and not _has_digit(name) + ): + filtered_list.append(name) return filtered_list def _has_digit(name): diff --git a/21/search_cars.py b/21/search_cars.py index 4d35eb8..555baa3 100644 --- a/21/search_cars.py +++ b/21/search_cars.py @@ -39,9 +39,7 @@ def get_all_matching_models( models = [] grep = grep.lower() for lst in cars.values(): - for model in lst: - if model.lower().find(grep) != -1: - models.append(model) + models.extend(model for model in lst if model.lower().find(grep) != -1) return sorted(models) @@ -50,7 +48,4 @@ def sort_car_models(cars: CarsType = cars) -> CarsType: Loop through the cars dict returning a new dict with the same keys and the values sorted alphabetically. """ - new_dict = {} - for car, model in cars.items(): - new_dict[car] = sorted(model) - return new_dict \ No newline at end of file + return {car: sorted(model) for car, model in cars.items()} \ No newline at end of file diff --git a/215/test_license.py b/215/test_license.py index 1732e28..432b49e 100644 --- a/215/test_license.py +++ b/215/test_license.py @@ -31,9 +31,9 @@ def test_invalid_license(): assert not validate_license(lcase_key) shorter_key = pool[1][:-2] assert not validate_license(shorter_key) - longer_key = pool[2] + 'A' + longer_key = f'{pool[2]}A' assert not validate_license(longer_key) - wrong_prefix = 'AB-' + pool[3][3:] + wrong_prefix = f'AB-{pool[3][3:]}' assert not validate_license(wrong_prefix) empty_key = '' assert not validate_license(empty_key) diff --git a/225/convert_chars.py b/225/convert_chars.py index 372c48a..c37b673 100644 --- a/225/convert_chars.py +++ b/225/convert_chars.py @@ -4,10 +4,6 @@ def convert_pybites_chars(text): """Swap case all characters in the word pybites for the given text. Return the resulting string.""" - new_str = '' - for char in text: - if char.lower() in PYBITES: - new_str += char.swapcase() - else: - new_str += char - return new_str + return ''.join( + char.swapcase() if char.lower() in PYBITES else char for char in text + ) diff --git a/241/numbers_to_dec.py b/241/numbers_to_dec.py index 5a0b39e..ebc0c66 100644 --- a/241/numbers_to_dec.py +++ b/241/numbers_to_dec.py @@ -15,7 +15,7 @@ def list_to_decimal(nums: List[int]) -> int: for num in nums: if isinstance(num, bool) or not isinstance(num, int): raise TypeError - elif not num in range(0, 10): + elif num not in range(10): raise ValueError return int(''.join(map(str, nums))) \ No newline at end of file diff --git a/25/promo.py b/25/promo.py index 70ea1cb..2b3dd0d 100644 --- a/25/promo.py +++ b/25/promo.py @@ -32,8 +32,9 @@ def __init__(self): def _pick_random_bite(self): """Pick a random Bite that is not done yet, if all Bites are done, raise a NoBitesAvailable exception""" - bites_available = [x for x in self.all_bites.keys() if x not in self.bites_done] - if bites_available: + if bites_available := [ + x for x in self.all_bites.keys() if x not in self.bites_done + ]: return random.choice(bites_available) raise NoBitesAvailable diff --git a/251/series1.py b/251/series1.py index 45b8fac..5abdd5c 100644 --- a/251/series1.py +++ b/251/series1.py @@ -27,8 +27,8 @@ def alpha_index_series() -> pd.Series: so index 'a'=1, 'b'=2 ... 'y'=25, 'z'=26 Don't worry about the series name. """ - values = [x for x in range(1, 27)] - index = [x for x in string.ascii_lowercase] + values = list(range(1, 27)) + index = list(string.ascii_lowercase) return pd.Series(data=values, index=index, dtype='int64') @@ -38,6 +38,6 @@ def object_values_series() -> pd.Series: so index 101='A', 102='B' ... 125='Y', 126='Z' Don't worry about the series name. """ - values = [x for x in string.ascii_uppercase] - index = [x for x in range(101, 127)] + values = list(string.ascii_uppercase) + index = list(range(101, 127)) return pd.Series(data=values, index=index) \ No newline at end of file diff --git a/252/series.py b/252/series.py index bdadbd0..d4f0e11 100644 --- a/252/series.py +++ b/252/series.py @@ -50,7 +50,4 @@ def get_every_second_indexes(ser: pd.Series, even_index=True) -> pd.core.series. If even_index is False return every index where idx % 2 != 0 Assume default indexing i.e. 0 -> n """ - if even_index == True: - return ser.iloc[::2] - else: - return ser.iloc[1::2] + return ser.iloc[::2] if even_index == True else ser.iloc[1::2] diff --git a/252/test_series.py b/252/test_series.py index 4deb4f9..45dfa75 100644 --- a/252/test_series.py +++ b/252/test_series.py @@ -11,7 +11,7 @@ @pytest.fixture() def float_series(): """Returns a pandas Series containing floats""" - return pd.Series([float(n) / 1000 for n in range(0, 1001)]) + return pd.Series([float(n) / 1000 for n in range(1001)]) @pytest.fixture() diff --git a/262/gc_content.py b/262/gc_content.py index 20b14b9..27cdcca 100644 --- a/262/gc_content.py +++ b/262/gc_content.py @@ -13,6 +13,4 @@ def calculate_gc_content(sequence): total_seq = sum(counter.values()) g_c = sum(v for k, v in counter.items() if k.lower() in ('g', 'c')) - gc_content = round(Decimal((g_c / total_seq) * 100), 2) - - return gc_content \ No newline at end of file + return round(Decimal((g_c / total_seq) * 100), 2) \ No newline at end of file diff --git a/262/test_gc_content.py b/262/test_gc_content.py index 5104056..6a1b749 100644 --- a/262/test_gc_content.py +++ b/262/test_gc_content.py @@ -89,10 +89,10 @@ def test_calculate_gc_content(dna, gc_content): assert calculate_gc_content(dna) == gc_content - dna_with_spaces = "".join([base + " " for base in dna]) + dna_with_spaces = "".join([f"{base} " for base in dna]) assert calculate_gc_content(dna_with_spaces) == gc_content - dna_with_special_chars = "".join([base + ".!?/," for base in dna]) + dna_with_special_chars = "".join([f"{base}.!?/," for base in dna]) assert calculate_gc_content(dna_with_special_chars) == gc_content dna_line_breaks = "\n" + dna + "\n" + dna + "\n" diff --git a/27/omdb.py b/27/omdb.py index a5b244e..b96ca63 100644 --- a/27/omdb.py +++ b/27/omdb.py @@ -23,7 +23,7 @@ def get_movie_most_nominations(movies: list) -> str: max_nom_title = '' for movie in movies: re_group = re.search(r'(\d+)+ nominations', movie['Awards']) - nominations = int(re_group.group(1)) + nominations = int(re_group[1]) if nominations >= max_noms: max_noms = nominations max_nom_title = movie['Title'] diff --git a/279/armstrong.py b/279/armstrong.py index c758d69..3bb684b 100644 --- a/279/armstrong.py +++ b/279/armstrong.py @@ -1,8 +1,5 @@ def is_armstrong(n: int) -> bool: str_num = str(n) num_length = len(str_num) - powered_digits = [] - for digit in str_num: - powered_digits.append(int(digit)**num_length) - + powered_digits = [int(digit)**num_length for digit in str_num] return sum(powered_digits) == n \ No newline at end of file diff --git a/28/dates.py b/28/dates.py index 7cf027e..784e04c 100644 --- a/28/dates.py +++ b/28/dates.py @@ -32,9 +32,9 @@ def get_month_most_posts(dates): that occurs most""" months = [] for date in dates: - month = str(date.month) if len(str(date.month)) > 2 else '0' + str(date.month) + month = str(date.month) if len(str(date.month)) > 2 else f'0{str(date.month)}' year = str(date.year) - months.append(year + '-' + month) - + months.append(f'{year}-{month}') + month_count = collections.Counter(months) return month_count.most_common(1)[0][0] diff --git a/288/test_minimum_number.py b/288/test_minimum_number.py index ce69a1a..a904f49 100644 --- a/288/test_minimum_number.py +++ b/288/test_minimum_number.py @@ -5,22 +5,6 @@ from minimum_number import minimum_number -@pytest.mark.parametrize('test_input, expected', [ - ([], 0), - ([0], 0), - ([1], 1), - ([5], 5), - ([1, 1], 1), - ([7, 1], 17), - ([1, 7], 17), - ([3, 2, 1], 123), - ([1, 9, 5, 9, 1], 159), - ([0, 9, 5, 9], 59), - ([9, 3, 1, 2, 7, 9, 4, 5, 7, 9, 8, 6, 1], 123456789), - ([4, 2], 24), - ([1, 5, 2, 3, 4, 1, 4, 2, 3], 12345), - (sample(range(1, 6), 5), 12345), - (sample(range(0, 6), 6), 12345), - ]) +@pytest.mark.parametrize('test_input, expected', [([], 0), ([0], 0), ([1], 1), ([5], 5), ([1, 1], 1), ([7, 1], 17), ([1, 7], 17), ([3, 2, 1], 123), ([1, 9, 5, 9, 1], 159), ([0, 9, 5, 9], 59), ([9, 3, 1, 2, 7, 9, 4, 5, 7, 9, 8, 6, 1], 123456789), ([4, 2], 24), ([1, 5, 2, 3, 4, 1, 4, 2, 3], 12345), (sample(range(1, 6), 5), 12345), (sample(range(6), 6), 12345)]) def test_minimum_number(test_input, expected): assert minimum_number(test_input) == expected \ No newline at end of file diff --git a/29/wrong_char.py b/29/wrong_char.py index 0e19973..fb81233 100644 --- a/29/wrong_char.py +++ b/29/wrong_char.py @@ -3,12 +3,12 @@ def get_index_different_char(chars): char_list = list(string.ascii_lowercase + string.ascii_uppercase + string.digits) - + numeric_count = 0 non_numeric_count = 0 numeric_char = [] non_numeric_char = [] - + for c in chars: if str(c) in char_list: numeric_count += 1 diff --git a/293/n_digit_numbers.py b/293/n_digit_numbers.py index acc10db..c4db549 100644 --- a/293/n_digit_numbers.py +++ b/293/n_digit_numbers.py @@ -20,7 +20,7 @@ def n_digit_numbers(numbers: List[T], n: int) -> List[int]: difference = n - len(num) if neg: - num = '-' + num + num = f'-{num}' multiplier = "1" if num == 0 or difference == 0: diff --git a/295/join_lists.py b/295/join_lists.py index e3378e3..fe39856 100644 --- a/295/join_lists.py +++ b/295/join_lists.py @@ -2,10 +2,9 @@ def join_lists(lst_of_lst: List[List[str]], sep: str) -> Union[List[str], None]: - if len(lst_of_lst) == 0: return None + if not lst_of_lst: return None new_list = [] for lst in lst_of_lst: - for item in lst: - new_list.append(item) + new_list.extend(iter(lst)) new_list.append(sep) return new_list[:-1] \ No newline at end of file diff --git a/30/directors.py b/30/directors.py index 372a5b3..2e441ae 100644 --- a/30/directors.py +++ b/30/directors.py @@ -35,8 +35,8 @@ def get_movies_by_director(): score = float(row[25]) except ValueError: continue - if year and int(year) < MIN_YEAR: - continue + if year and year < MIN_YEAR: + continue directors[director].append(Movie(title, year, score)) return directors diff --git a/30/test_directors.py b/30/test_directors.py index cce0ea6..3190b93 100644 --- a/30/test_directors.py +++ b/30/test_directors.py @@ -42,7 +42,7 @@ def test_get_average_scores_top_directors(scores): ('Stanley Kubrick', 8.0), ('James Cameron', 7.9), ('Joss Whedon', 7.9)] - assert scores[0:8] == expected + assert scores[:8] == expected @pytest.mark.parametrize("director", [ diff --git a/307/test_db_intro.py b/307/test_db_intro.py index 6acfbdb..782eb52 100644 --- a/307/test_db_intro.py +++ b/307/test_db_intro.py @@ -65,7 +65,7 @@ def test_wrong_pk(): def test_insert(db): assert db.num_transactions == 4 - query = f"SELECT * FROM ninjas;" + query = "SELECT * FROM ninjas;" output = db.cursor.execute(query).fetchall() assert output == NINJAS @@ -74,8 +74,10 @@ def test_insert_twice(db): with pytest.raises(sqlite3.IntegrityError) as e: db.insert("ninjas", NINJAS) - assert str(e.value) in ("UNIQUE constraint failed: ninjas.ninja", - "column ninja is not unique") + assert str(e.value) in { + "UNIQUE constraint failed: ninjas.ninja", + "column ninja is not unique", + } @pytest.mark.parametrize( diff --git a/314/to_columns.py b/314/to_columns.py index 1d2b165..8ade3d8 100644 --- a/314/to_columns.py +++ b/314/to_columns.py @@ -3,4 +3,4 @@ def print_names_to_columns(names: List[str], cols: int = 2) -> None: for i in range(0, len(names), cols): - print(''.join("{:<12}".format('| ' + name) for name in names[i:i + cols])) + print(''.join("{:<12}".format(f'| {name}') for name in names[i:i + cols])) diff --git a/318/decode.py b/318/decode.py index 7b72187..f5310ce 100644 --- a/318/decode.py +++ b/318/decode.py @@ -10,7 +10,4 @@ def get_credit_cards(data: bytes) -> List[str]: """ decoded_data = base64.b64decode(data) decoded_data = decoded_data.decode('utf-8') - cc = [] - for line in decoded_data.splitlines()[1:]: - cc.append(line.split(',')[-1]) - return cc + return [line.split(',')[-1] for line in decoded_data.splitlines()[1:]] diff --git a/323/intersection.py b/323/intersection.py index 46b0cce..4dbfd10 100644 --- a/323/intersection.py +++ b/323/intersection.py @@ -8,9 +8,7 @@ def intersection(*args: Iterable) -> Set[Any]: for iter in filtered: iter = filter(lambda x: x != "", iter) iter_list.append(set(iter)) - final = iter_list[0].intersection(*iter_list[1:]) - - return final + return iter_list[0].intersection(*iter_list[1:]) print( diff --git a/33/transpose.py b/33/transpose.py index bee6ae3..d832722 100644 --- a/33/transpose.py +++ b/33/transpose.py @@ -3,8 +3,7 @@ def transpose(data): if isinstance(data, dict): keys = tuple(data.keys()) values = tuple(data.values()) - output.append(keys) - output.append(values) + output.extend((keys, values)) else: names = [] since_days = [] @@ -15,8 +14,13 @@ def transpose(data): since_days.append(member.since_days) karma_points.append(member.karma_points) bitecoin_earned.append(member.bitecoin_earned) - output.append(tuple(names)) - output.append(tuple(since_days)) - output.append(tuple(karma_points)) - output.append(tuple(bitecoin_earned)) + output.extend( + ( + tuple(names), + tuple(since_days), + tuple(karma_points), + tuple(bitecoin_earned), + ) + ) + return output diff --git a/336/test_app1.py b/336/test_app1.py index 4637819..e9a4be1 100644 --- a/336/test_app1.py +++ b/336/test_app1.py @@ -6,8 +6,7 @@ @pytest.fixture def client(): - client = TestClient(app) - return client + return TestClient(app) def test_root_endpoint_with_get(client): diff --git a/338/test_app.py b/338/test_app.py index 4f073e2..f71e1f4 100644 --- a/338/test_app.py +++ b/338/test_app.py @@ -6,13 +6,12 @@ @pytest.fixture def client(): - client = TestClient(app) - return client + return TestClient(app) @pytest.fixture def food(): - food = Food( + return Food( id=1, name="egg", serving_size="piece", @@ -20,7 +19,6 @@ def food(): protein_grams=6.3, fibre_grams=1, ) - return food @pytest.fixture diff --git a/339/test_app.py b/339/test_app.py index 6ad3535..0ca4551 100644 --- a/339/test_app.py +++ b/339/test_app.py @@ -23,8 +23,7 @@ @pytest.fixture def client(): - client = TestClient(app) - return client + return TestClient(app) @pytest.fixture(autouse=True) diff --git a/340/test_app.py b/340/test_app.py index 7dfba90..d9e7dab 100644 --- a/340/test_app.py +++ b/340/test_app.py @@ -9,8 +9,7 @@ @pytest.fixture def client(): - client = TestClient(app) - return client + return TestClient(app) @pytest.fixture(autouse=True) diff --git a/341/test_models.py b/341/test_models.py index baea49d..6a9ba1f 100644 --- a/341/test_models.py +++ b/341/test_models.py @@ -15,13 +15,12 @@ def _verify_password(plain_password, hashed_password): @pytest.fixture def user(): - user = User(id=1, username="user1", password=LAME_PASSWORD) - return user + return User(id=1, username="user1", password=LAME_PASSWORD) @pytest.fixture def food(): - food = Food( + return Food( id=1, name="egg", serving_size="piece", @@ -29,7 +28,6 @@ def food(): protein_grams=6.3, fibre_grams=0, ) - return food def test_create_user_object(user): diff --git a/37/test_countdowns.py b/37/test_countdowns.py index 580e3d1..1087523 100644 --- a/37/test_countdowns.py +++ b/37/test_countdowns.py @@ -17,8 +17,7 @@ expected_other_start_arg = '''13 12 11 -''' -expected_other_start_arg += expected +''' + expected def test_countdown_for(capfd): diff --git a/38/nolan.py b/38/nolan.py index 61dbb58..24852f0 100644 --- a/38/nolan.py +++ b/38/nolan.py @@ -42,5 +42,4 @@ def get_runtime(movie): a namedtuple object""" Movie = namedtuple('movie', 'runtime title') - m = Movie(int(movie['runtime'].split(' ')[0]), movie['title']) - return m + return Movie(int(movie['runtime'].split(' ')[0]), movie['title']) diff --git a/4/tags.py b/4/tags.py index e97290a..da4b5dd 100644 --- a/4/tags.py +++ b/4/tags.py @@ -20,7 +20,6 @@ def get_pybites_top_tags(n=10): root = ET.fromstring(content) cat_list = [] for item in root[0].findall('item'): - for category in item.findall('category'): - cat_list.append(category.text) + cat_list.extend(category.text for category in item.findall('category')) tag_count = Counter(cat_list) return tag_count.most_common(n) diff --git a/41/login.py b/41/login.py index 9b4a844..68be6ac 100644 --- a/41/login.py +++ b/41/login.py @@ -5,10 +5,7 @@ def login_required(func): def wrapper(user): if user in known_users: - if user in loggedin_users: - return func(user) - else: - return 'please login' + return func(user) if user in loggedin_users else 'please login' else: return 'please create an account' wrapper.__doc__ = func.__doc__ diff --git a/44/gen_license.py b/44/gen_license.py index 4a78cdb..b98e7fd 100644 --- a/44/gen_license.py +++ b/44/gen_license.py @@ -16,7 +16,7 @@ def gen_key(parts: int = 4, chars_per_part: int = 8) -> str: alphabet = string.ascii_uppercase + string.digits key = '' - for i in range(parts): - key += ''.join(secrets.choice(alphabet) for i in range(chars_per_part)) + for _ in range(parts): + key += ''.join(secrets.choice(alphabet) for _ in range(chars_per_part)) key += '-' return key[:-1] \ No newline at end of file diff --git a/47/password.py b/47/password.py index 8948d07..0759e32 100644 --- a/47/password.py +++ b/47/password.py @@ -8,10 +8,7 @@ def _char_length(pw: str, low: int, high: int): return len(pw) >= low and len(pw) <= high def _has_digit(pw: str): - for x in pw: - if x.isdigit(): - return True - return False + return any(x.isdigit() for x in pw) def _has_2_lower(pw: str): count = 0 @@ -23,23 +20,17 @@ def _has_2_lower(pw: str): return False def _has_1_upper(pw: str): - if pw.islower(): - return False - return True + return not pw.islower() def _has_punctuation(pw: str): - for x in pw: - if x in PUNCTUATION_CHARS: - return True - return False + return any(x in PUNCTUATION_CHARS for x in pw) def _not_used_previously(pw: str): return pw not in used_passwords def validate_password(password): - validations = [] + validations = [_char_length(password, low=6, high=12)] - validations.append(_char_length(password, low=6, high=12)) validations.append(_has_digit(password)) validations.append(_has_2_lower(password)) validations.append(_has_1_upper(password)) diff --git a/52/quotes.py b/52/quotes.py index e2253eb..19da14c 100644 --- a/52/quotes.py +++ b/52/quotes.py @@ -44,11 +44,8 @@ def get_quote(qid): @app.route("/api/quotes", methods=["POST"]) def create_quote(): - if request.json == {}: + if request.json == {} or len(request.json) < ARGUMENT_COUNT: abort(400) - elif len(request.json) < ARGUMENT_COUNT: - abort(400) - for quote in quotes: if ( quote["quote"] == request.json["quote"] @@ -80,10 +77,7 @@ def update_quote(qid): @app.route("/api/quotes/", methods=["DELETE"]) def delete_quote(qid): - found = False - for quote in quotes: - if quote["id"] == qid: - found = True + found = any(quote["id"] == qid for quote in quotes) if not found: abort(404) diff --git a/52/test_quotes.py b/52/test_quotes.py index 3563a27..6683d4c 100644 --- a/52/test_quotes.py +++ b/52/test_quotes.py @@ -25,7 +25,7 @@ def test_get_quotes(): def test_get_existing_quote(): - response = client.get(API_ENDPOINT + "/2") + response = client.get(f"{API_ENDPOINT}/2") assert response.status_code == 200 data = json.loads(response.get_data()) @@ -37,7 +37,7 @@ def test_get_existing_quote(): def test_get_not_existing_quote(): - response = client.get(API_ENDPOINT + "/4") + response = client.get(f"{API_ENDPOINT}/4") assert response.status_code == 404 @@ -81,10 +81,11 @@ def test_create_existing_quote(): def test_update_quote(): update_quote = dict(quote="You talking to me?!", movie="Taxi driver (1976)") response = client.put( - API_ENDPOINT + "/4", + f"{API_ENDPOINT}/4", data=json.dumps(update_quote), content_type="application/json", ) + assert response.status_code == 200 data = json.loads(response.get_data()) @@ -97,30 +98,33 @@ def test_update_quote(): def test_update_no_data(): update_quote = {} response = client.put( - API_ENDPOINT + "/4", + f"{API_ENDPOINT}/4", data=json.dumps(update_quote), content_type="application/json", ) + assert response.status_code == 400 def test_update_not_existing_quote(): update_quote = dict(quote="You talking to me?!") response = client.put( - API_ENDPOINT + "/5", + f"{API_ENDPOINT}/5", data=json.dumps(update_quote), content_type="application/json", ) + assert response.status_code == 404 def test_update_no_changes(): update_quote = dict(quote="Get to the choppa!", movie="Predator") response = client.put( - API_ENDPOINT + "/2", + f"{API_ENDPOINT}/2", data=json.dumps(update_quote), content_type="application/json", ) + assert response.status_code == 200 data = json.loads(response.get_data()) @@ -131,7 +135,7 @@ def test_update_no_changes(): def test_delete_existing_quote(): - response = client.delete(API_ENDPOINT + "/2") + response = client.delete(f"{API_ENDPOINT}/2") assert response.status_code == 204 # number quotes from 4 to 3 @@ -142,5 +146,5 @@ def test_delete_existing_quote(): def test_delete_not_existing_quote(): - response = client.delete(API_ENDPOINT + "/5") + response = client.delete(f"{API_ENDPOINT}/5") assert response.status_code == 404 diff --git a/53/text2cols.py b/53/text2cols.py index b83ea7b..c5b0e9d 100644 --- a/53/text2cols.py +++ b/53/text2cols.py @@ -16,7 +16,7 @@ def text_to_columns(text): cols = [] - for i in range(rows + 1): + for _ in range(rows + 1): cols.append(text[start:end]) start += COL_WIDTH end += COL_WIDTH diff --git a/55/steam.py b/55/steam.py index 23280ff..4c9cbf4 100644 --- a/55/steam.py +++ b/55/steam.py @@ -12,8 +12,5 @@ def get_games(): """Parses Steam's RSS feed and returns a list of Game namedtuples""" steam_feed = parse(FEED_URL) Game = namedtuple('Game', 'title link') - games = [] - for entry in steam_feed.entries: - games.append(Game(entry.title, entry.link)) - return games + return [Game(entry.title, entry.link) for entry in steam_feed.entries] \ No newline at end of file diff --git a/6/pcc_stats.py b/6/pcc_stats.py index 0bc96c0..2c73c70 100644 --- a/6/pcc_stats.py +++ b/6/pcc_stats.py @@ -48,8 +48,7 @@ def gen_files(tempfile=tempfile): if is_dir == "True": list_of_directories.append(dir_value.lower()) - for directory in list_of_directories: - yield directory + yield from list_of_directories def diehard_pybites(files=None): diff --git a/62/performance.py b/62/performance.py index 8916c0f..a832ab0 100644 --- a/62/performance.py +++ b/62/performance.py @@ -20,10 +20,7 @@ def wrapper(*args, **kwargs): @timing def contains(sequence: List[int], num: int) -> bool: - for n in sequence: - if n == num: - return True - return False + return num in sequence @timing @@ -43,10 +40,7 @@ def ordered_list_max_fast(sequence: List[int]) -> int: @timing def list_concat(sequence: List[str]) -> str: - bigstr = '' - for i in sequence: - bigstr += str(i) - return bigstr + return ''.join(str(i) for i in sequence) @timing @@ -71,12 +65,9 @@ def list_inserts_fast(n: int) -> Deque[int]: @timing def list_creation(n: int) -> List[int]: - lst = [] - for i in range(n): - lst.append(i) - return lst + return list(range(n)) @timing def list_creation_fast(n: int) -> Generator[int, None, None]: - return (x for x in range(n)) + return iter(range(n)) diff --git a/63/test_traffic.py b/63/test_traffic.py index b095129..c2b9f33 100644 --- a/63/test_traffic.py +++ b/63/test_traffic.py @@ -30,7 +30,7 @@ def test_iterator_islice(slice1, slice2): def test_equal_values_in_islice(slice1): for color in 'red green amber'.split(): - assert sum(1 for state in slice1 if state.color == color) == 32 + assert sum(state.color == color for state in slice1) == 32 def test_return_types(slice2): diff --git a/7/logtimes.py b/7/logtimes.py index 68655c6..219bddd 100644 --- a/7/logtimes.py +++ b/7/logtimes.py @@ -40,5 +40,4 @@ def time_between_shutdowns(loglines): action = " ".join(log_parts[3:]).strip("\n") if action == "Shutdown complete.": shutdowns.append(date_time) - delta = shutdowns[1] - shutdowns[0] - return delta + return shutdowns[1] - shutdowns[0] diff --git a/8/rotate.py b/8/rotate.py index 7372544..d2b3f8c 100644 --- a/8/rotate.py +++ b/8/rotate.py @@ -1,8 +1,7 @@ def rotate(string, n): if n < 0: substring = string[n:] - final_string = substring + string[:n] + return substring + string[:n] else: substring = string[:n] - final_string = string[n:] + substring - return final_string \ No newline at end of file + return string[n:] + substring \ No newline at end of file diff --git a/91/anyall.py b/91/anyall.py index fcc32e7..a8c62c7 100644 --- a/91/anyall.py +++ b/91/anyall.py @@ -6,7 +6,7 @@ def contains_only_vowels(input_str): """Receives input string and checks if all chars are VOWELS. Match is case insensitive.""" unique_chars = set(input_str.lower()) - return len([x for x in unique_chars if x not in VOWELS]) == 0 + return not [x for x in unique_chars if x not in VOWELS] def contains_any_py_chars(input_str): @@ -19,7 +19,4 @@ def contains_digits(input_str): """Receives input string and checks if it contains one or more digits.""" unique_chars = set(input_str.lower()) - for char in unique_chars: - if char.isdigit(): - return True - return False \ No newline at end of file + return any(char.isdigit() for char in unique_chars) \ No newline at end of file diff --git a/96/wc.py b/96/wc.py index 267a40a..52c245c 100644 --- a/96/wc.py +++ b/96/wc.py @@ -12,8 +12,7 @@ def wc(file_): with open(file_, 'r') as f: chars = f.read() lines = chars.splitlines() - for line in lines: - words.append(line.split()) + words.extend(line.split() for line in lines) words = list(itertools.chain(*words)) file_name = str(f.name).split('\\')[-1] return f'{len(lines)}\t{len(words)}\t{len(chars)}\t{file_name}' diff --git a/temp.pyu.py b/temp.pyu.py index 7035f2d..b5dd77b 100644 --- a/temp.pyu.py +++ b/temp.pyu.py @@ -1,8 +1,5 @@ def encode(strs): - encoded_str = '' - for item in strs: - encoded_str += item + ':>:>' - return encoded_str + return ''.join(f'{item}:>:>' for item in strs) """ @param: str: A string @return: dcodes a single string to a list of strings