Competitive Programming Python: Repeated sum of digits Error - python

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.

Related

My code seems to break in line 2 at int(number), i don’t know why though?

Please help. I have the follow exercise but I can't get my code to work.
For every positive total number n you can determine a unique code consisting of two numbers m and p. That works like this:
Step 1: Write n as a number in the binary system, as a binary number b. See below for explanation.
Step 2: Write b backwards as a binary number a.
Step 3: The number m is the number of zeros with number one starting.
Step 4: You get the number by writing the binary number as a number in the decimal system.
For example, suppose n = 202.
Binary you can write that as 1100010.
If you write that backwards, you get 01010011.
That number starts with 1 times a 0.
If you omit that you get 1010011. Write that again in the decimal system and you get 83.
The AB code of 202 is then the pair 1 and 83.
Write a program that takes a number n in the least of standard input. 0 < n < 1000000000 applies.
The program writes two lines to standard output. On the first line is the number m and on the second the number p.
Example:
Input: 202
Output: 1 83
number = input()
a = f'{​​​​​​int(number):0b}​​​​​​'
a = str(a)
code = []
zeroes = 0
for i in a:
code.append(i)
code.reverse()
while True:
if code[0] == "0":
code.pop(0)
zeroes = zeroes + 1
else:
break
x = ''
for i in range(len(code)):
x = x + code[i]
newnum = int(x ,2)
print(str(zeroes))
print(newnum)
I am not sure but is the fString statement correct? Or should it be like:
f'int({number}):0b'

Python: Find Prime Number Algorithm

Recently I was given a challenge to my coding skills by my teacher since he saw that I was already knowledgeable in what he was teaching. The question is as follows.
Create a program that prompts the user for 2 numbers. The program will then display all the prime numbers in between the two given numbers, including the given numbers. Note: You cannot assume the first input is bigger than the second input.
So I took this question and built a fairly simple algorithm and ran it and it worked. I opened it today to find out for some reason my output is occasionally wrong, for example when you input 8 and 29 I get 27. I am looking for HINTS as to what is wrong with my logic because I cannot for the life of me figure out what Im doing wrong. I dont want straight up fixes because I would like to learn as much from this and doing it as much as possible by myself.
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
numList = []
#Removing Even Numbers
for num in range(numbers[0],numbers[1] + 1):
if num % 2 != 0:
numList.append(num)
#Checking For Prime Numbers
for currNum in numList:
#Set Start number to divide
i = 2
while i < currNum:
#Checks if the currNum can be divisble by i and is a whole number
if currNum % i != 0:
i = i + 1
else :
numList.remove(currNum)
break
print(numList)
From what I have learned from testing this out it seems like 27 is never checked during my for loop or while loop even though it is in the numList array.
Never remove items form a list you are iterating over.
Instead create a new list:
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
primes = []
for num in range(numbers[0], numbers[1] + 1):
#Set Start number to divide
i = 2
while i < num:
#Checks if the currNum can be divisble by i and is a whole number
if num % i == 0:
break
i += 1
else:
primes.append(num)
print(primes)

How can I display all numbers in range 0-N that are "super numbers"

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

digit_sum error, iterating through a string and then changing to an integer, python

On Codecademy.com I am on section 8, "Practice Makes Perfect", exercise 4 they ask you to:
Write a function called digit_sum that takes a positive integer n
as input and returns the sum of all that number's digits. For example:
digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that
the number you are given will always be positive.)
def digit_sum(n):
total = 0
n = str(n)
for i in n:
total += int(n[i])
return total
Since you have to only add one of the digits, I wrote a program that changed the number into a string and then iterate over each digit. When I iterate, I add each number to a local varible, total, by accessing the digit and then changing the number back into an integer. After writing my program, I was thrown the error "string indices must be integers, not str". This is the error you get when you try to add a number to a string. I was confused by this so I researched if other people were having the same problem. I also asked my programming teacher and we still could not figure it out. Can someone explain what I am doing wrong?
It does not tell me what line is throwing the error either. I forgot to mention but on the website they give a solution, but it is not at all in the terms of what I am doing, I am just severely confused of why this error is occurring.
Just change it to:
def digit_sum(n):
total = 0
n = str(n)
for i in n:
total += int(i)
return total
In python, unike c++ and other languages:
the for loop iterates the element itself and not its index.
Your code iterates over the characters of your string, not the indices. Change to:
def digit_sum2(n):
total = 0
n = str(n)
for i in range(0, len(n)):
total += int(n[i])
return total

"'int' object is not iterable" when asking for a Number input (beginner)

I am planning to create a program which basically lists the Fibbonacci sequnce up to 10,000
My problem is that in a sample script that I wrote I keep getting the error 'int' object is not iterable
My aim is that you enter a number to start the function's loop.
If anyone would help out that would be great
P.S I am a coding noob so if you do answer please do so as if you are talking to a five year old.
Here is my code:
def exp(numbers):
total = 0
for n in numbers:
if n < 10000:
total = total + 1
return total
x = int(input("Enter a number: "), 10)
exp(x)
print(exp)
numbers is an int. When you enter the number 10, for example, the following happens in exp():
for n in 10:
...
for loops through each element in a sequence, but 10 is not a sequence.
range generates a sequence of numbers, so you should use range(numbers) in the for loop, like the following:
for n in range(numbers):
...
This will iterate over the numbers from 0 to number.
As already mentioned in comments, you need to define a range -- at least this is the way Python do this:
def exp(numbers):
total = 0
for n in range(0, numbers):
if n < 10000:
total = total + 1
return total
You can adjust behavior of range a little e.g. interval is using. But this is another topic.
Your code is correct you just need to change :
for n in numbers:
should be
for n in range(0, numbers)
Since you can iterate over a sequence not an int value.
Good going, Only some small corrections and you will be good to go.
def exp(numbers):
total = 0
for n in xrange(numbers):
if n < 10000:
total += 1
return total
x = int(input("Enter a number: "))
print exp(x)

Categories