How Can I Print All Values That Are True According To The Statement Provided
so I programmed my code in a way that whenever an input number is given, the output will always only display '1' or '4' after squaring each digit of the number AND adding the value
Solution 1:
Explanation of infinite loop for 0
:
If we start loop from 0
it appears a infinite loop state because it never match x not in ['1', '4']
this condition. To overcome this we can ignore 0
or put a condition to check if number is 0
or not.
Try this:
defGetX(number):
sum_of_digits = 0
x = ''while x notin ['1', '4']:
for digit instr(number):
sum_of_digits += (int(digit)**2)
x = str(sum_of_digits)
number = sum_of_digits
sum_of_digits = 0return x
defIsHappy(x):
if x == '1':
returnTrueelse:
returnFalsefor x inrange(1, 101):
if IsHappy((GetX(x))):
print(x)
# or store happy number in a list
res = [x for x inrange(1, 101) if IsHappy((GetX(x)))]
print(res)
Output:
171013192328313244496870798286919497100
[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]
Solution 2:
Put the code that calculates the sum of digits in a function. You can then call the function in a loop.
defget_sum_of_digits(number):
x = ''while x notin ['1', '4']:
sum_of_digits = sum(int(digit)**2for digit instr(number))
x = str(sum_of_digits)
return x
defIsHappy(x):
if x == '1':
return'True'else:
return'False'for i inrange(1, 100):
if IsHappy(get_sum_of_digits(i)) == 'True':
print(i)
Post a Comment for "How Can I Print All Values That Are True According To The Statement Provided"