Printing First n Lucky Numbers - Python

I am writing a piece of code in python that checks if a given number is satisfied or not, that is, the number and adding the sum of their squares is 1, which is a lucky number or ends with an infinite loop that determines an unlucky number. After that, I want to list the first n Happy Numbers. I got a check for lucky numbers, although carelessly, I just can't figure out what a listing is.

def adder(num):
    total=0
    if len(str(num))>1: #check if given number is double digit or not
        tens = int(str(num)[0]) # splitting the digits 
        ones = int(str(num)[1])
        total = (tens**2)+(ones**2) # summing up the squares 
        #print (total)
        return total
    else: # if the given number  is a single digit
        total = (num**2)
        #print (total)
        return total

#adder(9)

def happynumber(num, counter):
    N = adder (num) # storing the sum in a variable 


    #print ("value of n is {}".format(N)) 
    if N == 1: #checks if the sum is 1
       # print ("In just {} tries we found that {} is a happy number.".format(counter, number))
        print (number)



    else: # if the sum isn't 1, racalls the happynumber function 
        counter += 1 # keeps track of number of tries so that we don't end up in an infinite loop
        if counter < 11: # setting the limit for number of tries
            #print (counter) 
            happynumber (N, counter)
        else:
            #print ("it took us {} tries and found that the number {} is not a happy number".format(counter, number))
            return False       

counter = 0


for i in range(0,100): # listing all the happy numbers between 0 and 100
    number = i
    happynumber (number, counter)

In addition, I would like you to look at my writing style and indicate some pointers.

Problem, I can’t list the first n numbers, as if trying.

I tried using a counter in a loop, but to no avail.

+4
source share
4 answers

, , , .

def happynumber(num, counter):
    N = adder(num)  

    if N == 1: 
        happyhappy.append(number)      #new happy number into list
    else: 
        ...continue with your code       

#-------main script-------------
happyhappy = []                        #create a list to store your happy numbers
counter = 0
for i in range(100): 
    number = i
    happynumber(number, counter)

print(happyhappy)                      #and retrieve the list

, adder() . . , , .

:

square_dic = {str(i): i ** 2 for i in range(10)}  #create a dictionary of squares
def adder(num):                           
    s = str(num)                                  #make the number into an iterable string
    x = [square_dic[i] for i in s]                #look up the square of each digit
    return sum(x)                                 #and calculate the sum of squares

Python

square_dic = {str(i): i ** 2 for i in range(10)}
def adder(num):                                   #does exactly, what the other function did
    return sum(square_dic[i] for i in str(num))
+1

, counter, . , , , , .

reset counter. , , , 10 , false , . counter = 0 return False if counter < 11/else

+1

. happynumber, , .

, , , .

:

def happynumber(num, counter, the_list):
    N = adder(num); 
    print ("value of n is {}".format(N));
    if counter == 0:  #THIS IS ADDED
        the_list.append(num); #THIS IS ADDED
    if N == 1: 
        print ("In just {} tries we found that {} is a happy number.".format(counter, number))
        print (num);
    else: 
        counter += 1
        if counter < 11:
            print (counter) 
            happynumber(N, counter, the_list)
        else:
            print ("it took us {} tries and found that the number {} is not a happy number".format(counter, number))
            the_list.pop(); #THIS IS ADDED
            return False       

counter = 0;

happynumber_list = []; #THIS IS ADDED
for i in range(0,100): 
    number = i
    happynumber (number, counter, happynumber_list)

... .. pop .

:

[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 59, 68, 70, 79, 82, 86, 91, 94, 95, 97]

?

+1

You can use memoization to unnecessarily use a counter. I would also use a generator ( yield), so you only get the number of results. Then you do not need to specify a range (0, 100), but you can simply indicate that you need the first 25 lucky numbers (or something else is needed).

Here's what it would look like:

import itertools

def sum_digit_squares(num):
    return sum(int(i)*int(i) for i in str(num))

def happynumbers():
    memo = { 1: True }
    for i in itertools.count(): # forever (as long as getting from this iterator)
        result = None # Will become either True (happy) or False (not happy)
        visited = set()
        j = i
        while result is None:
            if j in memo: # Did we make the calculation for this one before?
                result = memo[j] 
            elif j in visited:
                result = False # endless loop detected
            else:
                visited.add(j)
                j = sum_digit_squares(j)
        for j in visited:
            memo[j] = result
        if result:
            yield i

print (list(itertools.islice(happynumbers(), 0, 25))) # Produce first 25 happy numbers
0
source

Source: https://habr.com/ru/post/1692708/


All Articles