Reputation: 15
For who's interested in; lucky numbers are generated by eliminating numbers based on their position in the set. i.e:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
First eliminates every second number bc second value is 2:
1,3,5,7,9,11,13,15,17,19,21
First remaining number in the list after 1 is 3; so it eliminates every third number:
1,3,7,9,13,15,17,19,21
Next number is 7; eliminate every 7th number in the list:
1,3,7,9,13,15,21
Next surviving nunmber after 7 is 9 but obviously there are not enough numbers to eliminate. For further information you can check Lucky Number
So, if my list doesn't contain any negative number and begins with 1 i.e:
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22']
My code supposed to delete every number unless it's a lucky number, so I tried:
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)
But it returns:
['1', '3', '5', '7', '9', '11', '13', '15', '17', '19']
Where am I wrong? Or is there any efficient way to write it? Thank you.
Upvotes: 0
Views: 4044
Reputation: 1784
The negative index is a bit confusing to me (at least), see if this code is easy to interpret-
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']
Upvotes: 1