문자열 순열 문제를 코딩하려고합니다. 문자열 대신 [1,2,3]과 같은 정수 목록이 있습니다. 목록의 가능한 모든 순열을 인쇄해야합니다. 그러나 내가 알 수없는 코드에는 몇 가지 문제가 있습니다. 어떻게 든 기본 케이스에있는 if not in words
라인은 한 번만 공격합니다. 나는 지난 1 시간 동안 이것을 알아 내려고 노력하고있다. 어떤 도움을 주시면 감사하겠습니다!. TIA 여기에 버그 당신이 nums
은 그래서 당신은 수정했지만 수정이 기록되지 않은 하나의 사본 결국 동일한 목록을 수정 유지한다는 것입니다 코드배열 순열에 대한 전역 변수에 문자열 순열이 추가되지 않는 이유를 추적 할 수 없습니다.
words = list()
def permute(nums):
if len(nums) == 0:
return None
l = 0
r = len(nums)
permute_helper(nums,0,r)
def permute_helper(nums,start,end):
current = 0
if start == end-1:
if not nums in words:
print 'appended'
words.append(nums)
else:
for current in range(start,end):
temp = nums[start]
nums[start] = nums[current]
nums[current] = temp
#Recursive call
permute_helper(nums,start+1,end)
temp = nums[start]
nums[start] = nums[current]
nums[current] = temp
permute([1,2,3])
print words
itertools 사용 ... –
고마워요. 나는 그것을 –
로 업데이트 할 것이다. 감사. :-) –