반응형

File 읽어서 객체에 담기

# test 객체


class test:
	name: str
    age: int

def test():
    file_path = "test.txt"
    # 파일 읽기
    with open(file_path, 'r', encoding='UTF8') as file:
        file_content = file.read()

    # JSON 파싱
    data = json.loads(file_content)
    x = data["data"]

    # Syncer 인스턴스 생성
    test_data = test(**x)
반응형

'Python' 카테고리의 다른 글

파이썬 lambda 사용시  (0) 2023.06.01
print 하면 <map object at 0x10446d880> 나올 때  (0) 2023.06.01
[python] list 사용 방법  (0) 2023.05.29
zip()  (0) 2023.05.03
combinations()  (0) 2023.05.03
반응형
반응형

Two Sum

https://leetcode.com/problems/two-sum/

 

Two Sum - LeetCode

Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not

leetcode.com

 

코드

import time
import datetime

def twoSum(nums, target):
    start = time.time()
    # filter를 통해 뒤에 오는 숫자가 많으면 제거 후 index() 값을 구하는게 빨라질꺼 같아서 적용해보았지만 
    # 주어진 nums 배열에서는 속도 차이가 없었습니다.
    # nums = list(filter(lambda x: x < target, nums))

    for i, num in enumerate(nums):
        n = target - num
        if n in nums[i + 1:]:
            # 걸린 시간: 0:00:00.000013
            # return [i, nums.index(n)]
            # 위에 코드는 Example 3에서 [3, 3] 배열에서 2번째 인덱스 값이 틀리게 계산됩니다.
            # 이유는 값은 값이 있을 때 index() 함수는 가장 먼저 같은 값으로 있는 index를 return 해주기 때문입니다.

            # 걸린 시간: 0:00:00.000013
            # 시간복잡도:O(n^2)
            # nums.index(n)으로 구한 것과 시간 차이가 없읍니다.
            # nums의 i + 1 부터 검색하여 n 숫자의 index를 구하고 i만큼 빼고 index를 구했으니 다시 i의 값을 더해줍니다.
            # 그리고 나서 i가 0일 수 있으니 1을 더해줍니다.
            return [i, nums[i + 1:].index(n) + i + 1]

    end = time.time()
    sec = (end - start)
    sec = datetime.timedelta(seconds=sec)
    print(sec)

nums = [2,7,11,15] 
target = 9
# nums = [3, 3]
# target = 6
twoSum(nums, target)

 

결과

 

다른 분의 코드

def twoSum_dict(nums, target):
    start = time.time()

    dict = {}
    for i, num in enumerate(nums):
        dict[num] = i

    #타겟에서 첫번째 수를 뺀 결과를 키로 조회
    for i, num in enumerate(nums):
        if target - num in dict and dict[target - num] != i:
            # 걸린시간: 0:00:00.000001
            # 시간복잡도:O(1)
            # print([i, dict[target - num]])
            # return [i, dict[target - num]]

    end = time.time()
    sec = (end - start)
    sec = datetime.timedelta(seconds=sec)
    print(sec)

시간복잡도가 o(1)로 되면서 속도가 엄청 빨라집니다.

 

추가적으로 공부할 부분

- array.index(x) 리스트에서 x의 인덱스 반환
- array.index(x, start) 리스트[start:]에서 x의 인덱스 반환
- array.index(x, start, stop) 리스트[start:stop]에서 x의 인덱스 반환

 

반응형
반응형

파이썬 lambda 사용시

파이썬 lambda 사용할 때 격은 일에 대한 내용입니다.

 

 

 

1. map(lambda x: x> 1, nums)

nums 안에 있는 숫자 값을 조건에 따라 걸러 낼려고 했는데 map()을 사용하면 True, False로 return 하게 됩니다.

숫자로 받을려면 filter() 함수를 사용하면됩니다.

반응형

'Python' 카테고리의 다른 글

File 읽어서 객체에 담기  (0) 2024.09.04
print 하면 <map object at 0x10446d880> 나올 때  (0) 2023.06.01
[python] list 사용 방법  (0) 2023.05.29
zip()  (0) 2023.05.03
combinations()  (0) 2023.05.03
반응형
반응형

문제

vscode 환경에서 파이썬을 가지고 map에 있는 값을 읽을려고 print() 실행 했을 때 <map object at 0x10446d880>이라고 나왔다.

읽을 수 있게 바꿔야 합니다.

 

코드

def twoSum(nums, target):
	# arr map
    arr = map(lambda x: x < target, nums)

nums = [2,7,11,15]
target = 9
twoSum(nums, target)

 

해결

1. for문

for num in arr:
	print(num)

 

2. map을 list로 담기

arr = list(map(lambda x: x < target, nums))
print(arr)

 

 

반응형

'Python' 카테고리의 다른 글

File 읽어서 객체에 담기  (0) 2024.09.04
파이썬 lambda 사용시  (0) 2023.06.01
[python] list 사용 방법  (0) 2023.05.29
zip()  (0) 2023.05.03
combinations()  (0) 2023.05.03
반응형
반응형

list 사용 방법

  • 리스트는 [] 기호를 사용하여 표현
  • L = [i for i in L if i % 3 == 0] 도 가능
  • del(L[2]) - 리스트 특정 인덱스 내용을 삭제
  • del(L) - 리스트 자체를 삭제
  • t = (1, 2, 3, 4, 5)
  • L = list(t) - 튜플(tuple), 집합(set)과 같은 다른 자료형을 리스트로 바꾸기 위해서는 list()를 사용
  • append(값) - 리스트에 값을 하나 추가
  • insert(인덱스, 값) - 인덱스 위치에 값을 하나 추가
  • extend(iterable) - iterable 인자를 넘겨 리스트에 추가
  • copy() - 리스트 복사 (리턴받아 사용)
  • remove(값) - 전달한 값을 삭제 (중복된 경우 처음 나오는 값을 삭제)
  • pop(인덱스) - 인덱스에 위치한 값을 리턴하면서 삭제 (인자가 없으면 맨 뒤 값을 pop)
  • clear() - 리스트 값 모두 삭제 (빈 리스트 생성)
  • count(값) - 인자로 전달한 값의 개수를 확인
  • len() - 리스트의 길이를 확인하기 위해서는  함수를 사용
  • index(인덱스) - 인덱스에 위치한 값을 확인
  • reverse() - 리스트에 들어있는 값을 역순(거꾸로)으로 변경
  • sort() - 리스트 내용을 정렬 (오름차순)(reverse=True를 인자로 전달하면 내림차순 정렬이 가능)
반응형

'Python' 카테고리의 다른 글

파이썬 lambda 사용시  (0) 2023.06.01
print 하면 <map object at 0x10446d880> 나올 때  (0) 2023.06.01
zip()  (0) 2023.05.03
combinations()  (0) 2023.05.03
[panda]info()  (0) 2023.04.26
반응형
반응형

tf.config.set_visible_devices()이란?

tf.config.set_visible_devices(
    devices, device_type=None
)

device는 실제 GPU 장비의 이름이 들어가고, device_type에는 CPU 또는 GPU를 넣습니다.

 

만약 CPU만 사용할려면 device에 빈 리스트를 넣고 device_type에는 GPU를 넣으면 됩니다

예시) tf.config.set_visible_devices([], 'GPU')

 

반응형

'머신러닝 & 딥러닝' 카테고리의 다른 글

Feature space  (0) 2023.05.14
Failed to get CPU frequency: 0 Hz  (0) 2023.05.06
[library] seaborn  (0) 2023.04.28
AUC란?  (0) 2023.04.26
ModuleNotFoundError: No module named ""  (0) 2023.04.25
반응형
반응형

문제

glob()을 통해 파일을 가져올려고 하는데 TypeError: path should be path-like or io.BytesIO, not <class 'list'> 발생했습니다.

 

코드

sign = list(test_path.glob(f'{i}/*'))

 

예상 원인

뒤에 따라오는 from tensorflow.keras.preprocessing.image import load_img 에서 에러가 발생하고 있었습니다.

 

해결

load_img() 함수에 list를 넣어서 발생한거 같아 수정했더니 에러가 발생하지 않았습니다.

 

* load_img()

tf.keras.utils.load_img(
    path,
    grayscale=False,
    color_mode='rgb',
    target_size=None,
    interpolation='nearest',
    keep_aspect_ratio=False
)
반응형
반응형
반응형

zip(*iterables, strict=False)

  • 동일한 개수로 이루어진 iterable한 객체들(iterables)을 인수로 받아 묶어서 iterator로 반환합니다.

예시 코드)

for itemin zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
	print(item)
    
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
반응형

'Python' 카테고리의 다른 글

print 하면 <map object at 0x10446d880> 나올 때  (0) 2023.06.01
[python] list 사용 방법  (0) 2023.05.29
combinations()  (0) 2023.05.03
[panda]info()  (0) 2023.04.26
cannot import name 'fl_score' from 'sklearn.metrics'  (0) 2023.04.26

+ Recent posts