Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions 1/summing.py
Original file line number Diff line number Diff line change
@@ -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)
return sum(numbers) if numbers is not None else sum(list(range(1, 101)))
2 changes: 1 addition & 1 deletion 130/cars.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 6 additions & 4 deletions 136/bt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions 14/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

2 changes: 1 addition & 1 deletion 15/enumerate_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
6 changes: 2 additions & 4 deletions 161/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
17 changes: 7 additions & 10 deletions 167/test_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,29 @@ 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():
bob = User("julian", "Sequeira")
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():
bob = User("Tania", "Courageous")
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():
Expand All @@ -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')",
]
}
2 changes: 1 addition & 1 deletion 167/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
5 changes: 1 addition & 4 deletions 18/harry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions 180/names.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 6 additions & 4 deletions 189/control_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
9 changes: 2 additions & 7 deletions 21/search_cars.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand All @@ -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
return {car: sorted(model) for car, model in cars.items()}
4 changes: 2 additions & 2 deletions 215/test_license.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 3 additions & 7 deletions 225/convert_chars.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
2 changes: 1 addition & 1 deletion 241/numbers_to_dec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
5 changes: 3 additions & 2 deletions 25/promo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 4 additions & 4 deletions 251/series1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')


Expand All @@ -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)
5 changes: 1 addition & 4 deletions 252/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
2 changes: 1 addition & 1 deletion 252/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 1 addition & 3 deletions 262/gc_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
return round(Decimal((g_c / total_seq) * 100), 2)
4 changes: 2 additions & 2 deletions 262/test_gc_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion 27/omdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
Expand Down
5 changes: 1 addition & 4 deletions 279/armstrong.py
Original file line number Diff line number Diff line change
@@ -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
6 changes: 3 additions & 3 deletions 28/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
18 changes: 1 addition & 17 deletions 288/test_minimum_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions 29/wrong_char.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion 293/n_digit_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
5 changes: 2 additions & 3 deletions 295/join_lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Loading