리스트에 map 사용하기

  • map은 리스트의 요소를 지정된 함수로 처리해주는 함수 (원본 리스트를 변경하지 않고, 새 리스트를 생성)
    • list(map(함수, 리스트))
    • tuple(map(함수, 튜플))
  • 어떤 타입으로 변환해서 저장할 때, 매번 for문으로 반복하지 않고도, map을 사용해서 변환 가능
a=[1,2,3,4,5]
a=list(map(int,a))
  • 0-9까지의 숫자를 str으로 변환해서 리스트에 저장 가능
a = list(map(str, range(10))
a
['0',...,'9']
  • input().split()과 map
    • 원래는 문자열로 받아지지만, map을 통해 int로 변환해서 list로 바꿀 수 있다.
a=map(int,input().split())
list(a)
[10,20]
  • map이 반환하는 map객체는 iterator라서 변수 여러 개에 저장하는 unpacking이 가능함.
    • a,b=map(int, input().split())처럼 list를 생력한 것
a,b=[10,20]
a
10
b
20
 

파이썬 코딩 도장: 22.6 리스트에 map 사용하기

이번에는 리스트에 map을 사용해보겠습니다. map은 리스트의 요소를 지정된 함수로 처리해주는 함수입니다(map은 원본 리스트를 변경하지 않고 새 리스트를 생성합니다). list(map(함수, 리스트)) tupl

dojang.io

 

'Language > python' 카테고리의 다른 글

[python] Set과 List 사용하기 & 변환하기  (0) 2020.11.12

WRITTEN BY
choco-songyi

,

코딩테스트 문제를 풀다보니, set과 list를 변환할 때가 종종 있었다!

그래서 한 번 짚고 넘어가는 게 좋을 것 같다는 생각이 들었다:)

List

기본 문법

  • 리스트는 c의 배열과 비슷한 기능을 한다! (c++ STL의 vector와 유사하다.)

  • 연결 리스트 자료구조를 채택하고 있어서 append()와 remove()를 지원한다.

list1=[] # 리스트
list1=['first','list'] # 리스트 생성과 동시에 초기화
list1.append('hello') # 원소 추가
list1.insert(1,'bye') # 해당 인덱스에 원소 추가
list1.remove('hello') # 해당 원소 제거
list1.count('bye') # 해당 원소 갯수 계수
list1.sort() # 오름차순 정렬
list1.sort(reverse=True) # 내림차순 정렬

Set

기본 문법

  • 집합 연산자 set은 중복을 허용하지 않고, 순서가 없다. (indexing이 불가하다.)

s=set()
s1=set([1,2,3,4]) # list를 넣어서 초기화
s2={}
s3={1,2,3,4} # 괄호를 사용해서 초기화

s1.add(5) # 원소 추가
s1.update([6,7]) # 여러 개의 원소 한번에 추가
s1.remove(7) # 해당 원소 삭제 

s1-s3 # 차집합
s1|s3 # 합집합
s1&s3 # 교집합

Set into a List

  • list(set_name) 사용하기

my_set = {1,2,3}
my_list = list(my_set)
  • sorted(set_name) 메소드 사용하기

my_list = sorted(my_set)

List into a Set

  • 선언해줄 때의 방식으로 대입해주면 된다!

    • set(list_name)

list1=[1,2,3,4]
s=set(list1)

'Language > python' 카테고리의 다른 글

[python] 리스트에 map 사용하기  (0) 2020.11.12

WRITTEN BY
choco-songyi

,

문제 출처 : 프로그래머스 - programmers.co.kr/learn/courses/30/lessons/42839

 

코딩테스트 연습 - 소수 찾기

한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다. 각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이

programmers.co.kr

문제 설명

한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.

각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.

제한사항

  • numbers는 길이 1 이상 7 이하인 문자열입니다.

  • numbers는 0~9까지 숫자만으로 이루어져 있습니다.

  • 013은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.

입출력 예

numbers return
17 3
011 2

입출력 예 설명

  • 예제 #1

    [1, 7]으로는 소수 [7, 17, 71]를 만들 수 있습니다.

  • 예제 #2

    [0, 1, 1]으로는 소수 [11, 101]를 만들 수 있습니다.

  • 11과 011은 같은 숫자로 취급합니다.


코드 풀이

접근방식

1. 순열조합 라이브러리를 이용해서 경우의 수를 구하기

  • nPm : n개의 숫자를 m개로 순열!(순서 상관 있는 것= 순열)

  • 현재 필요한 순열 : nP1, nP2, ....nPn 까지 모두

    • 그래서 all_numbers list에 append해줌.

  • 코드 :

all_numbers.append(list(permutation({해당 리스트이름},m))
  • 출력 결과 : [[('1',), ('1',), ('0',)], [('1', '1'), ('1', '0'), ('1', '1'), ('1', '0'), ('0', '1'), ('0', '1')], [('1', '1', '0'), ('1', '0', '1'), ('1', '1', '0'), ('1', '0', '1'), ('0', '1', '1'), ('0', '1', '1')]]

 

2. 각 순열마다 문자열로 바꾸어주어서 int 정수형으로 저장해주기

  • 이 때, 중복되는 부분을 제거해주기 위해 set 집합 자료형을 이용해줌.

  • 3중 for문 -> 완전 탐색 하는 부분

  • 출력 결과 : [0, 1, 10, 11, 101, 110]

 

3. 집합자료형 set 을 list로 바꿔주기

  • set은 인덱싱이 불가하여 각 원소마다의 접근이 어렵기 때문에 list로 바꾸어주어야 한다.

  • 방법 : sorted(set이름) 사용함. (더 많은 방법은 아래 link 참고)

{list이름}=sorted({set이름})

 

4. 소수인지를 판별해준다.

  • math 라이브러리의 제곱근 math.sqrt(n) 을 이용해서 반복 횟수를 줄여준다. !!

  • 나머지가 0 : 즉 나누어 떨어진다면, point 변수를 통해 계수에서 제외한다.

from itertools import permutations
import math


def solution(numbers):
    answer = 0
    all_numbers = []
    # numbers 길이만큼 순열 구하기! 1<=n<=len(numbers)
    for n in range(1, len(numbers) + 1):
        all_numbers.append(list(permutations(numbers, n)))

    # list를 문자열로 바꾸어서 집합 set()에 넣기 (중복 x)
    set_numbers=set()
    for i in range(len(all_numbers)):
        for j in range(len(all_numbers[i])):
            temp='' # 각 순열 별로 문자열로 만들어주기
            for k in range(len(all_numbers[i][j])):
                temp = temp + all_numbers[i][j][k]
            # 저장한 문자열을 int형으로 set에 넣어주기 (0이 앞에 나오는 것 제거해줌)
            set_numbers.add(int(temp))

    # 소수 판별 및 count!
    # 인덱싱을 위해 set 데이터를 list로 옮겨주기
    last_list = sorted(set_numbers)
    # print(last_list)
    for n in last_list:
        if n==2:
            answer=answer+1
        elif n>2:
            point = True
            for i in range(2,int(math.sqrt(n))+1):
                if n%i==0:
                    point=False
                    break
            if point==True:
                answer=answer+1
    return answer

print(solution("17"))

결과

- 참고 :www.geeksforgeeks.org/python-convert-set-into-a-list/

 

Python | Convert set into a list - 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

 


WRITTEN BY
choco-songyi

,

티스토리의 스킨을 바꾸는 것은 재미있다....

(사실 보기 좋은 블로그에 더 눈이 잘 가게 되어있기 때문에 바꿔주고 싶은 마음이 든다...)

 

하지만, 기존 스킨의 배경 이미지를 내가 원하는 것으로 바꿔주고 싶다!

간단하지만, 처음에는 헤맸기 때문에 한 번 기록해보기로 한다!

 

1. 먼저 블로그 편집 - 스킨 편집에 들어간다.

 

 

2. 그리고 원하는 배경 이미지로 파일을 업로드 해준다!

 

 

 

3. css에 들어가서 업로드한 background url에 업로드한 파일의 url 명으로 바꾸어준다. 

 

4. 새로고침을 해서 변경된 배경 이미지를 확인한다.!

 


WRITTEN BY
choco-songyi

,

Pycharm 에서 commit을 하는데, git 계정이 두 개여서 다른 user로 바꾸고 싶었다..!

 

 

 

다른 계정으로 commit을 하니까 메인 계정에서 git contribution에 반영되지 않았기 때문!!! 실제 한 달 간 django project를 하면서 commit을 굉장히 많이 했는데 하나도 반영이 안됐다! ㅜㅜ

 

방법

pycharm 터미널에서 간단한 명령어를 통해 해결할 수 있었다!

(venv) git config user.name
[현재 유저이름]
(venv) git config user.email
[현재 이메일주소]
(venv) git config --local user.email [바꾸고 싶은 이메일 주소]

 

나의 경우에는 ... 이메일 주소만 바꾸니 원하는 계정 정보로 이용할 수 있었다! (알고보니, 이메일 주소를 바꿔서 다른 계정으로 연결되었던 것... 같다...ㅎ) 

 

'Git > 개인' 카테고리의 다른 글

[Git 관리] commit 취소하기  (0) 2020.11.02
[Git 관리] Git 이전 commit으로 돌아가는 방법  (0) 2020.10.29

WRITTEN BY
choco-songyi

,

1. Model (user)

- 기존 user에서 필드를 추가해주고 싶어서 AbstractUser를 상속해주었다!

  - 단, settings에서 따로 설정해줄 것 :

# 커스텀 유저 모델을 생성하기 위한 셋팅
AUTH_USER_MODEL = 'member.User'

- 처음에 추가한 필드 : 소개, 프로필 사진, 전화번호, 생일, 웹사이트

- 이후 기능구현을 위해 추가한 필드 : 팔로워, 사진 갯수

  - followers : 팔로우 기능을 구현하기 위해 ManyToManyField를 이용함.

from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models

# User : 기본 user를 상속하여 추가 field로 구성
# cf. blank=True :빈 채로 저장 & null=True : null 값으로 저장


class User(AbstractUser):

    bio = models.TextField(null=True, blank=True) # 소개
    photo = models.ImageField(upload_to='user/%Y/%m/%d', null=True, blank=True) # 프로필 사진
    phone_number = models.CharField(null= True, blank=True, max_length=20) # 전화번호
    date_of_birth = models.DateField(null=True, blank=True) # 생일
    website = models.CharField(null=True, blank=True, max_length=100) # 웹사이트
    followers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followings') # follow 기능을 위해 추가함.
    # ManyToManyField -> related_name : 정참조하고 있는 클래스의 인스턴스에서 거꾸로 호출(역참조 할지를 정해주는 이름)
    photo_cnt = models.IntegerField(default=0)

2. URLs

- view와 template을 이어주는 역할!

from django.conf.urls import url
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url('join/', views.create_user, name="join"),
    url('login/', views.sign_in, name="login"),
    url('logout/', views.sign_out, name='logout'),
    url('delete/',views.delete, name='delete'),
    url('change_password/',views.change_password,name='change_password'),
    url('profile_update/',views.profile_update, name='profile_update'),
    path('people/<str:username>/', views.peoplePage , name="people"),
    path('follow/<str:username>/',views.follow, name='follow'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

3. View

- 각 함수마다 기능 해당하는 url의 기능 수행

# 절대 경로 설정을 위해 추가
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from photo.models import Photo

from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash, get_user_model
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.views.generic import ListView
from rest_framework.generics import get_object_or_404

from .forms import UserCreationForm, ProfileForm
from .models import User

def change_password(request):
    if request.method == "POST":
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, '패스워드가 성공적으로 업데이트 되었습니다.')
            return redirect('index') # 다음 url로 이동한다.
        else:
            messages.error(request,"다음 에러를 확인해주세요.")
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'registration/change_password.html',{'form':form})

# 계정 삭제 기능
def delete(request):
    if request.method == "POST":
        request.user.delete()
        return redirect('index')
    else:
        return render(request, 'registration/delete.html')



# New User Registration(회원가입 기능)
def create_user(request):
    if request.method == 'POST':
        try:
            username = request.POST['username']
            email = request.POST['email']
            password = request.POST['password1']
            new_user = User.objects.create_user(username, email, password)
            new_user.save()
            return render(request, 'registration/signup_done.html', {'message': '회원가입이 완료되었습니다.'})
        except:
            return render(request, 'registration/signup_done.html', {'message': '회원이 이미 있음'})
    else:
        form = UserCreationForm()
        return render(request, 'registration/signup.html', {'form': form})


# 로그아웃 기능
def sign_out(request):
    logout(request)
    return render(request, 'home/base.html')

# 로그인 기능
def sign_in(request):
    if request.method == 'POST':
        # 유저 (username, password)로 인증
        user = authenticate(request, username=request.POST.get('username', ''),
                            password=request.POST.get('password', ''))
        if user is not None:
            login(request, user) 
            return render(request, 'registration/signup_done.html', {'message': "로그인 되었습니다."})
        else:
            return render(request, 'registration/signup_done.html', {'message': "로그인에 실패하였습니다."})
    else:
        # 로그인 폼 생성
        form = AuthenticationForm()
        return render(request, 'registration/login.html', {'form': form})
        
# profile update
def profile_update(request):
    user = request.user
    if request.method == 'POST':
        profile_form = ProfileForm(request.POST, request.FILES, instance=user)
        if profile_form.is_valid(): # 단, form이 valid하지 않으면 저장되지 않는다. (예) 생일의 형식이 안맞을 때
            profile_form.save()
        return redirect('people', request.user.username)
    else:
        profile_form = ProfileForm(instance=user)
    return render(request, 'profile/profile_update.html', {'profile_form': profile_form})



# 게시물의 작성자의 username을 통해 user 페이지에 접근하기
def peoplePage(request,username):
    person = get_object_or_404(User, username=username)
    # 작성자가 username인 photo를 전달하기
    photo_list = Photo.objects.filter(Q(user=person))
    context={}
    context['people']=person
    context['object_list']= photo_list

    return render(request, "profile/people.html",context)

# 팔로우 기능 
def follow(request, username):
    people = get_object_or_404(get_user_model(), username=username)
    if request.user in people.followers.all():
        # people을 unfollow하기
        people.followers.remove(request.user)
    else:
        # people을 follow하기
        people.followers.add(request.user)
    return render(request, "profile/people.html",{'people': people})


WRITTEN BY
choco-songyi

,

방법 두가지

- git reset

  - git reset --hard ...

  - git reset --soft ...

- git revert

 

상태& 하고 싶었던 것 

- 커밋했지만, 아직 push하지 않았음.

- 이전 커밋을 취소하고 리드미를 변경하여 커밋하고 싶음.

 

선택한 방법 

- git reset --soft HEAD~1

 

참고

gitabout.com/8

 

Git commit 되돌리기 명령어 Reset 과 Revert

Git 커밋(commit) 이력 되돌리기 이미 커밋(commit)된 작업 이력을 이전으로 되돌려야 하는 상황은 항상 발생합니다. 작업중에 실수로 올라간 커밋일 수 도 있고 버그나 오류가 포함된 커밋 일수도 있

gitabout.com

 

'Git > 개인' 카테고리의 다른 글

[Git 관리] user 변경하기  (0) 2020.11.10
[Git 관리] Git 이전 commit으로 돌아가는 방법  (0) 2020.10.29

WRITTEN BY
choco-songyi

,

 

[오류1]

Please commit your changes or stash them before you merge.
Aborting

[해결1]

git stash (local에서 하던 것을 잠시 미뤄두기)

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>git stash
Saved working directory and index state WIP on master: 6edaaf5 UpdateForm 조금 변경 !

 다시 pull을 해보자!


[오류2]

warning: Cannot merge binary files: db.sqlite3 (HEAD vs. eb7f395a92448ac8dddd762c0c997093207cc88d)
Auto-merging member/forms.py
CONFLICT (content): Merge conflict in member/forms.py
Auto-merging db.sqlite3
CONFLICT (content): Merge conflict in db.sqlite3
Automatic merge failed; fix conflicts and then commit the result.

[해결2]

DB를 지워보자!


[오류3]

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>git pull
error: Pulling is not possible because you have unmerged files.
hint: Fix them up in the work tree, and then use 'git add/rm <file>'
hint: as appropriate to mark resolution and make a commit.
fatal: Exiting because of an unresolved conflict.

[해결3] 

1. git status 를 통해 unmerged path를 확인한다.

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:   member/forms.py

2. git add 파일명

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>git add member/forms.py

3. git commit am "커밋메시지"

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>git commit -am "am commit"
[master 2876f19] am commit

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>git pull
Already up to date.

[결과]

pull 성공 :)

 

 

 

[결론]

git 오류날때 오류 메시지 구글링해서 시키는 대로 해보자! ...ㅎㅎ

 

[참고]

ayong8.tistory.com/entry/git-stash-%EC%A7%81%EA%B4%80%EC%A0%81%EC%9C%BC%EB%A1%9C-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0

 

git stash: 직관적으로 이해하기

git stash의 직관적 이해 직관적 이해 기본적으로 git stash는 현재 업데이트된 내용을 스택에 치워두는 명령어다 내 로컬의 modified, staged contents들을 (=나의 변경사항을) 스택구조 (한켠에 설정되어

ayong8.tistory.com

jmlim.github.io/git/2019/02/18/git-pull-fail-problem/

 

git merge 후 pull 실패 시 해결 방안 - You have not concluded your merge (MERGE_HEAD exists) · 기억하기 위한 개

커밋을 제대로 하지 않았을 경우 아래 메세지가 뜰 수 있음. Pulling is not possible because you have unmerged files

jmlim.github.io

 


WRITTEN BY
choco-songyi

,

1. git checkout HEAD~{n번째 전}

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>git checkout HEAD~1
Note: checking out 'HEAD~1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 5ba51da little change
M       api/__pycache__/__init__.cpython-38.pyc
M       api/__pycache__/urls.cpython-38.pyc
# ...생략...

- 결과 : HEAD가 바로 이전 커밋으로 돌아갔음. 

- 확인 : 이전 커밋 해시번호 (5ba51da5)로 돌아갔음

2. 체크아웃했더니 서버로부터의 pull이 또 실패...ㅎㅎ => master로 다시 돌아오자...

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>git checkout master
Previous HEAD position was 5ba51da little change
Switched to branch 'master'
# ---생략----

Your branch and 'origin/master' have diverged,
and have 1 and 5 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

 

'Git > 개인' 카테고리의 다른 글

[Git 관리] user 변경하기  (0) 2020.11.10
[Git 관리] commit 취소하기  (0) 2020.11.02

WRITTEN BY
choco-songyi

,

유저의 종류가 다양한데, 어떤 것을 사용해야 할지 고민이 되어서 찾아보았다!

- abstractUser는 장고의 내장 인증 기능을 이용하되, 특정 속성을 추가하고 싶을 때 사용한다! 

 

Conclusions

Alright! We’ve gone through four different ways to extend the existing User Model. I tried to give you as much details as possible. As I said before, there is no best solution. It will really depend on what you need to achieve. Keep it simple and choose wisely.

  • Proxy Model: You are happy with everything Django User provide and don’t need to store extra information.
  • User Profile: You are happy with the way Django handles the auth and need to add some non-auth related attributes to the User.
  • Custom User Model from AbstractBaseUser: The way Django handles auth doesn’t fit your project.
  • Custom User Model from AbstractUser: The way Django handles auth is a perfect fit for your project but still you want to add extra attributes without having to create a separate Model.

simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

 

How to Extend Django User Model

The Django’s built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot ofdevelopment and testing effort. It fits ...

simpleisbetterthancomplex.com

 


WRITTEN BY
choco-songyi

,