Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Ускорение кода питон

Данияр Бурнашев 11 Ученик (68), на голосовании 2 недели назад
Можете каким либо образом ускорить код на питоне?

t = int(input())
for i in range(t):
n, k = map(int, input().split())
a = list(map(int, input().split()))
srednee = sum(a) / len(a)
if n % 2 == 0:
hinata = a[:len(a) // 2]
kenma = a[len(a) // 2:]
hinata.sort(reverse=True)
kenma.sort(reverse=True)
else:
hinata = a[:len(a) // 2]
kenma = a[(len(a) // 2) + 1:]
if a[len(a) // 2] > srednee:
hinata.append(a[len(a) // 2])
else:
kenma.reverse()
kenma.append(a[len(a) // 2])
kenma.reverse()
hinata.sort(reverse=True)
kenma.sort(reverse=True)
while k > 0:
srednee = (sum(hinata) + sum(kenma)) / (len(hinata) + len(kenma))
if len(hinata) == len(kenma):
if (abs(srednee - hinata[len(hinata) - 1])) > (abs(srednee - kenma[0])):
hinata.remove(hinata[len(hinata) - 1])
k -= 1
else:
kenma.remove(kenma[0])
k -= 1
else:
if len(hinata) > len(kenma):
hinata.remove(hinata[len(hinata) - 1])
k -= 1
else:
kenma.remove(kenma[0])
k -= 1
print(sum(hinata) - sum(kenma))
Голосование за лучший ответ
— Обычный особенный человек Мыслитель (6400) 1 месяц назад
Yes, here's how you can potentially make your Python code faster:
1. Use NumPy:
* Replace standard lists with NumPy arrays for a, hinata, and kenma.
* Use NumPy operations for calculating mean (srednee), sorting, and sums. This leverages optimized C code under the hood.
2. Avoid Repeated Calculations:
* Calculate len(a) // 2 once outside loops and store it in a variable.
* Pre-calculate abs(srednee - hinata[len(hinata) - 1]) and abs(srednee - kenma[0]) before the while loop to avoid doing it every iteration.
3. Consider Cython:
* If further optimization is critical, use Cython to compile parts of your code into C extensions for significant speedups.
Note: Without knowing the purpose and typical input size, it's harder to suggest more targeted optimizations.
Let me know if you'd like to see an example of how to make these changes us
ing NumPy!
Похожие вопросы