문제 설명

문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요.
s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로 간주합니다.

제한 사항

  • str은 길이 1 이상인 문자열입니다.

입출력 예

s return
Zbcdefg gfedcbZ

코드 풀이

접근방식

  • 큰것부터 정렬하기 때문에 reverse=True인 sorted를 사용하자.

기본개념

  • 문자열 -> 리스트로 : list({문자열}
  • 리스트 -> 문자열로 : "".join({리스트})
def solution(s):
    return "".join(sorted(list(s),reverse=True))

- 참고 : list1.sort() 적용 x, sorted(list1) ok


WRITTEN BY
choco-songyi

,

문제 설명

0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요.

예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 수는 6210입니다.

0 또는 양의 정수가 담긴 배열 numbers가 매개변수로 주어질 때, 순서를 재배치하여 만들 수 있는 가장 큰 수를 문자열로 바꾸어 return 하도록 solution 함수를 작성해주세요.

제한 사항

  • numbers의 길이는 1 이상 100,000 이하입니다.

  • numbers의 원소는 0 이상 1,000 이하입니다.

  • 정답이 너무 클 수 있으니 문자열로 바꾸어 return 합니다.

입출력 예

numbers  return
[6, 10, 2] 6210
[3, 30, 34, 5, 9] 9534330

코드 분석

처음 시도

  • permutation을 사용해서 모든 경우의 수를 구했다.
  • 결과: sample은 ok, test case는 전부 시간 초과가 나왔다..!
# 주어진 numbers에서 정수를 이어붙여서 만들 수 있는 가장 큰 수를 찾는다.
# 정수를 붙이는 순열 이용 => 그 중 가장 큰 수 찾기
from itertools import permutations


def solution(numbers):
    answer_list = []
    all_list=list(permutations(numbers,len(numbers)))
    for i in range(len(all_list)):
        temp=""
        for j in range(len(all_list[i])):
            temp = temp +str(all_list[i][j])
        answer_list.append(temp)
    print(answer_list)
    answer=max(answer_list)
    return answer

수정한 코드

point

  • 문자열끼리 비교했다.
    • ASCII문자열로 비교가 되어서 앞에서부터 큰 수로 정렬이 가능하다.
    • map(str, {리스트})를 통해 형변환
  • sorted로 정렬해줄 때, key값에 lambda 함수를 이용해서 세 자리의 값을 모두 비교해주어서 정렬했다.
    • 내림차순으로 정렬하기 때문에 reverse=True를 해준다.
  • "".join(array)를 이용해서 문자열을 합쳐주었다.
# permutation 모든 경우의 수를 구하려고 하니 시간 초과 오류가 났다.
# 다른 방식으로 접근하는 것이 필요하다.

# 문자열을 내림차순으로 정렬한 다음, join 해주는 방식이다!
# 주의 : 처음에는 문자열로 비교할 것 !!(가장 큰 자릿수부터 비교 가능)


def solution(numbers):
    # 정수 type을 문자열 type으로 변경해주기 (map을 통한 형변환!)
    arr = list(map(str, numbers))

    # 문자열 크기대로 sorting하기
    # lambda : 1000이하의 정수이므로, x를 세 번 곱해주어 비교한다.
    array=sorted(arr, key=lambda x:x*3, reverse=True)

    # join으로 각각의 문자열들을 빈틈없이 붙여주기
    # int로 바꾸어주고, 다시 str으로 바꿔주기
    return str(int("".join(array)))

결과


WRITTEN BY
choco-songyi

,

리스트에 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

,

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

,

왜? db를 확인하고 싶어서 localhost:8080/admin으로 접속했는데 계정 정보를 모름!

1. django shell에 들어가서 계정 정보를 확인한다.

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py shell
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> superusers = User.objects.filter(is_superuser=True)
>>> superusers
<QuerySet [<User: kho903>]>
>>>

 

2. 패스워드를 바꾸어준다.

- 너무 쉬우면 계속 다시 하라고 함.

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py changepassword kho903
Changing password for user 'kho903'
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Password:
Password (again):
Password changed successfully for user 'kho903'

3. localhost:8000/admin/auth/user에서 확인해보기

- /admin 에서 로그인

 

 

- test로 회원가입한 user 두 명이 있는 것을 확인할 수 있음.

 

*** 새로 superuser 계정을 만들어줄 수도 있음.

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py createsuperuser
Username (leave blank to use 'user'): mink
Email address:
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

WRITTEN BY
choco-songyi

,

1. pycharm 에서 new project를 만들어준다.

2. Alt+F12 (단축키)로 파이참 터미널을 열어서 장고 프로젝트를 생성한다.

django-admin startproject (프로젝트명)
  • 'django-admin'은 내부 또는 외부 명령, 실행할 수 있는 프로그램 또는 배치 파일이 아닙니다.' 가 뜨게 되면, django를 다시 설치해서 똑같은 명령어를 입력한다.
  • 그러면 다음과 같은 디렉토리가 생성된다. 

- __init__.py : 아무것도 들어있지 않은 빈 파일, 파이썬에게 현재 폴더가 파이썬 파일임을 알려준다.

- settings.py : 장고 프로젝트의 셋팅과 설정이 포함된 파일 

- urls.py : 장고 프로젝트 안의 URL을 선언하는 곳 

- wsgi.py : WSGI 프로토콜을 사용하는 웹서버가 프로젝트의 페이지를 보여주기 위해 먼저 사용하는 파일 

 

 

 

 

 

 

 

 

3. Django App 만들기

cd {프로젝트명}
django-admin startapp {앱이름}

4. 서버 구동하기

python manage.py runserver

- 결과 : 

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 22, 2020 - 15:46:15
Django version 3.1.2, using settings 'insta.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

- 고치기

python manage.py makemigrations
python manage.py migrate

- 결과 :

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

- 다시 실행해도 오류 발생!

(venv) C:\Users\user\PycharmProjects\DjangoTest\insta>python manag
e.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
October 22, 2020 - 15:47:51
Django version 3.1.2, using settings 'insta.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:

- Why? 데이터베이스 호환 문제로 나중에 연결해서 해결할 것

 

참고 : https://7stocks.tistory.com/58

 

Windows + Pycharm + Django 설치부터 시작까지

서비스하기 전까지는 Linux가 아닌 Windows 또는 Mac 환경에서 작업하는 것이 편하다. 여기서는 윈도우에서 편하게 개발하기 위한 Back-End 환경을 조성하는 방법을 알아보자. * 개발 환경 OS: Windows 10

7stocks.tistory.com

 


WRITTEN BY
choco-songyi

,

Windows8 에서 Django 프레임워크를 설치하기 위해서

1. python 을 설치한다.

- 라이브러리들을 사용할 수 있는 Anaconda를 설치한다.

 

2. Anaconda powershell propmt에서 Django를 설치한다.

pip install Django

- 버전이 안맞아서 중간에 설치 오류가 나기 때문에 python 버전을 업그레이드 해준다.

python -m pip install --upgrade pip

- Restful 웹을 만들기 위해 rest-framework도 함께 설치해준다.

 pip install django-rest-framework

 


WRITTEN BY
choco-songyi

,