Python 重新排列数组,使相邻的两个元素不相同
假设您有一个字符列表。数组中字符的排列方式应确保两个相邻元素不相同 约束条件 字符数~10^6 示例输入-Python 重新排列数组,使相邻的两个元素不相同,python,python-3.x,Python,Python 3.x,假设您有一个字符列表。数组中字符的排列方式应确保两个相邻元素不相同 约束条件 字符数~10^6 示例输入-['c','d','d','a','a','x','d'] 示例输出-['a','d','x','c','d','a','d'] 我的尝试: a = ['a', 'a', 'b', 'c', 'c', 'b', 'd'] import random for c, d in zip(a, a[1:]): if c != d: continue else:
['c','d','d','a','a','x','d']
示例输出-['a','d','x','c','d','a','d']
我的尝试:
a = ['a', 'a', 'b', 'c', 'c', 'b', 'd']
import random
for c, d in zip(a, a[1:]):
if c != d:
continue
else:
random.shuffle(a):
print(a)
函数检查新数组是否具有不同的相邻元素:
def distinctAdjacentElement(a, n):
m = dict()
for i in range(n):
if a[i] in m:
m[a[i]] += 1
else:
m[a[i]] = 1
mx = 0
for i in range(n):
if mx < m[a[i]]:
mx = m[a[i]]
if mx > (n+1) // 2:
return True
else:
return False
def distinctAdjacentElement(a,n):
m=dict()
对于范围(n)中的i:
如果a[i]在m中:
m[a[i]]+=1
其他:
m[a[i]]=1
mx=0
对于范围(n)中的i:
如果mx(n+1)//2:
返回真值
其他:
返回错误
基于从Java到Python的代码转换,其中包括技术说明
from collections import Counter
from heapq import heappush, heappop
# Function to rearrange character of a string
# so that no char repeat twice
def rearrange(s):
# Use builtin function to count the freque3ncy of items
count = Counter(s)
# Insert all characters with their frequencies
# into a priority_queue (using a heap)
pq = []
for k, v in count.items():
heappush(pq, (-v, k)) # Use negative to make max heap
# since heaps are normally a min heap
# 'result' that will store resultant value
result = [0]*len(s)
# work as the previous visited element
# initial previous element be. ( '#' and
# it's frequency '-1' )
prev = (1, '#')
# traverse queue
ind = 0
while pq:
if ind >= len(s):
break
# pop top element from queue and add it
# to string.
k = heappop(pq)
result[ind] = k[1]
# If frequency of previous character is >= 0 that means it is useless, we
# need not to push it (note this is oposite from original algorithm since
# we are using a max heap by inverting the sign of the frequency counts
if prev[0] < 0:
heappush(pq, prev)
# make current character as the previous 'char'
# decrease frequency by 'one'
prev = (k[0]+1, k[1])
ind += 1
# If length of the resultant string and original
# tring is not same then string is not valid
if ind != len(s):
return None
elif isinstance(s, list):
return result
else:
return ''.join(result)
可能有多个这样的阵列。你为什么会期待这个呢?输入:
['a','a','a']
。预期产量:???还有,你有没有尝试解决这个问题?如果是这样的话,请分享你的代码,以避免它被关闭为“太宽”。一个可以应用于该问题的解决方案应该是,“是否有可能按照给定的顺序排列字符,使相邻的两个元素不完全相同?”。更为困难的是,“给定序列有多少这样独特的安排?”通常,这里没有人需要代码。我们帮助您更正代码。
print(rearrange(['c', 'd', 'a', 'a', 'x', 'd']))
>>> ['a', 'd', 'a', 'c', 'd', 'x']
print(rearrange(['b', 'b', 'a', 'a']))
>>> ['a', 'b', 'a', 'b']
print(rearrange(['b', 'b', 'a', 'a', 'a', 'a']))
>>> None
# Also handles strings
print(rearrange('bbaaa'))
>>> ababa