직무
공백으로 구분 된 정수 목록을 입력으로 받으면 각 하위 집합의 합계가 0 인이 숫자의 비어 있지 않은 고유 하위 집합을 모두 출력하십시오.
테스트 사례
입력 : 8 −7 5 −3 −2
출력 :-3 -2 5
승리 기준
이것은 code-golf 이므로 바이트 단위의 가장 짧은 코드가 이깁니다!
공백으로 구분 된 정수 목록을 입력으로 받으면 각 하위 집합의 합계가 0 인이 숫자의 비어 있지 않은 고유 하위 집합을 모두 출력하십시오.
입력 : 8 −7 5 −3 −2
출력 :-3 -2 5
이것은 code-golf 이므로 바이트 단위의 가장 짧은 코드가 이깁니다!
답변:
{⊇.+0∧}ᵘb
{⊇.+0∧}ᵘb
⊇ subset
+0 that sums to 0
. ∧ output the subset
{ }ᵘ take all unique solutions
b except the first (which is the empty solution)
itertools.permutations
그런 긴 이름을 가진 당신을 젠장 !
무차별 대입 솔루션. 나는 그것이 가장 짧지 않다는 것에 놀랐다. 그러나 나는 itertools
해결책을 망칠 것 같다 .
언 골프 드 :
import itertools
initial_set=map(int, input().split())
ans=[]
for length in range(1, len(x)+1):
for subset in itertools.permutations(initial_set, length):
if sum(subset)==0:
ans+=str(sorted(subset))
print set(ans)
골프 (추악한 출력) :
from itertools import*
x=map(int,input().split())
print set(`sorted(j)`for a in range(1,len(x)+1)for j in permutations(x,a)if sum(j)==0)
골프 (예쁜 결과) (183) :
from itertools import*
x=map(int,input().split())
print `set(`sorted(j)`[1:-1]for a in range(1,len(x)+1)for j in permutations(x,a)if sum(j)==0)`[5:-2].replace("'","\n").replace(",","")
import itertools as i
: itertools 모듈 가져 오기 및 호출 i
x=map(int,input().split())
: 입력을 공백으로 분리 한 다음 결과 목록의 항목을 정수 ( 2 3 -5
->[2, 3, -5]
)
세트 ( sorted(j)
i.permutations J에 대한 범위 (1, 렌 (X) +1) (X, a) 만약 합 (j) == 0)
에서 모든 부분 집합의 반환을리스트는 x
여기서 합 분류 0이면 고유 항목 만 가져옵니다
( set(...)
)
주변의 무덤 (`) sorted(j)
은 Python의 약자입니다 repr(sorted(j))
. 이것이 여기에있는 이유는 파이썬의 세트가리스트를 처리 할 수 없기 때문에 다음으로 가장 좋은 것은리스트가있는 문자열을 텍스트로 사용하는 것입니다.
split()
문자열 목록을 만들지 만 나중에 sum
해당 분할의 하위 집합을 호출 합니다.
from itertools import*
repr()
좋아, C #의 함수형 프로그래밍은 그렇게 짧지 않지만 나는 그것을 좋아 한다! (무차별 열거 만 사용하면 아무 효과가 없습니다.)
using System;using System.Linq;class C{static void Main(){var d=Console.ReadLine().Split(' ').Select(s=>Int32.Parse(s)).ToArray();foreach(var s in Enumerable.Range(1,(1<<d.Length)-1).Select(p=>Enumerable.Range(0,d.Length).Where(i=>(p&1<<i)!=0)).Where(p=>d.Where((x,i)=>p.Contains(i)).Sum()==0).Select(p=>String.Join(" ",p.Select(i=>d[i].ToString()).ToArray())))Console.WriteLine(s);}}
가독성을 높이기 위해 형식화 및 주석 처리 :
using System;
using System.Linq;
class C
{
static void Main()
{
// read the data from stdin, split by spaces, and convert to integers, nothing fancy
var d = Console.ReadLine().Split(' ').Select(s => Int32.Parse(s)).ToArray();
// loop through all solutions generated by the following LINQ expression
foreach (var s in
// first, generate all possible subsets; well, first just their numbers
Enumerable.Range(1, (1 << d.Length) - 1)
// convert the numbers to the real subsets of the indices in the original data (using the number as a bit mask)
.Select(p => Enumerable.Range(0, d.Length).Where(i => (p & 1 << i) != 0))
// and now filter those subsets only to those which sum to zero
.Where(p => d.Where((x, i) => p.Contains(i)).Sum() == 0)
// we have the list of solutions here! just convert them to space-delimited strings
.Select(p => String.Join(" ", p.Select(i => d[i].ToString()).ToArray()))
)
// and print them!
Console.WriteLine(s);
}
}
이 버전은 술어에서 용어에 대한 적절한 바인딩을 찾으려고 시도하지 않고 목록을 인쇄합니다.
s([],O):-O=[_|_],sum_list(O,0),print(O).
s([H|T],P):-s(T,[H|P]).
s([_|T],O):-s(T,O).
s([8,-7,5,-3,-2,4],[]).
레코드의 경우, 술어를 만족시키기위한 바인딩을 찾는 버전입니다.
s(L,O):-s(L,0,O),O=[_|_].
s([],0,[]).
s([H|T],S,[H|P]):-R is H+S,s(T,R,P).
s([_|T],S,O):-s(T,S,O).
s([8,-7,5,-3,-2,4],O).
이전 버전에는 빈 세트를 제거하지 못한 불완전한 솔루션이 포함되어 있습니다.
ŒPḊSÐḟ
완전성을 위해. Brachylog와 마찬가지로 Jelly도 도전 과제를 발표하지만 새로운 언어는 정상적으로 경쟁합니다.
ŒP Power set.
Ḋ Dequeue, remove the first element (empty set).
Ðḟ Filter out the subsets with truthy (nonzero)...
S sum.
>a:-.~(#:@i.@(2&^)@#<@":@(#~0=+/)@#"1 _])".1!:1[1
용법:
>a:-.~(#:@i.@(2&^)@#<@":@(#~0=+/)@#"1 _])".1!:1[1
8 _7 5 _3 _2 4
5 _3 _2
_7 5 _2 4
8 _7 _3 _2 4
(<@":@(#~0=+/)@#"1 _~2#:@i.@^#)
하면 4자를 절약 할 수 있습니다.
â±3╒yΣ╓à
압축을 푼 버전 (9 바이트)을 사용하여 설명합니다.
LS{|+!fmJ
L Convert to list
S Powerset
{ f Filter with block
|+! Sum is zero
mJ Print each subset, joined by spaces
Given a list of space-delimited integers as input
; 그러나 목록을 입력으로 사용하고 있습니다.
(a:-.~](<@#~0=+/)@#~[:#:@i.2^#)@".
".
입력을 목록으로 변환합니다. 그때:
a: -.~ ] (<@#~ (0 = +/))@#~ [: #:@i. 2 ^ #
i. NB. ints from 0 to...
2 ^ # NB. 2 to the input len
[: #:@ NB. converted to binary masks
] ( ) #~ NB. filter the input using
NB. using those masks, giving
NB. us all subsets
( )@ NB. and to each one...
( #~ (0 = +/)) NB. return it if its sum is
NB. 0, otherwise make it
NB. the empty list.
(<@ ) NB. and box the result.
NB. now we have our answers
NB. and a bunch of empty
NB. boxes, or aces (a:).
a: -.~ NB. remove the aces.
*.words.combinations.skip.grep(!*.sum)>>.Bag.unique
합계가 0 인 고유 백 목록을 리턴합니다. 백은 가중치 세트입니다.
*.words # Split by whitespace
.combinations # Get the powerset
.skip # Skip the empty list
.grep(!*.sum) # Select the ones that sum to 0
>>.Bag # Map each to a weighted Set
.unique # And get the unique sets
a=gets.split.map &:to_i;b=[];(1...a.length).each{|c|a.permutation(c){|d|d.sum==0?b<<d:0}};p b.map(&:sort).uniq
나중에 TIO 링크를 추가합니다.
stdin에서 입력을 숫자 목록으로 가져옵니다. 예 : 8 −7 5 −3 −2
작동 방식 : 입력을 숫자 배열로 변환합니다. 1에서 배열 길이까지의 길이 순열을 모두 가져옵니다. 합계가 0이면 출력 배열에 추가합니다. 중복없이 배열을 출력합니다.
샘플 입력에 대한 출력 : [[-3, -2, 5]]
3 3 -3 -3
합니까?