모델 폼(forms.ModelForm) : 연결된 모델의 데이터를 저장. Meta 클래스가 필요.
form.py 생성하기
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
# Product 모델과 연결
model = Product
fields = ['product_name', 'price', 'desc']
views.py
def product_create(request):
if request.method == 'GET':
form = ProductForm()
return render(request, 'mall.html', {'form': form})
elif request.method == 'POST':
form = ProductForm(request.POST)
# 유효성 검사에 실패하면 다시 상품등록 페이지로 이동
if form.is_valid():
# 임시저장
product = form.save(commit=False)
product.user = request.user
product.save()
return redirect('/')
def solution(lines):
dp_list = [] # 겹치는 부분을 저장할 리스트
for i in range(len(lines)): # lines의 인덱스
for j in range(i+1, len(lines)): # j가 i의 다음값
# lines[0][1] lines[1][0]
# 첫 선분의 end >= 두번째 선분의 start
# 첫 선분의 시작이 두 번째 선분의 끝보다는 클 때
# 두 선분이 겹치는 경우
if lines[i][1] >= lines[j][0] and lines[i][0] <= lines[j][1]:
dp_list_start = max(lines[i][0], lines[j][0])
dp_list_end = min(lines[i][1], lines[j][1])
# 중복 계산 방지 및 중첩되는 부분 제거
# 빈 값 = dp_list
for start, end in dp_list:
# 앞의 선분을 완전히 덮을 때
if dp_list_start <= end and dp_list_end >= start:
dp_list_start = min(dp_list_start, start)
dp_list_end = max(dp_list_end, end)
dp_list.remove((start, end))
dp_list.append((dp_list_start, dp_list_end))
# 겹치는 부분들의 길이 합산
total_length = sum([end - start for start, end in dp_list])
return total_length
시도해 본 것 1
2번 리스트 시작점이 1번 리스트 안에 들어갔냐를 확인(=)
2번 리스트 시작점을 기준으로 1번 끝나는 점까지가 겹치는 선분의 길이
3번 리스트 시작점이 2번 리스트 안에 있나 확인
3번 리스트 시작점을 기준으로 2번 끝나는 점까지가 겹치는 선분의 길이
ef solution(lines):
dp_list = []
count = 0
for idx, line in enumerate(lines):
if idx+1 < len(lines):
for i in range(line[0], line[1]+1):
if lines[idx+1][0] <= i:
dp_list.append(i)
# 1번째 마지막 겹치는 값이 있을 때
if lines[2][0] in range(lines[0][0], lines[0][1]+1):
# 있다면 3 start ~ 1 end 까지가 길인데
for l in range(lines[0][0], lines[0][1]+1):
if lines[2][0] <= l:
dp_list.append(l)
# 연속된 수라서 중복제거함
dp_list = list(set(dp_list))
# 선분의 길이를 count로 구함
for i, dp in enumerate(dp_list):
if i+1 < len(dp_list):
if dp_list[i+1] - dp == 1:
count += 1
return count
문제점 : 3번째 선분이 가장 길거라는 보장이 없음. 순서가 섞이면 예외처리 못 함.
시도해 본 것 2
중복 리스트를 만들어 다음 인덱스 값이랑 차이가 1 나면 count 함
def solution(lines):
# range로 lines 안의 요소를 모두 돌림
# 중복되는 숫자를 가져오기
num_list = []
num_list2 = []
num_list3 = []
count = 0
for a, b in lines:
for x in range(a, b+1):
num_list.append(x)
for i in num_list:
if i not in num_list2:
num_list2.append(i)
else:
if i not in num_list3:
num_list3.append(i)
# 다음 수가 전 수 보다 1 차이나면 count
for i, a in enumerate(num_list3):
if i+1 < len(num_list3):
if num_list3[i+1] - a == 1:
count += 1
return num_list