Thursday 14 June 2018

Generating Lucky Numbers in Python

I got to thinking how I could generate lucky numbers in Python (for an earlier post explaining what lucky numbers are: click here). I experimented a little but wasn't making any real progress which is not surprising given that I'm really just a beginner. A quick search revealed the following exercise: Python Math: Print the first n Lucky Numbers along with the required code. What surprised me was the brevity of the code:


I've worked through the code now and understand it, although I struggled initially, especially. Let's suppose n is given a value of 10. This means:
  • List = range(-1,109,2) = (-1, 1, 3, 5, ..., 107, 108)
  • while List[i:] = List[2:] = (3, 5, ..., 107, 108) because initially i has a value of 2
  • List[List[i]::List[i]] = List[List[2]::List[2]] = List[3, 5, ..., 107, 108]
  • i+=1 means that value of i, will increment by 1, as the while loop is traversed
The while loop will continue as long as List[i:] is True but eventually the i will be greater than the length of List and List[:i] will be FALSE. In SageMathCell, things look like this:


The above code is purely Python and doesn't used any SAGE code at all. As far as I know, there's no command in the latter that will generate lucky numbers (as can be done for prime numbers). There are 82 exercises with solutions at the W3resource site. It would be instructive to attempt some of these. 

No comments:

Post a Comment