Count the number of trailing 0s in factorial of a given number.
Input Format
First line of input contains T - number of test cases. Its followed by T lines, each containing an integer N.
Output Format
For each test case, print the number of trailing 0s in N!, separated by new line
Here's the code for the above problem
`n=int(input())
for i in range (0,n):
num=int(input())
count=0
i=5
m=num/i
for i in range (m>=1):
count= count+m
print(count)`
the expected output is:
Input:
2
5
10
output:
1
2
but only 2 is being displayed as output overriding 1
plz help
You just need to move your print statement into your outer loop:
result = []
n = int(input())
for i in range(0, n):
num = int(input())
count = 0
i = 5
m = num / i
for i in range(m >= 1):
i * 5
count = count + m
result.append(count) # <- print statement was here but I added extra indent and then changed to append
for count in result:
print(count)
Per your comment, I also added code to store up your results instead of printing each result right away, so that they will all be printed at the end, after you've given all of your input.
This is one of the downsides of Python using indentation as language syntax. It's easy to make these sorts of mistakes.
btw, this gives the output you expect, but what do you think the line i * 5 is doing? It isn't doing anything. Also, with range(m >= 1), you're creating a range from a boolean value, which is strange.
This code finds no. Of trailing zeroes in factorial of numbers
for i in range(int(input())):
a=int(input())
f=1
c=0
for j in range(1,n+1):
f*=j
while(f%10==0):
f/=10
c+=1
print(c)
Related
Find the number of 6 digit numbers such that each digit appears atleast twice
I tried the below code but it doesn't work:
count = 0
for n in range(10**5,(10**6)-1):
n = str(n).split()
for i in range(len(n)):
n[i] = int(n[i])
if n.count(i) >= 2:
count+=1
print(count)
The original question is of Permutation and Combinations but I want to solve this using python...
Here are some of the mistakes in your code -
The range needs to be range(10**5, 10**6) to cover all 6 digit numbers
str(n).split() won't split the n into a list of characters since there is no delimiter between the string representation of the number. You can use [letter for letter in str(n)] instead.
You want to run the second loop for each of the numbers in the first loop, so the second loop needs to be inside the first loop.
Within the second loop, you are increasing the count if one of the digits occurs more than twice in the number, so you might end up increasing the count multiple times for a single number. e.g. for 112233 you would end up increasing the count by 3 instead of just 1.
here's a simplified code which does what you want in a similar format -
count = 0
for n in range(10**5, 10**6):
n = [letter for letter in str(n)]
count += 1
for letter in n:
if n.count(letter) < 2:
count -= 1
break
print(count)
outputs -
11754
You can use all() function along with list comprehension to simplify the code -
count = 0
for n in range(10**5, 10**6):
n = [letter for letter in str(n)]
count += all(n.count(letter) >= 2 for letter in n)
answers = []
count = 0
my_dict = {}
digits = '0123456789'
for n in range(10**5, (10**6)-1):
my_dict = {}
ns = str(n)
for m in ns:
if m in digits:
my_dict[m] = ns.count(m)
if my_dict[min(my_dict, key=my_dict.get)] > 1:
count += 1
answers.append(ns)
print(count)
Here is an alternative way. It gets the correct number.
This question already has answers here:
How do I print a fibonacci sequence to the nth number in Python?
(8 answers)
Closed 2 years ago.
I'm very new to python and programming in general. This is the first year we have programming classes, so I'd say I started about a month ago.
We got our first assignment last week and I've managed to make most of the tasks, apart from the following one:
Generate n numbers from the Fibonacci sequence, where n is entered by the user.
Write these numbers to the screen.
Print the numbers on 1 single line.
Tip: print (value, end = '')
Do not use list or array.
This is the last question and this one is significantly more difficult than the others. I tried some things but non came close to doing what is asked. I genuinely have no clue how I'd even have to start.
In pseudocode:
First you need to check, print and save the results of fibonacci(0) and fibonacci(1)
Then make a loop to calculate the next fibonacci value using the last two calculated and print it.
Update the variables for the last two calculated.
Iterate steps 2 and 3 for each N>2
Thinking in python3:
# Print Fibonacci(0)
if n>=0:
print (1, end =', ')
f2 = 1
# Print Fibonacci(1)
if n>0:
print (1, end =', ')
f1=1
# Print Fibonacci(n) ; n>1
if n>1:
for i in range (2, n+1):
result = f1+f2
print(result, end=', ')
# updating last two variables
f2 = f1
f1 = result
Although not mentioned, you may want to 'memorize' previous Fibonacci numbers so you can generate the sequence faster.
def fibonacci(n, _cache={}):
if n in _cache: # Check to see if the number has been done
return _cache[n] # Return the pre-done number
elif n > 1:
return _cache.setdefault(n, fibonacci(n-1) + fibonacci(n-2)) # Call this function recursively to generate the previous Fibonacci numbers
return n
n = int(input("n = "))
for i in range(n):
print(fibonacci(i), end=', ')
You need to think about loops, how to iterate a set number of times, and use the print statement given to you in the "tip".
In pseudo code:
next_in_sequence = 1
loop_count = 1
while loop_counter <= number_entered:
next_in_sequence = caclulate_next_fibonacci(next_in_sequence)
print (next_in_sequence, end = '')
loop_counter = loop_counter + 1
Have a go at writing this in python, you'll have to write the caclulate_next_fibonacci function to work out the next number in the sequence. If you have any problems edit your question to show your code and ask for more help
To calculate the next Fibonacci number simply add together the two previous values. You can do this in a for loop using variables declared outside the loop to hold the previous two values.
Use this statement within your loop
print (value, end = '')
This will print the sequence all on one line with each value separated by a space.
n = int(input())
fib0 = 0
fib1 = 1
for x in range(0, n):
nextFib = fib0 + fib1
fib0 = fib1
fib1 = nextFib
print(fib0 , end = ' ')
The program asks the user for a number N.
The program is supposed to displays all numbers in range 0-N that are "super numbers".
Super number: is a number such that the sum of the factorials of its
digits equals the number.
Examples:
12 != 1! + 2! = 1 + 2 = 3 (it's not super)
145 = 1! + 4! + 5! = 1 + 24 + 120 (is super)
The part I seem to be stuck at is when the program displays all numbers in range 0-N that are "super numbers". I have concluded I need a loop in order to solve this, but I do not know how to go about it. So, for example, the program is supposed to read all the numbers from 0-50 and whenever the number is super it displays it. So it only displays 1 and 2 since they are considered super
enter integer: 50
2 is super
1 is super
I have written two functions; the first is a regular factorial program, and the second is a program that sums the factorials of the digits:
number = int(input ("enter integer: "))
def factorial (n):
result = 1
i = n * (n-1)
while n >= 1:
result = result * n
n = n-1
return result
#print(factorial(number))
def breakdown (n):
breakdown_num = 0
remainder = 0
if n < 10:
breakdown_num += factorial(n)
return breakdown_num
else:
while n > 10:
digit = n % 10
remainder = n // 10
breakdown_num += factorial(digit)
#print (str(digit))
#print(str(breakdown_num))
n = remainder
if n < 10 :
#print (str(remainder))
breakdown_num += factorial(remainder)
#print (str(breakdown_num))
return breakdown_num
#print(breakdown(number))
if (breakdown(number)) == number:
print(str(number)+ " is super")
Existing answers already show how to do the final loop to tie your functions together. Alternatively, you can also make use of more builtin functions and libraries, like sum, or math.factorial, and for getting the digits, you can just iterate the characters in the number's string representation.
This way, the problem can be solved in a single line of code (though it might be better to move the is-super check to a separate function).
def issuper(n):
return sum(math.factorial(int(d)) for d in str(n)) == n
N = 1000
res = [n for n in range(1, N+1) if issuper(n)]
# [1, 2, 145]
First I would slightly change how main code is executed, by moving main parts to if __name__ == '__main__', which will execute after running this .py as main file:
if __name__ == '__main__':
number = int(input ("enter integer: "))
if (breakdown(number)) == number:
print(str(number)+ " is super")
After that it seems much clearer what you should do to loop over numbers, so instead of above it would be:
if __name__ == '__main__':
number = int(input ("enter integer: "))
for i in range(number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
Example input and output:
enter integer: 500
1 is super
2 is super
145 is super
Small advice - you don't need to call str() in print() - int will be shown the same way anyway.
I haven't done much Python in a long time but I tried my own attempt at solving this problem which I think is more readable. For what it's worth, I'm assuming when you say "displays all numbers in range 0-N" it's an exclusive upper-bound, but it's easy to make it an inclusive upper-bound if I'm wrong.
import math
def digits(n):
return (int(d) for d in str(n))
def is_super(n):
return sum(math.factorial(d) for d in digits(n)) == n
def supers_in_range(n):
return (x for x in range(n) if is_super(x))
print(list(supers_in_range(150))) # [1, 2, 145]
I would create a lookup function that tells you the factorial of a single digit number. Reason being - for 888888 you would recompute the factorial of 8 6 times - looking them up in a dict is much faster.
Add a second function that checks if a number isSuper() and then print all that are super:
# Lookup table for single digit "strings" as well as digit - no need to use a recursing
# computation for every single digit all the time - just precompute them:
faks = {0:1}
for i in range(10):
faks.setdefault(i,faks.get(i-1,1)*i) # add the "integer" digit as key
faks.setdefault(str(i), faks [i]) # add the "string" key as well
def fakN(n):
"""Returns the faktorial of a single digit number"""
if n in faks:
return faks[n]
raise ValueError("Not a single digit number")
def isSuper(number):
"Checks if the sum of each digits faktorial is the same as the whole number"
return sum(fakN(n) for n in str(number)) == number
for k in range(1000):
if isSuper(k):
print(k)
Output:
1
2
145
Use range.
for i in range(number): # This iterates over [0, N)
if (breakdown(number)) == number:
print(str(number)+ " is super")
If you want to include number N as well, write as range(number + 1).
Not quite sure about what you are asking for. From the two functions you write, it seems you have solid knowledge about Python programming. But from your question, you don't even know how to write a simple loop.
By only answering your question, what you need in your main function is:
for i in range(0,number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
import math
def get(n):
for i in range(n):
l1 = list(str(i))
v = 0
for j in l1:
v += math.factorial(int(j))
if v == i:
print(i)
This will print all the super numbers under n.
>>> get(400000)
1
2
145
40585
I dont know how efficient the code is but it does produce the desired result :
def facto():
minr=int(input('enter the minimum range :')) #asking minimum range
maxr=int(input('enter the range maximum range :')) #asking maximum range
i=minr
while i <= maxr :
l2=[]
k=str(i)
k=list(k) #if i=[1,4,5]
for n in k: #taking each element
fact=1
while int(n) > 0: #finding factorial of each element
n=int(n)
fact=fact*n
n=n-1
l2.append(fact) #keeping factorial of each element eg : [1,24,120]
total=sum(l2) # taking the sum of l2 list eg 1+24+120 = 145
if total==i: #checking if sum is equal to the present value of i.145=145
print(total) # if sum = present value of i than print the number
i=int(i)
i=i+1
facto()
input : minr =0 , maxr=99999
output :
1
2
145
40585
For example, if given a number 3, the program will print
1
1 2 2
1 2 2 3 3 3
OK,what I have tried like this:
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
It will print like:
1
1 2
1 2 3
You were close. Your problem is that you need to use j to print the current number j times. Thankfully, Python makes this easy by using sequence multiplication. That is, Python allows you to multiply a sequence - like a string - by a number. The contents of the string is replicated the amount of times it was multiplied by:
>>> 'a' * 3
'aaa'
>>> '1' * 4
'1111'
Thus, you can convert the current integer j to a string, and multiplied the string by j:
for j in range(1, a + 1):
print((str(j) + ' ') * j, sep='', end="")
With the above change your code now outputs:
Enter a positive integer: 3
1
1 2 2
1 2 2 3 3
Here are a few more ways you can improve your code.
Avoid eval like the black plague. It's very dangerous security-wise. Of course, you probably don't even have to worry about this now, but better not get in the habit. There's always a Better Way TM. In this case, use the built-in function int.
Rather than keeping an explicit counter with a, use the built-in function enumerate.
With the above improvements, your code becomes:
n = int(input("Enter a positive integer: "))
for a, i in enumerate(range(1, n + 1), 1):
for j in range(1, a + 1):
print((str(j) + ' ') * j, sep='', end="")
print()
You're missing a key thing in the code you've given (as below):
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
Within the for j in range(...) loop, where you actually print out each number, you only print the each number out once, rather than j times (where j is the current number).
You can fix this by using a special behavior of Python (string 'multiplication').
n = eval(input("Enter a positive integer: "))
a = 1
for i in range(1, n+1):
for j in range(1, a+1):
print('{} '.format(j) * j, end="")
a += 1
print()
Here is a method that does what you're requesting.
def numbers(n: int) -> None:
for i in range(1, n+2):
for j in range(1, i):
print(j * (str(j) + ' '), end='')
print()
First, we loop over all numbers from 1 to n+1.
Then, we loop over all numbers from 1 to the current number we are working with, minus one (that's why we have the n+2 in the outer loop).
Now we have all the information we need to print our line: we are printing j times the value of j followed by a space, appending it to whatever was printed on this line already before.
Finally, after finishing our line, we print a newline, so we can start fresh in the next outer loop.
Hope this helps!
You are definitely on the right track. Let's look closer at your code:
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
i is going iterate from 1 to n. That's a good intuition, as we need every number.
j is going iterate from 1 to a. A way to debug the code is to work through an example. Let's say i will iterate in range(1, 3). The first time in the loop, j will iterate in range(1, 2) and it'll print "1". The second time, j will iterate in range(1, 3) and it'll print "1 2". There's our problem; we wanted 2 to print out twice!
i is actually the number we want to print, j is the number of times we want to print the number. We actually don't need the a variable:
n = int(input("Enter a positive integer: "))
message = ""
for i in range(1, n + 1):
for j in range(0, i):
message += str(i) + " "
print(message)
We can condense this further. I try to think of it in my head first, and then code it.
"I want 1 once, 2 twice, 3 thrice, etc.". This means, we don't even need an inner loop. You know how many times you want to print i... i times!
message = ""
for i in range(1, n + 1):
message += (str(i) + " ") * i
print(message)
Also, notice the style in your code. PEP8 has guidelines for how to write proper Python code. Notice:
Using "int" is better than "eval" if possible, because you only want your program to take numbers.
Spacing in parenthesis "range(1, a+1)" is better than "range(1,a+1)".
Variable declarations like "a = 1" is better than "a=1".
These best practices will make your code more readable :)
>>> print(*[' '.join(map(str, [n for n in range(1, n+1) for n in [n]*n])) for n in range(1, n+1)], sep='\n')
1
1 2 2
1 2 2 3 3 3
Don't know It's right place to ask this or not. But I was feeling completely stuck. Couldn't find better way to solve it.
I am newbie in competitive Programming. I was solving Repeated sum of digits problem Here is The Question.
Given an integer N, recursively sum digits of N until we get a single digit.
Example:-
Input:
2
123
9999
Output:-
6
9
Here is my code:-
def sum(inp):
if type(inp) == int:
if len(str(inp)) <= 1:
return inp
else:
a = list(str(inp))
while len(a) > 1:
b = 0
for i in a:
b+= int(i)
a = list(str(b))
return b
t = int(raw_input())
for i in range(0,t):
print sum(i)
While submitting it gave My following error:-
Wrong !! The first test case where your code failed:
Input:
42
Its Correct output is:
6
And Your Output is:
0
However When I tested my code personally using 42 It's perfectly gives me correct Output 6.
Here is the link of question:- Repeated sum of digits Error
You have not implemented the code properly. You are iterating over i from 0 to t. Why?? The methodology goes as follows:
N = 12345
Calculate the sum of digits(1+2+3+4+5 = 15).
Check if it is less than 10. If so, then the current sum is the answer.. If not.. follow the same procedure by setting N = 15
Here is the code:
def sum(inp):
while inp > 9:
num = inp
s = 0
while num > 0:
s = s + num%10
num = num/10
inp = s
return inp
t = int(raw_input())
for i in range(t):
n = int(raw_input())
print sum(n)
Edit: I think you are iterating till t because you have considered t to be the number of testcases. So, inside the for loop, you should take another input for N for each of the testcase. [This is based on the input and output that you have provided in the question]
Edit-2: I have changed the code a bit. The question asks us to find the repeated sum of t numbers. For that, I have added a loop where we input a number n corresponding to each testcase and find its repeated sum.