프로젝트를 다른 시스템(예: 동료 개발자의 컴퓨터 또는 배포 서버)으로 옮길 때, 동일한 파이썬 버전과 패키지를 정확히 맞춰야 하는 번거로움이 있습니다. 가상환경 내 설치된 패키지 목록을requirements.txt로 저장하고, 이를 다른 환경에서 설치하면 동일한 실행 환경을 쉽게 재현할 수 있습니다.
[python] Scatter plot animated using python, ffmpeg
"""
An animated scatter plot can be created using Python's matplotlib library with its animation module.
Here's an example of how to create an animated scatter plot, where points move dynamically over time.
"""import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Generate random initial data for the scatter plot
num_points = 50
x_data = np.random.rand(num_points)
y_data = np.random.rand(num_points)
colors = np.random.rand(num_points)
sizes = np.random.rand(num_points) * 100# Function to update scatter plotdefupdate(frame):global x_data, y_data
x_data += (np.random.rand(num_points) - 0.5) * 0.1# Randomly move x
y_data += (np.random.rand(num_points) - 0.5) * 0.1# Randomly move y
scatter.set_offsets(np.c_[x_data, y_data]) # Update positions
scatter.set_sizes(np.random.rand(num_points) * 100) # Update sizes
scatter.set_array(np.random.rand(num_points)) # Update colorsreturn scatter,
# Create the figure and scatter plot
fig, ax = plt.subplots()
scatter = ax.scatter(x_data, y_data, c=colors, s=sizes, cmap='viridis', alpha=0.6)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title("Animated Scatter Plot")
# Create animation
ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)
# Show the animation
plt.show()
import matplotlib.animation as animation
animation.FFMpegWriter = animation.writers['ffmpeg']
"""
Install FFmpeg: FFmpeg is required to save animations in video formats like .mp4. Install it as follows:
Windows:
Download the FFmpeg executable from https://ffmpeg.org/download.html.
Add the bin folder to your system’s PATH environment variable.
1.EXE 파일 다운받아서 *.7z 파일 다운로드.
2.압축 풀고, 시스템 환경 변수에 추가.
3. ffmpeg -version 으로 실행되는지 확인
"""
ani.save("animated_scatter.mp4", writer="ffmpeg", fps=30) # Save as MP4
"""
정렬 알고리즘 실행 시 비용 계산은 보통 실행 시간(시간 복잡도)이나 작업 횟수를 측정하여 이뤄집니다.
이를 위해 Python에서 time 모듈이나 timeit 모듈을 사용할 수 있습니다.
시간 복잡도에 따른 차이
1.퀵 정렬:
평균 시간 복잡도 𝑂(𝑛log𝑛)O(nlogn).
큰 데이터셋에서도 효율적으로 작동.
2.버블 정렬:
최악 및 평균 시간 복잡도 𝑂(𝑛2)O(n 2 ).
작은 데이터셋에서는 괜찮지만, 데이터 크기가 클수록 비효율적.
"""import time # 실행 시간 측정을 위한 모듈# 퀵 정렬 알고리즘defquick_sort(arr):iflen(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# 버블 정렬 알고리즘defbubble_sort(arr):
n = len(arr)
for i inrange(n):
for j inrange(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
# 테스트 데이터 생성import random
array_size = 1000# 데이터 크기
test_array = random.sample(range(1, 10000), array_size)
print(f" test_array : {test_array} \n\n\n")
# 퀵 정렬 실행 시간 측정
start_time = time.time()
quick_sort(test_array.copy())
end_time = time.time()
print(f"퀵 정렬 실행 시간: {end_time - start_time:.5f}초")
# 버블 정렬 실행 시간 측정
start_time = time.time()
bubble_sort(test_array.copy())
end_time = time.time()
print(f"버블 정렬 실행 시간: {end_time - start_time:.5f}초")
# 병합 정렬 알고리즘defmerge_sort(arr):iflen(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
defmerge(left, right):
result = []
i = j = 0while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# 병합 정렬 실행 시간 측정
start_time = time.time()
merge_sort(test_array.copy())
end_time = time.time()
print(f"병합 정렬 실행 시간: {end_time - start_time:.5f}초")
[python] 정렬 알고리즘 실행 시 비용 계산은 보통 실행 시간(시간 복잡도)이나 작업 횟수를 측정
import numpy as np
x = np.arange(7,16);
y = np.arange(1,18,2);
z = np.column_stack((x[:: -1],y))
for i,j in z:
print(' '*i+'*'*j)
for r inrange(3):
print(' '*13, ' || ')
print(' '*12, end = '\======/')
print('')