반응형

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] 알고리즘 - 정렬

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

 

파이썬 알고리즘 정의와 종류 (정렬, 탐색)

여러 가지 알고리즘 중에서 정렬 알고리즘과 탐색 알고리즘의 정의와 종류를 설명하고 파이썬 코드로 구현한 알고리즘을 보여드립니다.

modulabs.co.kr

정렬(Sorting)

정렬은 특정한 기준에 따라 데이터를 늘어놓는 알고리즘입니다.

버블 정렬(Bubble Sort)

버블 정렬은 바로 옆에 있는 것과 비교해서 정렬하는 것입니다. 구현은 쉽지만 효율성이 매우 낮다고 알려져 있습니다.

선택 정렬(Selection Sort)

데이터를 선택 정렬은 배열에서 작은 데이터를 선별하여서 데이터를 앞으로 보내는 정렬의 일종입니다. 이 정렬도 효율은 낮습니다.

삽입 정렬(Insertion Sort)

삽입 정렬은 자료 배열의 모든 요소를 앞에서부터 차례대로 이미 정렬된 배열 부분과 비교하여, 자신의 위치를 찾아 삽입함으로써 정렬을 완성하는 알고리즘입니다.

퀵 정렬(Quick Sort)

퀵 정렬은 찰스 앤터니 리처드 호어가 개발한 정렬 알고리즘이다. 다른 원소와의 비교만으로 정렬을 수행하는 비교 정렬에 속한다. 퀵 정렬은 n개의 데이터를 정렬할 때, 최악의 경우에는 O(n²)번의 비교를 수행하고, 평균적으로 O(n log n)번의 비교를 수행합니다.

병합 정렬(Merge Sort)

합병 정렬 또는 병합 정렬은 O(n log n) 비교 기반 정렬 알고리즘이다. 일반적인 방법으로 구현했을 때 이 정렬은 안정 정렬에 속하며, 분할 정복 알고리즘의 하나 입니다.

힙 정렬(Heap Sort)

힙 정렬이란 최대 힙 트리나 최소 힙 트리를 구성해 정렬을 하는 방법으로서, 내림차순 정렬을 위해서는 최소 힙을 구성하고 오름차순 정렬을 위해서는 최대 힙을 구성하면 됩니다.

기수 정렬(Radix Sort)

기수 정렬은 기수 별로 비교 없이 수행하는 정렬 알고리즘이다. 기수로는 정수, 낱말, 천공카드 등 다양한 자료를 사용할 수 있으나 크기가 유한하고 사전순으로 정렬할 수 있어야 한다. 버킷 정렬의 일종으로 취급되기도 합니다.

계수 정렬(Count Sort)

계수 정렬 또는 카운팅 소트는 컴퓨터 과학에서 정렬 알고리즘의 하나로서, 작은 양의 정수들인 키에 따라 객체를 수집하는 것, 즉 정수 정렬 알고리즘의 하나 입니다.

 

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

import random

class Sort :
    def bubble_sort(arr):
        for i in range(len(arr)):
            for j in range(len(arr) - i - 1):
                if arr[j] > arr[j+1]:
                    arr[j], arr[j+1] = arr[j+1], arr[j]
        return arr


    def selection_sort(arr):
        for i in range(len(arr)):
            min_index = i
            for j in range(i+1, len(arr)):
                if arr[min_index] > arr[j]:
                    min_index = j
            arr[i], arr[min_index] = arr[min_index], arr[i]
        return arr


    def quick_sort(arr):
        if len(arr) <= 1:
            return arr
        pivot = arr[len(arr) // 2]
        left, right, equal = [], [], []
        for i in arr:
            if i < pivot:
                left.append(i)
            elif i > pivot:
                right.append(i)
            else:
                equal.append(i)
        return Sort.quick_sort(left) + equal + Sort.quick_sort(right)


    def merge_sort(arr):
        if len(arr) < 2:
            return arr
        
        mid = len(arr) // 2
        left = Sort.merge_sort(arr[:mid])
        right = Sort.merge_sort(arr[mid:])

        merged_arr = []
        l = r = 0
        while l < len(left) and r < len(right):
            if left[l] < right[r]:
                merged_arr.append(left[l])
                l += 1
            else:
                merged_arr.append(right[r])
                r += 1

        merged_arr += left[l:]
        merged_arr += right[r:]
        return merged_arr


    def heap_sort(arr):
        def heapify(arr, n, i):
            largest = i
            l = 2 * i + 1
            r = 2 * i + 2

            if l < n and arr[i] < arr[l]:
                largest = l

            if r < n and arr[largest] < arr[r]:
                largest = r

            if largest != i:
                arr[i], arr[largest] = arr[largest], arr[i]
                heapify(arr, n, largest)

        n = len(arr)
        for i in range(n, -1, -1):
            heapify(arr, n, i)

        for i in range(n-1, 0, -1):
            arr[i], arr[0] = arr[0], arr[i]
            heapify(arr, i, 0)

        return arr



    def radix_sort(arr):
        RADIX = 10
        placement = 1

        max_digit = max(arr)

        while placement < max_digit:
            buckets = [list() for _ in range(RADIX)]

            for i in arr:
                tmp = int((i / placement) % RADIX)
                buckets[tmp].append(i)

            a = 0
            for b in range(RADIX):
                buck = buckets[b]
                for i in buck:
                    arr[a] = i
                    a += 1

            placement *= RADIX

        return arr


    def counting_sort(arr):
        max_value = max(arr)
        m = max_value + 1
        count = [0] * m

        for a in arr:
            count[a] += 1

        i = 0
        for a in range(m):
            for c in range(count[a]):
                arr[i] = a
                i += 1
        return arr


arr = [i for i in random.sample(range(10), 10)]



print("Original array: ", arr)
print("Bubble sort: ", Sort.bubble_sort(arr))
print("Selection sort: ", Sort.selection_sort(arr))
print("Quick sort: ", Sort.quick_sort(arr))
print("Merge sort: ", Sort.merge_sort(arr))
print("Heap sort: ", Sort.heap_sort(arr))
print("Radix sort: ", Sort.radix_sort(arr))
print("Counting sort: ", Sort.counting_sort(arr))

 

반응형

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

[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] How to send text messages with Python for Free  (0) 2023.09.26
반응형

[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
반응형

# sudoku using python

def is_valid_move(board, row, col, num):
    """
    Check if placing 'num' at position (row, col) is a valid move.
    """
    # Check the row
    if num in board[row]:
        return False

    # Check the column
    if num in [board[i][col] for i in range(9)]:
        return False

    # Check the 3x3 subgrid
    start_row, start_col = 3 * (row // 3), 3 * (col // 3)
    for i in range(start_row, start_row + 3):
        for j in range(start_col, start_col + 3):
            if board[i][j] == num:
                return False

    return True

def solve_sudoku(board):
    """
    Solve the Sudoku puzzle using backtracking.
    """
    empty_cell = find_empty_cell(board)

    if not empty_cell:
        # Puzzle is solved
        return True

    row, col = empty_cell

    for num in range(1, 10):
        if is_valid_move(board, row, col, num):
            board[row][col] = num

            if solve_sudoku(board):
                return True

            # If the current placement doesn't lead to a solution, backtrack
            board[row][col] = 0

    # No valid move found, need to backtrack
    return False

def find_empty_cell(board):
    """
    Find an empty cell in the Sudoku grid.
    """
    for i in range(9):
        for j in range(9):
            if board[i][j] == 0:
                return (i, j)
    return None

def print_board(board):
    """
    Print the Sudoku grid.
    """
    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()

# Example Sudoku puzzle (0 represents empty cells)
sudoku_board = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
]

print("Sudoku Puzzle:")
print_board(sudoku_board)
print("\nSolving...\n")

if solve_sudoku(sudoku_board):
    print("Sudoku Solution:")
    print_board(sudoku_board)
else:
    print("No solution exists.")
반응형
반응형

How to send text messages with Python for Free

https://medium.com/testingonprod/how-to-send-text-messages-with-python-for-free-a7c92816e1a4

 

How to send text messages with Python for Free

This week, I am going to be showing you how to send text messages with Python for free. It’s actually surprisingly easy to do and I thought…

medium.com

What you’ll need

For this post, I’ll be using the following:

It should be noted that if you’re using gmail, like me, you’ll need to setup and use an application password with your account. You can read more information and security warnings on that here: https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor&visit_id=637700239874464736-1954441174&rd=1

import smtplib
import sys
 
CARRIERS = {
    "att": "@mms.att.net",
    "tmobile": "@tmomail.net",
    "verizon": "@vtext.com",
    "sprint": "@messaging.sprintpcs.com"
}
 
EMAIL = "EMAIL"
PASSWORD = "PASSWORD"
 
def send_message(phone_number, carrier, message):
    recipient = phone_number + CARRIERS[carrier]
    auth = (EMAIL, PASSWORD)
 
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(auth[0], auth[1])
 
    server.sendmail(auth[0], recipient, message)
 
 
if __name__ == "__main__":
    if len(sys.argv) < 4:
        print(f"Usage: python3 {sys.argv[0]} <PHONE_NUMBER> <CARRIER> <MESSAGE>")
        sys.exit(0)
 
    phone_number = sys.argv[1]
    carrier = sys.argv[2]
    message = sys.argv[3]
 
    send_message(phone_number, carrier, message)
반응형

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

[python] sudoku 만들기 - 랜덤 문제  (0) 2023.09.27
[python] sudoku 만들기  (0) 2023.09.27
[python] algorithm, 알고리즘  (0) 2023.09.20
[python] GUI 비밀번호 자동 생성기  (0) 2023.09.18
[python] pyperclip  (0) 2023.09.18
반응형

[한빛미디어] "이것이 취업을 위한 코딩 테스트다 with 파이썬" 전체 소스코드 저장소입니다
https://github.com/ndb796/python-for-coding-test

Types of Algorithm

    Searching
    Sorting
    Recursive
    Backtracking
    Greedy
    Randomized
    Divide & Conquer
    Dynamic Programing


 https://www.instagram.com/p/CxZgarwyv_2/?igshid=MjNiZGVkZTJkZQ%3D%3D 



https://www.geeksforgeeks.org/python-data-structures-and-algorithms/

반응형

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

[python] sudoku 만들기  (0) 2023.09.27
[python] How to send text messages with Python for Free  (0) 2023.09.26
[python] GUI 비밀번호 자동 생성기  (0) 2023.09.18
[python] pyperclip  (0) 2023.09.18
[Python] kivy  (0) 2023.09.15
반응형

#####
"""https://copyassignment.com/password-generator-in-python-gui-application/"""
#####
# importing the tkinter module
from tkinter import *

# importing the pyperclip module to use it to copy our generated 
# password to clipboard
import pyperclip

# random module will be used in generating the random password
import random

# initializing the tkinter
root = Tk()

# setting the width and height of the gui
root.geometry("400x400")    # x is small case here

# declaring a variable of string type and this variable will be 
# used to store the password generated
passstr = StringVar()

# declaring a variable of integer type which will be used to 
# store the length of the password entered by the user
passlen = IntVar()

# setting the length of the password to zero initially
passlen.set(0)


# function to generate the password
def generate():
    # storing the keys in a list which will be used to generate 
    # the password 
    pass1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
            'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 
            'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', 
            '9', '0', ' ', '!', '@', '#', '$', '%', '^', '&', 
            '*', '(', ')']

    # declaring the empty string
    password = ""

    # loop to generate the random password of the length entered           
    # by the user
    for x in range(passlen.get()):
        password = password + random.choice(pass1)

    # setting the password to the entry widget
    passstr.set(password)

# function to copy the password to the clipboard
def copytoclipboard():
    random_password = passstr.get()
    pyperclip.copy(random_password)

# Creating a text label widget
Label(root, text="Password Generator Application", font="calibri 20 bold").pack()

# Creating a text label widget
Label(root, text="Enter password length").pack(pady=3)

# Creating a entry widget to take password length entered by the 
# user
Entry(root, textvariable=passlen).pack(pady=3)

# button to call the generate function
Button(root, text="Generate Password", command=generate).pack(pady=7)

# entry widget to show the generated password
Entry(root, textvariable=passstr).pack(pady=3)

# button to call the copytoclipboard function
Button(root, text="Copy to clipboard", command=copytoclipboard).pack()

# mainloop() is an infinite loop used to run the application when 
# it's in ready state 
root.mainloop()

Python의 tkinter 라이브러리를 사용하여 간단한 비밀번호 생성기 GUI 애플리케이션을 만든 것 같습니다. 이 애플리케이션을 사용하면 사용자는 비밀번호 길이를 지정한 다음 지정된 길이에 따라 무작위 비밀번호를 생성할 수 있습니다.

코드 분석은 다음과 같습니다.

  1. 필요한 모듈을 가져옵니다: GUI용 tkinter, 생성된 비밀번호를 클립보드에 복사하기 위한 pyperclip, 임의 문자 생성용 Random.
  2. tkinter 인스턴스를 초기화하고 GUI 창의 형상을 설정합니다.
  3. 생성된 비밀번호와 사용자가 입력한 비밀번호 길이를 저장하기 위해 tkinter 변수( passstr및 )를 만듭니다.passlen
  4. generate사용자가 지정한 길이에 따라 임의의 비밀번호를 생성하는 기능을 정의합니다 . 문자 목록( pass1)을 사용하여 무작위로 문자를 선택하여 암호를 만듭니다.
  5. copytoclipboardpyperclip 모듈을 사용하여 생성된 비밀번호를 클립보드에 복사하는 함수를 정의합니다 .
  6. 라벨, 입력 필드, 버튼 등의 GUI 요소를 생성하고 이를 기능과 연결합니다.
  7. 를 사용하여 기본 GUI 이벤트 루프를 시작합니다 root.mainloop(). 이는 사용자가 창을 닫을 때까지 애플리케이션을 계속 실행합니다.

이 코드를 실행하면 원하는 비밀번호 길이를 입력할 수 있는 GUI가 생성됩니다. "비밀번호 생성" 버튼을 클릭하여 임의의 비밀번호를 생성한 다음 "클립보드에 복사" 버튼을 클릭하여 비밀번호를 클립보드에 복사합니다. .

귀하의 코드는 기본 비밀번호 생성기 애플리케이션에 맞게 구조화되어 있고 기능적으로 작동하는 것으로 보입니다. 필요한 경우 오류 처리를 추가하거나 사용자 인터페이스를 개선하여 이를 더욱 향상시킬 수 있습니다.

반응형

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

[python] How to send text messages with Python for Free  (0) 2023.09.26
[python] algorithm, 알고리즘  (0) 2023.09.20
[python] pyperclip  (0) 2023.09.18
[Python] kivy  (0) 2023.09.15
[python] PDF to png, import fitz , PyMuPDF  (0) 2023.09.15

+ Recent posts