This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed last month.
i = 1
input_number = int(input("Input a digit you wish to count: "))
def count(n):
global i
n = int(n/10)
if n > 0:
i = i+1
count(n)
else:
j = i
print(f"j={j}")
return j
j = count(input_number)
print(f"i={i}")
print(j)
I'm trying to use a recursive way to print the digits of a number. I used a global counter to count, and can print the global counter as result. However, my question is - why can't I make the function to return the counter and print the function result directly? It returns None somehow.
The count function does not always return a value, so in those cases, it returns None.
If n is greater than 0, no return is encountered.
if n > 0:
i = i+1
count(n)
You were likely wanting:
if n > 0:
i = i+1
return count(n)
Please also note that if you want integer division, you can use //. E.g. n = int(n/10) can be n = n // 10 or just n //= 10.
Related
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 2 years ago.
Can you tell me why my fundamental Python program doesn't run properly. First I have a isprime module:
def isPrime(value):
count = 0
for i in range(1, value + 1):
if value % i == 0:
count += 1
if count == 2:
return True
else:
return False
and I import it to the PrimeFinder.py:
from isPrime import isPrime
lst = []
NumberOfValue = int(input())
for i in range(1, NumberOfValue + 1):
value = int(input())
lst.append(value)
for value in lst:
if isPrime(value) == False:
lst.remove(value)
print(lst)
But when I input:
the result also include non-prime numbers, can you explain if I was wrong in somewhere, thanks a lot for you help
from isPrime import isPrime
lst = []
NumberOfValue = int(input())
for i in range(1, NumberOfValue + 1):
value = int(input())
if isPrime(value):
lst.append(value)
print(lst)
Change the code to this, it will work. .remove will not remove the value from the list
Appears you should be doing
for i in range(1, NumberOfValue + 1):
value = int(input())
if isPrime(value):
lst.append(value)
Otherwise, you're modifying a list while iterating, and therefore skipping over some indicies and leaving elements behind
Regarding the efficiency of your isPrime function, there are better ways isPrime Function for Python Language
i have a problem when i try to find if a number is factorial
this is what I've done so far:
i = 1
count = 0
while n>1:
if n % i == 0:
n /= i
else:
break
i+=1
if n<=1:
count += 1
return count
but it returns 1 and I don't know how to fix
As written, the value of count in your example code indicates whether or not the number n is a factorial number, for a single n.
If it is, then at some point n <= 1, so count will be incremented, and the value of count returned by the function will be 1. If it is not, then at some point before n <= 1, n % i == 0 will be False, the loop will break, and the returned value of count will be 0.
Note, though, that there is an edge case not covered by your example code as is. Namely, 1 is a factorial number (1! = 1). But if n is 1, the condition on the while loop is never True, so the function immediately returns 0. So, you need to change the condition in the while loop.
E.g.
def isfactorialnumber(n):
i = 1
count = 0
while n >= 1:
if n % i == 0:
n /= i
else:
break
i += 1
if n <= 1:
count += 1
return count
I have 2 further comments about this code.
First, in the context of this new function, the variable name count is misleading. What is it counting? Nothing, really. It can only take 2 values, 1 or 0. It would be better then, to use a boolean variable, and call it result or similar. Even better, get rid of the variable and refactor your code as:
def isfactorialnumber(n):
i = 1
while n >= 1:
if n % i == 0:
n /= i
else:
break
i += 1
if n <= 1:
return True
return False
Which is equivalent but a little better.
Second, a more readable, natural way to solve the problem would be to work from bottom-up. That is, solve the problem by generating the factorial numbers, m that are less than or equal to n, then checking if the last m is equal to n. This leads to more concise and understandable code IMO.
E.g.
def isfactorialnumber(n):
m = 1
i = 1
while m < n:
m *= i
i += 1
return m == n
Finally, assuming each number in your file, is on its own line:
with open('factorials.txt') as infile:
print(len([1 for line in infile if isfactorialnumber(int(line))]))
Will print the number of factorial numbers in the file factorials.txt
count = 0
for n in listOfNumbers:
i = 1
while n>=1:
if n % i == 0:
n /= i
else:
break
i+=1
if n<=1:
count += 1
return count
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)
What I think:
def sum_square(n):
result = 0
if n > 0:
i = iter(n)
for i in n:
result += i * i
return result
elif n <= 0:
raise ValueError("n should be positive")
print(sum_square(4))
However, the terminal displays that int object is not iterable.
What's wrong with my answer? Could you do the modification based on my thought?
Closed form
First of all, know that the sum of squares has a closed form. Here is the formula shifted to sum up to n - 1.
def sum_square(n):
if n < 0:
raise ValueError('n must be positive')
return n*(n-1)*(2*n-1)//6
Actually, all sums of powers have a known closed form.
About your code
You cannot call iter(n) on an integer, you probably meant range(n).
def sum_square(n):
result = 0
if n > 0:
for i in range(n):
result += i * i
return result
elif n <= 0:
raise ValueError("n should be positive")
Although the above could be simplified using sum.
def sum_square(n):
return sum(x**2 for x in range(n))
How do I get my num_digit function to return 1 instead of 0 whenever I put in 0 as the parameter in the function?
How do I get the function to return any integer such as negative numbers?
def num_digits(n):
count = 0
while n:
count = count + 1
n = abs(n) / 10
return count
I was working on question number 2 first. Even if I put the abs(n) in the line of code where while is, I still get an infinite loop which I still do not really understand why. I figured if I can get my n value to always be positive and input in say -24, it would convert it to 24 and still count the number of values.
On question 1, I do not know where to start, ive tried:
def num_digits(n):
count = 0
while n:
if n == 0:
count = count + 1
n = n / 10
return count
I forgot to add I have limited tools to use since I am still learning python. I have gotten up to iterations and am studying the while loops and counters. I have not gotten to break yet although I have an idea of what it does.
When in doubt, brute force is always available:
def num_digits(n):
if n == 0:
return 1
if n < 0:
return num_digits(abs(n))
count = 0
while n:
count = count + 1
n = n / 10
return count
Process the exceptional cases first, and then you only have to deal with the regular ones.
If you want to avoid the conditionals, I suggest taking abs(n) only once, at the beginning, and using an infinite loop + break for the 0 case:
def num_digits(n):
n = abs(n)
count = 0
while True:
count = count + 1
n = n / 10
if n == 0:
break
return count
For a more practical solution, you can either count the number of digits in the string (something like len(str(n)) for positive integers) or taking log base 10, which is a mathematical way of counting digits.
def num_digits(n):
if n == 0:
return 0
return math.floor(math.log10(math.abs(n)))