I wrote this code for summing up digits of a number which is bigger than 10 until the result only have one digit and when I try to compile it, it won't even give me an error until I stop it. I want to know what's the problem.
number = input()
#sumed_up_digits = result
result = 0
while len(number) != 1:
for i in number:
int_i = int(i)
result = result + int_i
number = str(result)
print(result)
Try the following code:
s=input()
n=len(s)
result=0
for i in range(n-1):
result=result+int(s[i])
print(result)
This for loop runs from 0th to (n-2)th index of the given string, hence the last digit will not be added to the result. Like for 1245, it will add 1,2 and 4 to result, but not 5.
result is cumulative and include previous sums.
try:
number = input()
#sumed_up_digits = sum
sum = 0
while len(number) != 1:
result = 0
for i in number:
int_i = int(i)
result = result + int_i
sum = sum + result
number = str(result)
print(sum)
You can do it like this:
number = input()
if len(number) <= 1:
print(0)
while len(number) > 1:
number = str(sum(int(i) for i in number))
print(int(number))
Of course, you would need to check that the initial input number is made of digits...
the problem is number isn't being shortened so the condition for the loop to stop is never reached.
number = input()
result = 0
while len(number) != 1:
# set digit to last number
digit = int(number) % 10
result += digit
number = number[:-1]
print(result)
Related
I know how to do this with a while loop and know how to use a for-loop in other languages like Java and C++. I want to use a for-loop in place of where I have written the while loop asking for the user input.
# You are required to use for-loop to solve this and round your answer to 2 decimal places. Write
# a program that takes n ∈ N (i.e., any positive integer including zero) from the user and use the
# input value to compute the sum of the following series:
n = -1
while n < 0:
n = int(input("Enter a value to compute: "))
# keep asking for user input until a whole number (0, 1, 2, 3, etc...) has been entered
k = 0
sum = 0
# To hold the sum of the fraction to be displayed
lastTerm = 0
# This variable represents the last term to be added to the fraction sum before the while loop below terminates
if n == 0:
sum = 0
elif n == 1:
sum = 1
else:
while lastTerm != 1 / n:
lastTerm = (n - k) / (k + 1)
sum = sum + (n - k) / (k + 1)
k += 1
print("{:.2f}".format(sum))
# Print the sum to two decimal places
One option is to catch the exception which is thrown when you cannot convert the input to an int, i.e.
while(True):
try:
# read input and try and covert to integer
n = int(input("Enter a value to compute: "))
# if we get here we got an int but it may be negative
if n < 0:
raise ValueError
# if we get here we have a non-negative integer so exit loop
break
# catch any error thrown by int()
except ValueError:
print("Entered value was not a postive whole number")
Alternative, slightly cleaner but I'm not 100% sure isdigit() will cover all cases
while(true):
n = input("Enter a value to compute: ")
if value.isdigit():
break
else:
print("Entered value was not a postive whole number")
How about this? It uses the for loop and sums all the values in the list.
x=[1,2,3,4] #== test list to keep the for loop going
sum_list=[]
for i in x:
j=float(input("Enter a number: "))
if not j.is_integer() or j<0:
sum_list.append(j)
x.append(1) #=== Add element in list to keep the cyclone going
else:
break
sums=sum(sum_list)
print("The Sum of all the numbers is: ",round(sums,2))
Use this to check for whole numbers -
if num < 0:
# Not a whole number
elif num >= 0:
# A whole number
for a for loop:
import itertools
for _ in itertools.repeat([]): # An infinite for loop
num = input('Enter number : ')
if num < 0:
# Not a whole number
pass # This will ask again
elif num >= 0:
# A whole number
break # break from for loop to continue the program
Easier Way -
mylist = [1]
for i in mylist : # infinite loop
num = int(input('Enter number : '))
if num < 0:
mylist.append(1)
pass # This will ask again
elif num >= 0:
# A whole number
break
i have to write a program with a loop that asks the user to enter a series of positive numbers. the user should enter a negative number to signal the end of the series, and after all positive numbers have been entered, the program should display their sum.
i don't know what to do after this, or whether this is even right (probably isn't):
x = input("numbers: ")
lst = []
for i in x:
if i > 0:
i.insert(lst)
if i < 0:
break
you should use input in the loop to enter the intergers.
lst = []
while True:
x = int(input('numbers:'))
if x > 0:
lst.append(x)
if x < 0:
print(sum(lst))
break
def series():
sum1 = 0
while True:
number = int(input("Choose a number, -1 to quit:"))
if number>=0:
sum1+=number
else:
return sum1
series()
while True means that the algorithm has to keep entering the loop until something breaks it or a value is returned which ends the algorithm.
Therefore, while True keep asking for an integer input , if the given integer is positive or equal to zero, add them to a sum1 , else return this accumulated sum1
You can use a while loop and check this condition constantly.
i, total = 0, 0
while i>=0:
total+=i
i = int(input('enter number:'))
print(total)
Also, don't use:
for loop for tasks you don't know exactly how many times it is going to loop
while loop as while True unless absolutely necessary. It's more prone to errors.
variable names that have the same name as some built-in functions or are reserved in some other ways. The most common ones I see are id, sum & list.
do you want that type of code
sum_=0
while True:
x=int(input())
if x<0:
break
sum_+=x
print(sum_)
Output:
2
0
3
4
5
-1
14
if you want a negative number as a break of input loop
convert string to list; input().split()
convert type from string to int or folat; map(int, input().split())
if you want only sum, it is simple to calculate only sum
x = map(int, input("numbers: ").split())
ans = 0
for i in x:
if i >= 0:
ans += i
if i < 0:
break
print(ans)
I am struggling to write a program that finds the sum of every odd number in a list of 21. this is what I have so far...
sum = 1
numbers = range(1,21,1)
for number in numbers:
if number % 2 == 1;
total += numbers
print(total)
Any help is appreciated.
You can try either already creating a range of odd numbers simply by asking the range to "jump" by 2, starting from 1: 1,3,5,.. and then summing it all:
res = sum(range(1,21,2))
print(res)
>> 100
Or,
create the range, and filter the odd numbers, and then sum it all:
r = range(1,21)
filtered = filter(lambda x: x%2, r)
res = sum(filtered)
#or in 1 line: sum(filter(lambda x: x%2, range(1,21)))
print(res)
>> 100
You had 3 issues:
1) You called on total but never defined it (total+=numbers) while i think you meant to use sum
2) You wrote Total += numbers instead of +=number
3) In this line if number % 2 == 1: you accidentaly used ; instead of :
Here is the fixed code, Enjoy!
EDIT: I want to add that range() is non inclusive, so if you want 21 to be in the list you should use range(1,22,1)
sum = 0
numbers = range(1,21,1)
for number in numbers:
if number % 2 == 1:
sum += number
print(sum)
sum = 0
numbers = range(1,21+1)
for number in numbers:
if number % 2 == 1:
sum += number
print(sum)
or
sum = 0
numbers = range(1,21+1, 2)
for number in numbers:
sum += number
print(sum)
by the way:
range(start, stop, steps) doesn't include stop.
# Imported Modules
import time
import decimal
# Functions
def FindOddNums(a, b):
b = b + 1
for i in range(a, b):
# checks if i / 2 is a float and if float cannot be converted into a int if so than execute below code
if isinstance(i / 2, float) and not float.is_integer(i / 2):
# Check if b is more than 20 if so then no need to wait 1 sec before printing
if b > 20:
print(i)
elif b < 20:
time.sleep(1)
print(i)
def AskWhat():
time.sleep(1)
num1 = input("What first number do you want to check?: ")
time.sleep(1)
num2 = input("What second number do you want to check?: ")
time.sleep(1)
# User input is strings so need to be converted to ints
num1 = int(num1)
num2 = int(num2)
FindOddNums(num1, num2)
if __name__ == '__main__':
AskWhat()
Is this what you're looking for?
This actually calculates the thing but using steps is also a good way to go. But this is another way
I am beginner in programming, So can you please tell me what's wrong with my code?
I want to print next palindrome number if the number entered by the user (n) is not palindrome
n = int(input("Enter any number :- "))
reverse = 0
temp = n
while (n!=0):
reverse = reverse * 10
reverse = reverse + n%10
n=n//10
if(temp==reverse):
print ("Already palindrome:: ")
if(temp != reverse):
new_temp = temp
new_reverse = 0
for i in range(new_temp,new_temp+10):
while(temp != 0):
new_reverse = new_reverse * 10
new_reverse = new_reverse + temp%10
temp = temp//10
if(new_temp==new_reverse):
print ("Next pallindrome is :- ",new_temp)
break
if(new_temp != new_reverse):
temp = new_temp+1
There are two problems with your code.
1) Your "for i in range" loop calculates the reverse of the temp variable, but you don't change the temp variable's value.
You do
new_temp = temp
for i in range(new_temp,new_temp+10):
[SNIP]
if(new_temp != new_reverse):
temp = new_temp+1 #this value never changes.
So you're making 10 iterations with one and the same value.
2) Ten iterations might not be enough to find a palindrome. Keep going until you find a palindrome.
Working code:
def reverse(num):
reverse= 0
while num:
reverse= reverse*10 + num%10
num= num//10
return reverse
num= int(input("Enter any number :- "))
if num==reverse(num):
print ("Already palindrome.")
else:
while True:
num+= 1
if num==reverse(num):
print ("Next palindrome is : %s"%num)
break
To check if a number is a palindrome, you don't need to convert it to a number. In fact, its a lot simpler if you just check the string equivalent of your number.
>>> i = '212'
>>> i == i[::-1]
True
>>> i = '210'
>>> i == i[::-1]
False
Use this to your advantage, and create a function:
def is_palindrome(foo):
return str(foo) == str(foo)[::-1]
Next, to find the next palindrome, simply increment the number till your palindrome check is true.
Combine all that, and you have:
def is_palindrome(n):
return str(n) == str(n)[::-1]
n = raw_input('Enter a number: ')
if is_palindrome(n):
print('Congratulations! {0} is a palindrome.'.format(n))
else:
n1 = n
while not is_palindrome(n1):
n1 = int(n1)+1
print('You entered {0}, but the next palindrome is {1}'.format(n, n1))
Here is how it works:
$ python t.py
Enter a number: 123
You entered 123, but the next palindrome is 131
$ python t.py
Enter a number: 121
Congratulations! 121 is a palindrome.
If it helps, I believe it's possible to solve this problem with n/2 iterations where n is the length of the input number. Here's my solution in Python:
def next_palin_number(number):
number+=1
# Convert the number to a list of its digits.
number = list(str(number))
# Initialize two indices for comparing symmetric digits.
i = 0
j = len(number) - 1
while i < j:
# If the digits are different:
if number[i] != number[j]:
# If the lower-power digit is greater than the higher-power digit:
if int(number[j]) > int(number[i]):
if number[j-1]!='9':
number[j - 1] = str(int(number[j - 1]) + 1)
number[j] = number[i]
else:
number = list(str(int(''.join(number[:j]))+1))+number[j:]
else:
number[j] = number[i]
i += 1
j -= 1
# Concatenate and return the result.
return "".join(number)
This problem has a wonderful number of ways to solve them.
One of them is
def nearest_palindrome(number):
#start writitng your code here
while True:
number+=1
if str(number) == str(number)[::-1]:
return number
number=12300
print(nearest_palindrome(number))
Thanks for your time to read my answer : )
I have written this for finding next pallindrome number given a pallindrome number.
def palindrome(num):
bol=False
#x=len(str(num))
num=num+1
while(bol==False):
if(check_palindrome(num)):
bol=True
else:
num=num+1
return num
def check_palindrome(n):
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
return True
b=palindrome(8)
print(b)
def next_palin_drome(n):
while True:
n+=1
if str(n) == str(n)[::-1]:
return n
n=12231
print(next_palin_drome(n))
output:12321
def nearest_palindrome(number):
for i in range(1,number):
number=number+1
tem=str(number)
tem1=tem[-1::-1]
if(tem==tem1):
return number
else:
continue
number=12997979797979797
print(nearest_palindrome(number))
def nearest_palindrome(number):
n = len(str(number))//2
if(len(str(number)) % 2 == 0):
#number like 1221
number_1 = int((str(number))[:n]) #12
number_2 = int((str(number))[n:]) #21
if(number_1 < number_2):
number_1 += 1
number_2 = int(str(number_1)[::-1])
else:
number_2 = int(str(number_1)[::-1])
# if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(number_1)[::-1]
#combining the both parts
ans = int(str(number_1) + str(number_2))
return ans
else:
#numer like 12510 n=2
nu = int((str(number))[:n+1]) #add in this number
number_1 = int((str(number))[:n]) # 12
number_2 = int((str(number))[n+1:]) # 21
if (number_1 < number_2):
nu += 1
number_2 = int((str(nu))[::-1][1:])
else:
number_2 = int((str(nu))[::-1][1:])
#if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(nu)[::-1]
number_2 = number_2[1:]
#combinning both parts
ans = int(str(nu) + str(number_2))
return ans
number=12331
print(nearest_palindrome(number))
If a definite range is given:
# function to check if the number is a palindrome
def palin(x):
s=str(x)
if s==s[::-1]:
return True
else:
return False
n=int(input("Enter the number"))
# Putting up range from the next number till 15 digits
for i in range(n+1,int(10e14)):
if palin(i) is True:
print(i)
break
A brute force method:
def math(n):
while not var:
n += 1
if str(n) == str(n)[::-1] : f = 'but next is : '+str(n); return f
n = int(input()); t = math(n); print('Yes',t) if str(n) == str(n)[::-1] else print('No',t); global var; var = False
This is a good fast solution. I saw that the other solutions were iterating and checking through every +1 they did, but this is really slow for big numbers.
This solution has O(n) time if you look at the length of the number
beginNumber = 123456789101112131415161718 #insert number here for next palidrome
string = str(beginNumber + 1)
length = len(string)
number= [int(x) for x in list(string)]
for i in range(length//2):
if (number[i] != number[length-1-i]):
if (number[i]<number[length-1-i]):
number[length-2-i] += 1
number[length-1-i] = number[i]
print("".join([str(x) for x in number]))
I have written this for finding next pallindrome number given a pallindrome number..
#given a pallindrome number ..find next pallindrome number
input=999
inputstr=str(input)
inputstr=inputstr
#append 0 in beginning and end of string ..in case like 99 or 9999
inputstr='0'+inputstr+'0'
length=len(inputstr)
halflength=length/2;
#if even length
if(length%2==0):
#take left part and reverse it(which is equal as the right part )
temp=inputstr[:length/2]
temp=temp[::-1]
#take right part of the string ,move towards lsb from msb..If msb is 9 turn it to zero and move ahead
for j,i in enumerate(temp):
#if number is not 9 then increment it and end loop
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now you have right hand side...mirror it and append left and right part
output=temp[::-1]+temp
#if the length is odd
if(length%2!=0 ):
#take the left part with the mid number(if length is 5 take 3 digits
temp=inputstr[:halflength+1]
#reverse it
temp=temp[::-1]
#apply same algoritm as in above
#if 9 then make it 0 and move on
#else increment number and break the loop
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now the msb is the middle element so skip it and copy the rest
temp2=temp[1:]
#this is the right part mirror it to get left part then left+middle+right isoutput
temp2=temp2[::-1]
output=temp2+temp
print(output)
similarly for this problem take the left part of given number ...reverse it..store it in temp
inputstr=str(number)
if(inputstr==inputstr[::-1])
print("Pallindrome")
else:
temp=inputstr[:length/2]
temp=temp[::-1]
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
now depending on length of your number odd or even generate the output..as in the code
if even then output=temp[::-1]+temp
if odd then temp2=temp1[1:]
output=temp2[::-1]+temp
I am not sure about this solution..but hope it helps
I want to write a program that can calculate the sum of an integer as well as count its digits . It will keep doing this until it becomes a one digit number.
For example, if I input 453 then its sum will be 12 and digit 3.
Then it will calculate the sum of 12=1+2=3 it will keep doing this until it becomes one digit. I did the first part but i could not able to run it continuously using While . any help will be appreciated.
def main():
Sum = 0
m = 0
n = input("Please enter an interger: ")
numList = list(n)
count = len(numList)
for i in numList:
m = int(i)
Sum = m+Sum
print(Sum)
print(count)
main()
It is not the most efficient way, but it doesn't matter much here; to me, this is a problem to elegantly solve by recursion :)
def sum_digits(n):
n = str(n)
if int(n) < 10:
return n
else:
count = 0
for c in n:
count += int(c)
return sum_digits(count)
print sum_digits(123456789) # --> 9 # a string
A little harder to read:
def sum_digits2(n):
if n < 10:
return n
else:
return sum_digits2(sum(int(c) for c in str(n))) # this one returns an int
There are a couple of tricky things to watch out for. Hopefully this code gets you going in the right direction. You need to have a conditional for while on the number of digits remaining in your sum. The other thing is that you need to covert back and forth between strings and ints. I have fixed the while loop here, but the string <-> int problem remains. Good luck!
def main():
count = 9999
Sum = 0
m = 0
n = input("Please enter an integer: ")
numList = list(n)
while count > 1:
count = len(numList)
for i in numList:
m = int(i)
Sum = m+Sum
print(Sum)
print(count)
# The following needs to be filled in.
numlist = ???
main()
You can do this without repeated string parsing:
import math
x = 105 # or get from int(input(...))
count = 1 + int(math.log10(x))
while x >= 10:
sum = 0
for i in xrange(count):
sum += x % 10
x /= 10
x = sum
At the end, x will be a single-digit number as described, and count is the number of original digits.
I would like to give credit to this stackoverflow question for a succinct way to sum up digits of a number, and the answers above for giving you some insight to the solution.
Here is the code I wrote, with functions and all. Ideally you should be able to reuse functions, and here the function digit_sum(input_number) is being used over and over until the size of the return value (ie: length, if sum_of_digits is read as a string) is 1. Now you can use the while loop to keep checking till the size is what you want, and then abort.
def digit_sum(input_number):
return sum(int(digit) for digit in str(input_number))
input_number = input("Please enter a number: ")
sum_of_digits = digit_sum(input_number)
while(len(str(sum_of_digits)) > 1):
sum_of_digits = digit_sum(input_number)
output = 'Sum of digits of ' + str(input_number) + ' is ' + str(sum_of_digits)
print output
input_number = sum_of_digits
this is using recursive functions
def sumo(n):
sumof = 0
while n > 0:
r = n%10 #last digit
n = n/10 # quotient
sumof += r #add to sum
if sumof/10 == 0: # if no of digits in sum is only 1, then return
return sumof
elif sumof/10 > 0: #else call the function on the sumof
sumo(sumof)
Probably the first temptation would be to write
while x > 9:
x = sum(map(int, str(x)))
that literally means "until there is only one digit replace x by the sum of its digits".
From a performance point of view however one should note that computing the digits of a number is a complex operation because Python (and computers in general) store numbers in binary form and each digit in theory requires a modulo 10 operation to be extracted.
Thus if the input is not a string to begin with you can reduce the number of computations noting that if we're interested in the final sum (and not in the result of intermediate passes) it doesn't really matter the order in which the digits are summed, therefore one could compute the result directly, without converting the number to string first and at each "pass"
while x > 9:
x = x // 10 + x % 10
this costs, from a mathematical point of view, about the same of just converting a number to string.
Moreover instead of working out just one digit however one could also works in bigger chunks, still using maths and not doing the conversion to string, for example with
while x > 99999999:
x = x // 100000000 + x % 100000000
while x > 9999:
x = x // 10000 + x % 10000
while x > 99:
x = x // 100 + x % 100
while x > 9:
x = x // 10 + x % 10
The first loop works 8 digits at a time, the second 4 at a time, the third two and the last works one digit at a time. Also it could make sense to convert the intermediate levels to if instead of while because most often after processing n digits at a time the result will have n or less digits, leaving while loops only for first and last phases.
Note that however the computation at this point is so fast that Python general overhead becomes the most important part and thus not much more can be gained.
You could define a function to find the sum and keep updating the argument to be the most recent sum until you hit one digit.
def splitSum(num):
Sum = 0
for i in str(num):
m = int(i)
Sum = Sum + m
return str(Sum)
n = input("Please enter an integer: ")
count = 0
while count != 1:
Sum = splitSum(n)
count = len(Sum)
print(Sum)
print(count)
n = Sum