while adding two numbers, I want to check how many times carry is occurring –
for eg:
Input
Num 1: 451
Num 2: 349
Output
2
Explanation:
Adding ‘num 1’ and ‘num 2’ right-to-left results in 2 carries since ( 1+9) is 10. 1 is carried and (5+4=1) is 10, again 1 is carried. Hence 2 is returned.
def NumberOfCarries(num1, num2):
count = 0
l = str(num1)
i = 0
if i <= len(l):
n = num1 % 10
n2 = num2 % 10
sum = n + n2
print(f" num is {num1} and {num2} n1 is {n} and n2 is {n2} and sum is {sum}")
if sum > 9:
count += 1
num1 = num1 // 10
num2 = num2 // 10
i += 1
else:
num1 = num1 // 10
num2 = num2 // 10
i += 1
return count
num1 = int(input("> "))
num2 = int(input("> "))
print(NumberOfCarries(num1, num2))
Here loop is not working, only one time the sum is generating. I want to generate for each number in numb1. I tired with while, if and for. Please help me.I am new to this
I think you tried to do this:
def number_of_carries(num1, num2):
amplitude_num1 = len(str(num1))
amplitude_num2 = len(str(num2))
count = 0
i = 0
carry_over = 0
while i < amplitude_num1 or i < amplitude_num2:
n = num1 % 10
n2 = num2 % 10
sum_of_digits = n + n2 + carry_over
print(f" num is {num1} and {num2}, n1 is {n} and n2 is {n2}, carry digit from previous addition is {carry_over}, sum is {sum_of_digits}")
if sum_of_digits > 9:
count += 1
carry_over = 1
else:
carry_over = 0
num1 //= 10
num2 //= 10
i += 1
return count
num1 = int(input("> "))
num2 = int(input("> "))
print(number_of_carries(num1, num2))
But if you want to have a solution that would accept more that 2 numbers this could be modified to:
def number_of_carries(numbers):
amplitude = max(len(str(x)) for x in numbers)
count = 0
i = 0
carry_over = 0
for i in range(amplitude):
current_numbers = tuple(x % 10 for x in numbers)
sum_of_digits = sum(current_numbers) + carry_over
print(
f" numbers are {' '.join(str(x) for x in numbers)}, "
f"current_numbers are {' '.join(str(x) for x in current_numbers)}, "
f"carry digit from previous addition is {carry_over}, sum is {sum_of_digits}"
)
if sum_of_digits > 9:
count += 1
carry_over = sum_of_digits // 10
numbers = tuple(x // 10 for x in numbers)
return count
input_numbers = (198, 2583, 35)
print(number_of_carries(input_numbers))
Related
Hello everyone i am a new to programming and i have a small problem in the code, i need to get the average of the sum i already made the sum of digits and here is the code:
num = int(input("Enter a number\n"))
r = 0
m = 0
while num != 0:
m = num % 10
r = r + m
num = int(num / 10)
print(f"The sum of all digits is {result} and the average is")
i need the average but i dont know how to get it( for example in the num i added 5555, 5+5+5+5 = 20) how would i get the average and thanks
i tried to do r / m but also didnt work
This is the short solution:
num = input("Enter a number\n")
s = sum([int(x) for x in num])
a = s / len(num)
print(f"The sum of all digits is {s} and the average is {a}")
Also, this is the fixed version of your code:
num = int(input("Enter a number\n"))
r = 0
m = 0
t = 0
while num != 0:
m = num % 10
r = r + m
num = int(num / 10)
t = t + 1
print(f"The sum of all digits is {r} and the average is {r/t}")
n_str = input("Enter numbers by gaps: ")
n = [float(num) for num in n_str.split()]
summ = 0
for i in n:
summ = summ + i
print("Average of ", n, " is ", summ / len(n))
So I could print out the odd numbers. However, the output isn't what i want. It should look like 1+3+5+7 = 16 but I could not make it into a single line.
I couldn't figure out how to extract the values from the while loop as with my method it only gives the latest odd number which is 7 while 1,3 and 5 could not be taken out
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
odd = (str(oddNum))
print (odd)
total = total + oddNum
oddNum = oddNum + 2
count += 1
print (odd + "=" + str(total))
#output will be:
'''
1
3
5
7
7=16
but it should look like 1+3+5+7=16
'''
An alternative method would be the use of:
range() method to generate the list of odd numbers
.join() method to stitch the odd numbers together (eg. 1+3+5+7)
f-strings to print odds together with the total = sum(odd_nums)
Code:
num = int(input("Insert a postive integer:")) #4
odd_nums = range(1, num * 2, 2)
sum_nums = "+".join(map(str, odd_nums))
print(f"{sum_nums}={sum(odd_nums)}")
Output:
1+3+5+7=16
Note:
Same but using two lines of code:
num = int(input("Insert a postive integer:")) #4
print(f"{'+'.join(map(str, range(1, num * 2, 2)))}={sum(range(1, num * 2, 2))}")
Output:
1+3+5+7=16
You are not storing old oddNum values in odd. With minimal changes can be fixed like this:
num = int(input("Insert a positive integer:"))
oddNum = 1
total = 0
count = 1
odd = ""
while count <= num:
total = total + oddNum
odd += f"{oddNum}"
oddNum = oddNum + 2
count += 1
odd = "+".join(odd)
print(odd + "=" + str(total))
There are a few options, you can either create a string during the loop and print that at the end, or create a list and transform that into a string at the end, or python3 has the ability to modify the default end of line with print(oddNum, end='').
Using a string:
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
sequence = ''
while count <= num:
sequence += ("+" if sequence != "" else "") + str(oddNum)
total = total + oddNum
oddNum = oddNum + 2
count += 1
print (sequence + "=" + str(total))
Using print:
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
if count != 1:
print('+', end='')
print (oddNum, end='')
total = total + oddNum
oddNum = oddNum + 2
count += 1
print ("=" + str(total))
Alternatively using walrus (:=), range,print, sep, and end:
print(*(odd:=[*range(1,int(input('Insert a postive integer:'))*2,2)]),sep='+',end='=');print(sum(odd))
# Insert a postive integer:4
# 1+3+5+7=16
I'm trying to add up all the number from 1 to N and print the result and then keep asking the user to enter number till the number zero is entered. I can make it sum the numbers and end the while but can't make it keep asking for more numbers like this: https://pastebin.com/9pWDT6su
num = int(input('N: '))
sum = 0
while num != 0:
while num < 0:
num = int(input('ERROR - N: '))
sum = sum + num
num = num - 1
print('Sum: ', sum)
# If I put this outside the WHILE it'll work but it won't allow me to
# keep adding numbers
num = int(input('N: '))
print('END')
Try this :
num = int(input('N: '))
while num != 0:
sum=0
while num > 0:
sum = sum + num
num = num - 1
print('Sum: ', sum)
num = int(input('N: '))
print('END')
If you want the sum of 1-n for all numbers remove sum=0 inside while
Try this:
num = int(input('N: '))
sum_ = 0
while True:
if num < 0:
num = int(input('ERROR - N: '))
elif num == 0:
break
else:
sum_ = sum_ + num
print('Sum: ', sum_)
num = int(input('N: '))
def even_divide_count(num1, num2):
y = 0
number = num1 // num2
if number % 2 == 1 or number == 0:
return 0
else:
even_divide_count(number, num2)
y += 1
return y
I apologize because this is the first question I'm asking on stack overflow so apologizes for the formatting. I'm attempting to maintain the value for the variable y through recursion however the maximum value I get when y is returned is 1 as it doesn't end up adding all the y values through levels of incursion. Any help is greatly appreciated!
*updated because I forgot a line
def even_divide_count(num1, num2):
y = 0
number = num1 // num2
if number % 2 == 1 or number == 0:
return 0
else:
1 + even_divide_count(number, num2)
y += 1
return y
*found my answer, it's posted above
This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number