获取一个从0到n的数字列表,其中没有相邻的连续数字且数字的值不等于其索引
Getting a list of numbers from 0 to n, which has no adjacent consecutive numbers and the value of the number is not equal to its index
所以,我想要一个函数 return 一个列表 (l),它有值 (0, 1, 2, 3, ... , n) 但连续的数字不能彼此相邻.并且数字的值不能等于它的索引。
例如。对于 n = 4,
def main(n)
---code goes here---
return l
print(main(4))
>>>[1, 3, 0, 2]
非常感谢
编辑:
到现在为止已经写了这么多,但我不确定我是否在正确的轨道上......
def sameRowColumn(lst):
for i in range(len(lst)):
if i == lst[i]:
return True
def sameDiagonal(lst):
for i in range(len(lst)):
for j in range(len(lst)):
if i != j:
if i + lst[i] == j + lst[j] or i - lst[i] == j - lst[j]:
return True
# def backTrack(lst1, lst2, dist):
# for i in range(len(lst1)-1, (len(lst1)-1)-dist, -1):
# lst2.append(lst1[i])
# lst1.remove(lst1[i])
def queensList(N):
l = []
nums = [i for i in range(N)]
while len(l) != N and len(nums) != 0:
l.append(nums[0])
print(l, nums)
if sameRowColumn(l) or sameDiagonal(l):
l.remove(nums[0])
nums.insert(len(nums), nums.pop(0))
print(l, nums)
else:
nums.remove(nums[0])
print(l, nums)
return l, nums
print(queensList(4))
这里是在 python 3.6
中测试过的
这会依次打印所有奇数和所有偶数,如果最后一个偶数等于我们交换 n-1 和 n
的索引
n=input("Enter ur number: ")
n = int(n)
l =[0]*n
y=1
z=0
for x in range(n):
if y<=n and x+1<=n/2:
l[x]=y
y=y+2
else:
if(x==z):
l[x]= l[x-1]
l[x-1] = z
z=z+2
else:
l[x]=z
z=z+2
print(l)
所以,我想要一个函数 return 一个列表 (l),它有值 (0, 1, 2, 3, ... , n) 但连续的数字不能彼此相邻.并且数字的值不能等于它的索引。
例如。对于 n = 4,
def main(n)
---code goes here---
return l
print(main(4))
>>>[1, 3, 0, 2]
非常感谢
编辑: 到现在为止已经写了这么多,但我不确定我是否在正确的轨道上......
def sameRowColumn(lst):
for i in range(len(lst)):
if i == lst[i]:
return True
def sameDiagonal(lst):
for i in range(len(lst)):
for j in range(len(lst)):
if i != j:
if i + lst[i] == j + lst[j] or i - lst[i] == j - lst[j]:
return True
# def backTrack(lst1, lst2, dist):
# for i in range(len(lst1)-1, (len(lst1)-1)-dist, -1):
# lst2.append(lst1[i])
# lst1.remove(lst1[i])
def queensList(N):
l = []
nums = [i for i in range(N)]
while len(l) != N and len(nums) != 0:
l.append(nums[0])
print(l, nums)
if sameRowColumn(l) or sameDiagonal(l):
l.remove(nums[0])
nums.insert(len(nums), nums.pop(0))
print(l, nums)
else:
nums.remove(nums[0])
print(l, nums)
return l, nums
print(queensList(4))
这里是在 python 3.6
中测试过的这会依次打印所有奇数和所有偶数,如果最后一个偶数等于我们交换 n-1 和 n
的索引n=input("Enter ur number: ")
n = int(n)
l =[0]*n
y=1
z=0
for x in range(n):
if y<=n and x+1<=n/2:
l[x]=y
y=y+2
else:
if(x==z):
l[x]= l[x-1]
l[x-1] = z
z=z+2
else:
l[x]=z
z=z+2
print(l)