반응형

https://www.geeksforgeeks.org/stack-in-python/

 

Stack in Python - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.

The functions associated with stack are:

  • empty() – Returns whether the stack is empty – Time Complexity: O(1)
  • size() – Returns the size of the stack – Time Complexity: O(1)
  • top() / peek() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
  • push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
  • pop() – Deletes the topmost element of the stack – Time Complexity: O(1)

Implementation:

There are various ways from which a stack can be implemented in Python. This article covers the implementation of a stack using data structures and modules from the Python library. 
Stack in Python can be implemented using the following ways: 

  • list
  • Collections.deque
  • queue.LifoQueue

 

# Python program to
# demonstrate stack implementation
# using list
 
stack = []
 
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
 
print('Initial stack')
print(stack)
 
# pop() function to pop
# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
 
print('\nStack after elements are popped:')
print(stack)
 
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[Python] Turtle 🐢  (0) 2023.11.09
[python] Top 10 Python Libraries  (0) 2023.10.26
[python] Create a Video Chat/Video Steaming App using Python  (0) 2023.10.20
[python] PyAudio  (0) 2023.10.20
[Python] savefig 0.0.4  (0) 2023.10.17
반응형

Create a Video Chat/Video Steaming App using Python

https://medium.com/geekculture/creating-video-chat-app-using-python-9da0a9c386ba

 

Create a Video Chat/Video Steaming App using Python

Due to the pandemic the only way to stay connected through the internet. But due to such a huge activity in Advertisement department, data…

medium.com

Server.py

from pyfiglet import Figlet
os.system("clear")
pyf = Figlet(font='puffy')
a = pyf.renderText("Video Chat App without Multi-Threading")
b = pyf.renderText("Server")
os.system("tput setaf 3")
print(a)
import socket, cv2, pickle,struct
# Socket Create
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host_name  = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
print('HOST IP:',host_ip)
port = 9999
socket_address = (host_ip,port)
# Socket Bind
server_socket.bind(socket_address)
# Socket Listen
server_socket.listen(1)
print("Listening at:",socket_address)
# Socket Accept
while True:
 client_socket,addr = server_socket.accept()
 print('Connected to:',addr)
 if client_socket:
  vid = cv2.VideoCapture(0)
  
  while(vid.isOpened()):
   ret,image = vid.read()
   img_serialize = pickle.dumps(image)
   message = struct.pack("Q",len(img_serialize))+img_serialize
   client_socket.sendall(message)
   
   cv2.imshow('Video from Server',image)
   key = cv2.waitKey(10) 
   if key ==13:
    client_socket.close()

Client.py

from pyfiglet import Figlet
os.system("clear")
pyf = Figlet(font='puffy')
a = pyf.renderText("Video Chat App without Multi-Threading")
b = pyf.renderText("Client")
os.system("tput setaf 3")
print(a)
import socket,cv2, pickle,struct
# create socket
client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#  server ip address here
host_ip = '<IP>' 
port = 9999
client_socket.connect((host_ip,port)) 
data = b""
metadata_size = struct.calcsize("Q")
while True:
 while len(data) < metadata_size:
  packet = client_socket.recv(4*1024) 
  if not packet: break
  data += packet
 packed_msg_size = data[:metadata_size]
 data = data[metadata_size:]
 msg_size = struct.unpack("Q",packed_msg_size)[0]
 
 while len(data) < msg_size:
  data += client_socket.recv(4*1024)
  frame_data = data[:msg_size]
  data  = data[msg_size:]
  frame = pickle.loads(frame_data)
  cv2.imshow("Receiving Video ",frame)
  key = cv2.waitKey(10) 
  if key  == 13:
   break
client_socket.close()
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[python] Top 10 Python Libraries  (0) 2023.10.26
[python] Stack in Python  (0) 2023.10.24
[python] PyAudio  (0) 2023.10.20
[Python] savefig 0.0.4  (0) 2023.10.17
[python] pdf to png, 해상도 높게 저장하기  (0) 2023.10.04
반응형

PyAudio

https://pypi.org/project/PyAudio/

 

PyAudio

Cross-platform audio I/O with PortAudio

pypi.org

PyAudio는 크로스 플랫폼 오디오 I/O 라이브러리인 PortAudio v19에 대한 Python 바인딩을 제공합니다. PyAudio를 사용하면 Python을 사용하여 GNU/Linux, Microsoft Windows 및 Apple macOS와 같은 다양한 플랫폼에서 오디오를 쉽게 재생하고 녹음할 수 있습니다.

 

pip install PyAudio

반응형
반응형

savefig 0.0.4

 

pip install savefig

 

https://pypi.org/project/savefig/

 

Save matplotlib figures with embedded metadata for reproducibility and profit

 

반응형
반응형

[python] pdf to png, 해상도 높게 저장하기 

 

import fitz  # PyMuPDF

def pdf_to_png(pdf_file, output_folder, dpi=300):
    # Open the PDF file
    pdf_document = fitz.open(pdf_file)
    
    for page_number in range(pdf_document.page_count):
        # Get the page
        page = pdf_document[page_number]
        
        # Set the resolution (DPI)
        zoom = dpi / 72.0
        mat = fitz.Matrix(zoom, zoom)
        image = page.get_pixmap(matrix=mat)
        
        # Save the image as a PNG file
        image.save(f"{output_folder}/page_{page_number + 1}.png", "png")

    # Close the PDF file
    pdf_document.close()

if __name__ == "__main__":
    input_pdf = "input.pdf"  # Replace with your PDF file path
    output_folder = "output_images"  # Replace with your output folder
    dpi = 600  # Adjust DPI as needed
    
    pdf_to_png(input_pdf, output_folder, dpi)
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[python] PyAudio  (0) 2023.10.20
[Python] savefig 0.0.4  (0) 2023.10.17
[python] matrix 3.0.0  (0) 2023.10.04
[python] 알고리즘 - 탐색  (0) 2023.09.27
[python] 알고리즘 - 정렬  (0) 2023.09.27
반응형

https://pypi.org/project/matrix/

 

matrix

Generic matrix generator.

pypi.org

matrix 3.0.0

Generic matrix generator.

Installation

pip install matrix

You can also install the in-development version with:

pip install https://github.com/ionelmc/python-matrix/archive/main.zip

Documentation

https://python-matrix.readthedocs.io/

Development

To run all the tests run:

tox
반응형
반응형

알고리즘 탐색(Search)

탐색이란, 원하는 값을 찾는 것입니다.

선형 탐색(Linear Search)

순서대로 하나씩 찾는 방법 입니다.

이분(이진) 탐색(Binary Search)

반씩 제외하면서 찾는 방법 입니다.

해시 탐색(Hash Search)

선형탐색이나 이진탐색은, 어떤 값이 어떤 index에 들어있는지에 대한 정보가 없는 상태에서 탐색할 때 사용하는 방식이 었습니다.반면에 해시 탐색은 값과 index를 미리 연결해 둠으로써 짧은 시간에 탐색할 수 있는 알고리즘입니다.

완전 탐색

브루트 포스(Brute Force)

brute: 무식한, force: 힘 무식한 힘으로 해석할 수 있다. 완전탐색 알고리즘. 즉, 가능한 모든 경우의 수를 모두 탐색하면서 요구조건에 충족되는 결과만을 가져옵니다. 이 알고리즘의 강력한 점은 예외 없이 100%의 확률로 정답만을 출력한다는 점입니다.

백트래킹

해를 찾는 도중 해가 아니어서 막히면, 되돌아가서 다시 해를 찾아가는 기법을 말합니다. 최적화 문제와 결정 문제를 푸는 방법이 됩니다.

재귀함수

함수는 자기 자신을 내부에서 호출할 수 있다. 이러한 함수를 재귀 함수라고 한다. 재귀 알고리즘(recursive algorithm)이란 재귀 함수를 이용하여 문제를 해결하는 알고리즘을 말합니다.

# 정렬/탐색 알고리즘 : https://modulabs.co.kr/blog/algorithm-python/
# Search 탐색 

def linear_search(list, target):
    for i in range(0, len(list)):
        if list[i] == target:
            return i
    return None

def binary_search(list, target):
    first = 0
    last = len(list) - 1

    while first <= last:
        midpoint = (first + last) // 2
        if list[midpoint] == target:
            return midpoint
        elif list[midpoint] < target:
            first = midpoint + 1
        else:
            last = midpoint - 1
    return None

def hash_search(list, target):
    hash_table = {}
    for i in range(0, len(list)):
        hash_table[list[i]] = i
    if target in hash_table:
        return hash_table[target]
    return None

def brute_force_search(list, target):
    for i in range(0, len(list)):
        for j in range(i + 1, len(list)):
            if list[i] + list[j] == target:
                return [i, j]
    return None

def recursive_binary_search(list, target):
    if len(list) == 0:
        return False
    else:
        midpoint = len(list) // 2
        if list[midpoint] == target:
            return True 
        else:
            if list[midpoint] < target:
                return recursive_binary_search(list[midpoint + 1:], target)
            else:
                return recursive_binary_search(list[:midpoint], target)







print(linear_search([1,2,3,4,5], 5)) 

print(binary_search([1,2,3,4,5], 5))

print(hash_search([1,2,3,4,5], 5))

print(brute_force_search([1,2,3,4,5], 5))

print(recursive_binary_search([1,2,3,4,5], 5))

BFS(너비 우선 탐색) & DFS(깊이 우선 탐색)

# 정렬/탐색 알고리즘 : https://modulabs.co.kr/blog/algorithm-python/
# Search 탐색 2 : BFS(너비 우선 탐색) & DFS(깊이 우선 탐색)

from collections import deque

graph_list = { 1: set([2, 3]),
                2: set([1, 3, 4]),
                3: set([1, 5]),
                4: set([1]),
                5: set([2,6]),
                6: set([3,4])}

root_node = 1

def bfs(graph, root):
    visited = []
    queue = deque([root])
    while queue:
        node = queue.popleft()
        if node not in visited:
            visited.append(node)
            queue += graph[node] - set(visited)
    return visited

print(bfs(graph_list, root_node))

def dfs(graph, root):
    visited = []
    stack = [root]
    while stack:
        node = stack.pop()
        if node not in visited:
            visited.append(node)
            stack += graph[node] - set(visited)
    return visited

print(dfs(graph_list, root_node))
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[python] pdf to png, 해상도 높게 저장하기  (0) 2023.10.04
[python] matrix 3.0.0  (0) 2023.10.04
[python] 알고리즘 - 정렬  (0) 2023.09.27
[python] sudoku 만들기 - 랜덤 문제  (0) 2023.09.27
[python] sudoku 만들기  (0) 2023.09.27
반응형

[python] sudoku 만들기 - 랜덤 문제 

#sudoku puzzle create using python chatGPT
import random

def generate_solved_sudoku():
    base  = 3
    side  = base*base
    # pattern for a baseline valid solution
    def pattern(r,c): return (base*(r%base)+r//base+c)%side

    # randomize rows, columns and numbers (of valid base pattern)
    def shuffle(s): return random.sample(s,len(s)) 
    rBase = range(base) 
    rows  = [ g*base + r for g in shuffle(rBase) for r in shuffle(rBase) ] 
    cols  = [ g*base + c for g in shuffle(rBase) for c in shuffle(rBase) ]
    nums  = shuffle(range(1,base*base+1))

    # produce board using randomized baseline pattern
    board = [ [nums[pattern(r,c)] for c in cols] for r in rows ]
    
    return board

def print_sudoku(board):
    for i in range(9):
        if i % 3 == 0 and i != 0:
            print("- - - - - - - - - - - -")
        for j in range(9):
            if j % 3 == 0 and j != 0:
                print("|", end=" ")
            print(board[i][j], end=" ")
        print()

def remove_numbers(board, difficulty_level):
    """
    Remove numbers from the solved Sudoku grid based on the difficulty level.
    """
    if difficulty_level == 'easy':
        num_to_remove = 30  # Easy: 30 numbers removed
    elif difficulty_level == 'medium':
        num_to_remove = 40  # Medium: 40 numbers removed
    else:
        num_to_remove = 50  # Hard: 50 numbers removed
    
    for _ in range(num_to_remove):
        row = random.randint(0, 8)
        col = random.randint(0, 8)
        if board[row][col] != 0:
            board[row][col] = 0

# Generate a solved Sudoku puzzle
solved_sudoku = generate_solved_sudoku()

# Print the solved Sudoku puzzle
print("Solved Sudoku Puzzle:")
print_sudoku(solved_sudoku)

# Create a copy of the solved puzzle
unsolved_sudoku = [row[:] for row in solved_sudoku]

# Remove numbers to create a puzzle
difficulty_level = 'medium'  # Change difficulty level as needed ('easy', 'medium', 'hard')
remove_numbers(unsolved_sudoku, difficulty_level)

# Print the unsolved Sudoku puzzle (the generated puzzle)
print("\nUnsolved Sudoku Puzzle:")
print_sudoku(unsolved_sudoku)
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[python] 알고리즘 - 탐색  (0) 2023.09.27
[python] 알고리즘 - 정렬  (0) 2023.09.27
[python] sudoku 만들기  (0) 2023.09.27
[python] How to send text messages with Python for Free  (0) 2023.09.26
[python] algorithm, 알고리즘  (0) 2023.09.20

+ Recent posts