Python 中的幸运数字
Lucky Numbers in Python
谁感兴趣;幸运数字是根据数字在集合中的位置消除数字而生成的。即:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
首先消除每个第二个数字 bc 第二个值为 2:
1,3,5,7,9,11,13,15,17,19,21
列表中1之后的第一个剩余数字是3;所以它消除了每三个数字:
1,3,7,9,13,15,17,19,21
下一个数字是7;消除列表中的每第 7 个数字:
1,3,7,9,13,15,21
7之后的下一个幸存数字是9,但显然没有足够的数字可以消除。
有关更多信息,您可以查看 Lucky Number
因此,如果我的列表不包含任何负数且以 1 开头,即:
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22']
我的代码应该删除每个数字,除非它是幸运数字,所以我尝试了:
def lucky_numbers(numbers):
del numbers[::-2] # Delete even numbers
while int(numbers[1]) < len(numbers):
x = int(numbers[1])
del numbers[-1::x]
print(numbers)
return
return
lucky_numbers(numbers)
但是 returns:
['1', '3', '5', '7', '9', '11', '13', '15', '17', '19']
我哪里错了?或者有什么有效的写法吗?谢谢。
负指数让我有点困惑(至少),看看这段代码是否易于解释-
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22']
def lucky_numbers(numbers):
index = 1
next_freq = int(numbers[index])
while int(next_freq) < len(numbers):
del numbers[next_freq-1::next_freq]
print(numbers)
if str(next_freq) in numbers:
index += 1
next_freq = int(numbers[index])
else:
next_freq = int(numbers[index])
return
lucky_numbers(numbers)
['1', '3', '5', '7', '9', '11', '13', '15', '17', '19', '21']
['1', '3', '7', '9', '13', '15', '19', '21']
['1', '3', '7', '9', '13', '15', '21']
谁感兴趣;幸运数字是根据数字在集合中的位置消除数字而生成的。即:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
首先消除每个第二个数字 bc 第二个值为 2:
1,3,5,7,9,11,13,15,17,19,21
列表中1之后的第一个剩余数字是3;所以它消除了每三个数字:
1,3,7,9,13,15,17,19,21
下一个数字是7;消除列表中的每第 7 个数字:
1,3,7,9,13,15,21
7之后的下一个幸存数字是9,但显然没有足够的数字可以消除。 有关更多信息,您可以查看 Lucky Number
因此,如果我的列表不包含任何负数且以 1 开头,即:
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22']
我的代码应该删除每个数字,除非它是幸运数字,所以我尝试了:
def lucky_numbers(numbers):
del numbers[::-2] # Delete even numbers
while int(numbers[1]) < len(numbers):
x = int(numbers[1])
del numbers[-1::x]
print(numbers)
return
return
lucky_numbers(numbers)
但是 returns:
['1', '3', '5', '7', '9', '11', '13', '15', '17', '19']
我哪里错了?或者有什么有效的写法吗?谢谢。
负指数让我有点困惑(至少),看看这段代码是否易于解释-
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22']
def lucky_numbers(numbers):
index = 1
next_freq = int(numbers[index])
while int(next_freq) < len(numbers):
del numbers[next_freq-1::next_freq]
print(numbers)
if str(next_freq) in numbers:
index += 1
next_freq = int(numbers[index])
else:
next_freq = int(numbers[index])
return
lucky_numbers(numbers)
['1', '3', '5', '7', '9', '11', '13', '15', '17', '19', '21']
['1', '3', '7', '9', '13', '15', '19', '21']
['1', '3', '7', '9', '13', '15', '21']