Finding magic numbers in python [duplicate] - python

This question already has answers here:
Sum the digits of a number
(11 answers)
Closed 2 years ago.
I am trying to find the magic number in this program but I got stuck on this part and am not sure where to go next. I have searched up many ways on the internet but they are all using more complex code that I have not learned yet.
Example
input 45637
4+5+6+3+7 = 25
2+5 = 7
7 = magic number
num = int(input("Enter a positive number : "))
ans = 0
while num > 0 or ans > 9:
digit = num % 10
num = num//10
print(digit)

Using statements and operators you have already learned as demonstrated in your code, you can use a nested while loop to aggregate the digits from the division remainders into a total as the number for the next iteration of the outer while loop:
num = 45637
while num > 9:
total = 0
while num > 0:
digit = num % 10
num = num // 10
total = total + digit
num = total
print(num)
This outputs:
7

One way:
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
Full code:
num = int(input("Enter a positive number : "))
ans = num
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
print(ans)
Output for input 45637:
7

Related

Count occurence of largest number using python [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 5 months ago.
Suppose that you entered 3 5 2 5 5 5 0 and input always ends with the number 0, the program finds that the largest number is 5 and the occurrence count for 5 is 4.
Input: i enter 3 5 2 5 5 5 0 and it shows nothing as result
Code:
currentnum = int(input('Enter Numbers List, to end enter 0: '))
maxx = 1
while currentnum > 0:
if currentnum > maxx:
max = currentnum
count = 1
elif currentnum == maxx:
count += 1
print('The Largest number is:', int(maxx), 'and count is', int(count))
Python doesn't have thunks.
currentnum = int(input('Enter Numbers List, to end enter 0: '))
This sets currentnum to the result of running int on the value returned by the input call. From this point on, currentnum is an int.
while currentnum > 0:
if currentnum > maxx:
max = currentnum
count = 1
elif currentnum == maxx:
count += 1
In this loop, you never take any more input, or reassign currentnum, so the loop will carry on forever, checking the same number over and over again.
If you assigned to currentnum at the end of your loop, you could take input in one-number-per-line. However, you want a space-separated input format, which can be better handled by iterating over the input:
numbers = [int(n) for n in input('Enter numbers list: ').split()]
max_num = max(numbers)
print(f"The largest number is {max_num} (occurs {numbers.count(max_num)} times)")
(Adding the 0-termination support is left as an exercise for the reader.)
Another, similar solution:
from collections import Counter
counts = Counter(map(int, input('Enter numbers list: ')))
max_num = max(counts, key=counts.get)
print(f"The largest number is {max_num} (occurs {counts[max_num]} times)")
I recommend trying your approach again, but using a for loop instead of a while loop.
Okay. So one of the most important things to do while programming is to think about the logic and dry run your code on paper before running it on the IDE. It gives you a clear understanding of what is exactly happening and what values variables hold after the execution of each line.
The main problem with your code is at the input stage. When you enter a value larger than 0, the loop starts and never ends. To make you understand the logic clearly, I am posting a solution without using any built-in methods. Let me know if you face any issue
nums = []
currentnum = int(input('Enter Numbers List, to end enter 0: '))
while currentnum > 0:
nums.append(currentnum)
currentnum = int(input('Enter Numbers List, to end enter 0: '))
max = 1
count = 0
for num in nums:
if num > max:
max = num
count = 1
elif num == max:
count += 1
print('The Largest number is:', max, 'and count is', count)
Now this can not be the efficient solution but try to understand the flow of a program. We create a list nums where we store all the input numbers and then we run the loop on it to find the max value and its count.
Best of luck :)
Use the standard library instead. takewhile will find the "0" end sentinel and Counter will count the values found before that. Sort the counter and you'll find the largest member and its count.
import collections
import itertools
test = "3 5 2 5 5 5 0 other things"
counts = collections.Counter((int(a) for a in
itertools.takewhile(lambda x: x != "0", test.split())))
maxval = sorted(counts)[-1]
maxcount = counts[maxval]
print(maxval, maxcount)
to make sure that operation stops at '0', regex is used.
counting is done by iterating on a set from the input using a dict comprehension.
import re
inp = "3 5 2 5 5 5 0 other things"
inp = ''.join(re.findall(r'^[\d\s]+', inp)).split()
pairs = {num:inp.count(num) for num in set(inp)}
print(f"{max(pairs.items())}")
Why not do it this way?
print(f"{max(lst)} appears {lst.count(max(lst))} times")

Sum of n natural numbers using while loop in python [duplicate]

This question already has answers here:
Sum of the integers from 1 to n
(11 answers)
Closed 6 months ago.
The question was tp :write a program to find the sum of n natural numbers using while loop in python.
n = int(input("Enter a number: "))
i = 1
while i<n:
print(i)
i = i + 1
this is what I have done s far...
can not understand what to do next.
n = int(input("enter a number: "))
i = 1
sum = 0
while (i <= n):
sum = sum + i
i = i + 1
print("The sum is: ", sum)
with a while loop the sum of natural numbers up to num
num = 20
sum_of_numbers = 0
while(num > 0):
sum_of_numbers += num
num -= 1
print("The sum is", sum_of_numbers)
You can either follow Alasgar's answer, or you can define a function with the formula for this particular problem.
The code's gonna be something like this:
def natural(n):
sumOfn = (n * (n + 1))/2
terms = int(input("Enter number of terms: "))
natural(terms)
number = int(int(input("Enter the number: "))
if number < 0:
print("Enter a positive number: ")
else:
totalSum = 0
while (number > 0):
totalSum += number
number -= 1
print ("The sum is" , totalSum)
num = int(input('Enter the number : '))
sum = 0
while 0<num:
sum += num
num -= 1
print(f'The sum of the number is {sum}')

Sum of digits in a number [duplicate]

This question already has answers here:
How to manage division of huge numbers in Python?
(4 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
This function is supposed to return the sum of all the digits in a number.
def sum_digits(num):
if int(num) <= 0:
return 0
else:
sum = 0
while int(num) != 0:
n = int(num) % 10
num = int(num) / 10
sum = int(sum + n)
return sum
It works fine for smaller numbers, but if i enter for example number 999999999999999999999999999999999 it returns 74 instead of 297.
Thanks for help
You need to divide with (//) instead of (/), because that would return a floating number.
You need to do something like this:
def sum_digits(num):
num = int(num)
if num <= 0:
return 0
else:
sum = 0
while num != 0:
n = num % 10
num //= 10
sum += n
return sum
(I reformated your code a little for better readability.)
edit: typo fixed
I approached your problem a little different
number = 999999999999999999999999999999999
number = str(number)
sum = 0
for digit in number:
digit = int(digit)
sum = digit+sum
print(sum)

Find all the divisors of a number using Python [duplicate]

This question already has answers here:
What is the best way to get all the divisors of a number?
(18 answers)
Closed 2 years ago.
I am trying to write a Python script that will find prime numbers. In the way that I am going about this, the script is going to take a number from a range, determine the factors, determine if the only two factors are 1 and itself, and return true if it's a prime number. I need help with my code to find the factors.
num = int(input("enter: "))
i = 1
while i < num:
if num % i == 0:
print(i)
i += 1
else:
pass
The i is set to 1 because you can't divide by 0. However, the return starts to work, however, it only returns a couple of numbers, not the full list that I am hoping for. For example, you input 20, it returns only 1 and 2.
You're only incrementing i in the "is even" case. This'd fix it:
num = int(input("enter: "))
i = 1
while i < num:
if num % i == 0:
print(i)
i += 1
However, it's better to use range() for iterating over a range of numbers:
num = int(input("enter: "))
for i in range(1, num):
if num % i == 0:
print(i)

Coding exclusions in a for loop (python) [duplicate]

This question already has answers here:
Sieve of Eratosthenes in Python
(3 answers)
Closed 6 years ago.
i'm trying to figure out how to exclude certain numbers (numbers that aren't prime) in my program. For example, I don't want 15 to be printed so I used the modulo to exclude numbers divisible by 5 but that eliminates 5, which is a prime number. Any help on how to code this would be huge help! Thank you...
start = int(input("Start number: "))
end = int(input("End number: "))
while start < 0 or end < 0:
print ("Start and end number must be positive. Try again.")
start = int(input("Start number: "))
end = int(input("End number: "))
while start > end:
print ("End number must be greater than start number. Try again.")
for x in range (start, end):
is_prime = True
for x in range (start, end):
trial = x % 2
trial1 = x % 5
trial2 = x % 3
if trial != 0 and trial1 != 0 and trial2 != 0:
print (x, "is a prime number")
x = x + 1
else:
is_prime = False
You can create a list of numbers you want to use in your loop let's call it loop_list and then simply use for x in loop_list, that avoid you setting up exclusions
If you want to be sure that N is a prime number, you have to check for all number to squareroot(N) if N%number != 0.
Are you looking for optimisation? If no, you just need that.
You can try this prime number logic :-
def check_prime(num):
notPrimeFlag = 'N'
for i in range(2, num):
if num % i == 0:
notPrimeFlag = 'Y'
break
if notPrimeFlag == 'N':
print("Prime number")

Categories