39
Axel
Last seen 1 month ago
Member for 2 years, 8 months, 23 days
Difficulty Normal
Optimization ideas:
-->
# first step: removed List (used once), space as argument of split(), and useless condition
counter=0
for word in text.split():
if word.isdigit():
counter += int(word)
return counter
-->
# next step - comprehension with if
More
you need no walrus and if-comprehension:
return sum(
max(0 ,(min(d2, end_watching or d2) - max(d1, start_watching or d1)).total_seconds())
for d1, d2 in zip_longest(*[iter(els)] * 2, fillvalue=end_watching)
and zip_longest too:
for d1, d2 in zip(els[::2], els[1::2] + [
More
Cool solution! Btw there is some tricks for improve code and make it clear:
* list(map(list())) is too heavy, simple list comprehension is enough
* my_list[::(-1) ** row] for reverse every odd line and save your filling idea
return list(map(list, [r[...] if i%2 else r[...] for i in range(r
More
Это решение точно смотрится лучше предыдущего. Но тоже есть что поправить :)
Для начала хотя бы так:
datetime(1970, 1, 1, 0, 0, 0) --> datetime.max
datetime(9999, 12, 31, 23, 59, 59)) --> datetime.max
Далее, раз вы уже используете цикл по zip, прямо напрашивается сделать так:
i
More
As for me, four strings for such task is too much :)
p = text.find(symbol, text.find(symbol) + 1)
return None if p < 0 else p
More
There are some tricks to optimize solution:
# original code
return prod([int(i) for i in list(str(number).replace('0', ''))])
# most of python functions accept generators -->
return prod(int(i) for i in list(str(number).replace('0', '')))
# you can easily iterate strin
More
Very familiar solution in comments :) My last version is 5 lines only...
More
Можно чуть пооптимизировать:
return sum([int(i if i.isdigit() else 0) for i in text.split()])
-->
return sum(int(i if i.isdigit() else 0) for i in text.split()) # суммируем генератор, а не список
-->
return sum(int(i) for i in filter(str.isdigit, text.split())) # предварите
More
Great! Btw...
return items[items.index(border) if border in items else 0:]
More
Слишком страшная функция def fight(self, army1, army2) :) Можно сделать так...
Запилить isalive для армии
Просто использовать функцию fight(), которая у вас уже есть
В зависимости от того, что вернет функция, убивать элемент либо из первого списка, либо из второго...
class Battle:
de
More
Constructions like 'True if condition1 else condition2' looks strange, and may be replaced with 'condition1 or condition2'
return True if not text.replace(' ', '').isalpha() else text.isupper()
-->
return not text.replace(' ', '').isalpha() or text.isupper()
Btw for this task you can s
More
И опять слишком похоже на C++ :)
Есть несколько хитростей, чтобы сократить функцию до одной строчки
1. Добавьте в MORSE такое значение - "": "*", и посмотрите, во что превратится code.split(' '). Это позволит вам избавиться от цикла по словам.
2. Используйте comprehension вместо внутреннего цикла (
More
I love conditions in python!
if result >= 0 and result <= 180:
return result
else:
return "I don't see the sun!"
-->
return result if 0 <= result <= 180 else "I don't see the sun!"
And you can optimize angle calclulations:
all code
-->
result = 15 * in
More
Slices is the best way to improve code:
even_positions_sum = 0
for i in range(0, len(array), 2):
even_positions_sum += array[i]
-->
even_positions_sum = sum(array[::2])
And avoid exceptions:
try:
last_digit = array[-1]
except:
last_digit = 0
More
Для для is_alive можно использовать декоратор \@property. Уберет кучу строчек кода (минимум 4)
@property
def is_alive(self):
return self.health > 0
More
a slightly longer in symbols than with zip, but faster
return sum([(b - a).total_seconds() for a, b in zip(els[::2], els[1::2])])
More
Wooow, it's too hard to understand for me. But solution is pretty easy.
1. Filter string from anything except brackets
2. Replace '()' or '[]' or '{}' pair with the empty string
3. Add solt to taste (repeat while you have any to replace)
4. If result is empty string - expression is correct
Btw...
More