I have attempted this problem like this :
a = input("Enter number : ")
s = 3
w = 1
while a>0:
digit=a%10
if n%2 == 0:
p = p*digit
else:
s = s+digit
a=a/10
n=n+1
print "The sum is",s
it works perfectly for even no of digits but for odd no of digits like for 234 it shows the sum as 6 and product 3
No explicit loop:
import operator
from functools import reduce # in Python 3 reduce is part of functools
a = input("Enter number : ")
lst = [int(digit) for digit in a]
add = sum(lst[1::2])
mul = reduce(operator.mul, lst[::2],1)
print("add =",add,"mul =",mul,"result =",add+mul)
Producing:
Enter number : 234
add = 3 mul = 8 result = 11
You have to start with n = 0 for this to work
a = int(input("Enter number"))
s = 0
p = 1
n = 0
while a>0:
digit=a%10
if n%2 == 0:
p *= digit
else:
s += digit
a /= 10
n += 1
print "The sum is",s
print "Product is",p
Easy mistake to make about the numbering. The first item of any string, list or array is always index 0. For example, be careful in future to take away 1 from the value returned from len(list) if you are iterating through a list's items with a for loop e.g.
for x in range(len(list)-1):
#your code using list[x]
Here's the mathematical version:
n = input('Enter a number: ')
digits = []
while n > 0:
digits.append(n%10)
n //= 10
s = 0
p = 1
i = 0
for digit in reversed(digits):
if i%2 == 0:
s += digit
else:
p *= digit
i += 1
print 'Sum of even digits:', s
print 'Product of odd digits:', p
print 'Answer:', s+p
I have tried to make this as simple as possible for you.
Here's a function that does the same thing:
def foo(n):
s = 0
p = 1
for i, digit in enumerate(str(n)):
if i%2 == 0:
s += digit
else:
p *= digit
return s+p
def foo(num):
lst = [int(digit) for digit in str(num)]
mul, add = 1, 0
for idx, val in enumerate(lst):
if not idx % 2:
mul *= val
else:
add += val
return add, mul
And using it:
>>> foo(1234)
(6, 3)
>>> foo(234)
(3, 8)
This function will take an integer or a string representation of an integer and split it into a list of ints. It will then use enumerate to iterate over the list and preform the required operations. It returns a 2 element tuple.
Related
I want to print the digits of an integer in order, and I don't want to convert to string. I was trying to find the number of digits in given integer input and then divide the number to 10 ** (count-1), so for example 1234 becomes 1.234 and I can print out the "1". now when I want to move to second digit it gets confusing. Here is my code so far:
Note: Please consider that I can only work with integers and I am not allowed to use string and string operations.
def get_number():
while True:
try:
a = int(input("Enter a number: "))
return a
except:
print("\nInvalid input. Try again. ")
def digit_counter(a):
count=0
while a > 0:
count = count+1
a = a // 10
return count
def digit_printer(a, count):
while a != 0:
print (a // (10 ** (count-1)))
a = a // 10
a = get_number()
count = digit_counter(a)
digit_printer(a, count)
I want the output for an integer like 1234 as below:
1
2
3
4
Using modulo to collect the digits in reversed order and then print them out:
n = 1234
digits = []
while n > 0:
digits.append(n%10)
n //=10
for i in reversed(digits):
print(i)
Recursive tricks:
def rec(n):
if n > 0:
rec(n//10)
print(n%10)
rec(1234)
Finding the largest power of 10 needed, then going back down:
n = 1234
d = 1
while d * 10 <= n:
d *= 10
while d:
print(n // d % 10)
d //= 10
def solution(l):
for x in (range(len(l))):
sum_l = sum(l)
num = l[x]
y = sum_l%3
l.sort()
if len(l) == 1 and l[0]%3 != 0:
return 0
elif ((num%3) == y and y != 0) :
l.remove(num)
l.sort(reverse=True)
strings = [str(number) for number in l]
l_string = ''.join(strings)
l_int = int(l_string)
return l_int
elif y == 0:
l.sort(reverse=True)
strings = [str(number) for number in l]
l_string = ''.join(strings)
l_int = int(l_string)
return l_int
else:
return 0
Here is the code. Basically, I am asked to find the largest number that can be made by the integers in the list divisible by 3. It passes all the test cases except one (blind case), and I have literally no idea what the issue is. I've tried every possible type of list, meaning, 1 digit, 2 digits, etc. The list can have numbers 0-9, with 1-9 numbers in it. Can I get some help as to what I might be missing?
Here is how you can find the largest number that can be made by the integers in the list divisible by 3:
from itertools import permutations
def solution(l):
p1 = [s for i in range(2,len(l)+1) for s in permutations(l,i)] # List of tuples with all possible combinations of numbers
p2 = [str(t) for t in p1 if not sum(t)%3] # List of tuples with elements adding together divisable by 3
return int(''.join([n for n in max(p2) if n.isdigit()])) # Return greatest tuple converted to number form
print(solution([4,6,9,1,3,3,2,4]))
Output:
9644331
The best way to find whether a number is divisible by 3 with only its digits is by adding up all the digits. If the answer is divisible by three, then so is any number made up of the combination of all the digits.
from itertools import permutations
def solution(l):
if not l:
return 0
if len(l) == 1 and l[0] % 3 == 0:
return l[0]
if len(l) == 1 and l[0] % 3 != 0:
return 0
p1 = [s for i in range(2, len(l) + 1) for s in
permutations(l, i)]
p2 = []
for each in p1:
num = ""
for i in each:
num += str(i)
if int(num) % 3 == 0:
p2.append(int(num))
x = sorted(list(set(p2)))
ans = 0
if len(x) != 0:
ans = max(x)
if ans != 0:
return ans
return 0
def cozum(list):
a=[]
for i in range(1,len(list)):
p = permutations(list,i)
for pe in p:
a.append(pe)
toplamlar=[ tup for tup in a if sum(tup)%3 == 0 ]
if toplamlar:
res = max([ int(''.join(map(str, sayi))) for sayi in toplamlar])
return res
else:
return "No number divisible by 3"
Trying to make a function which detects the the middle digit of an odd number is 0 and returns True if it is, otherwise False. I really want to get this function to work without converting the integer to a string first.
This is what I have so far:
def test(n):
n = str(n)
if len(n) % 2 == 0:
return False
else:
left_side = n[:len(n)//2]
right_side = n[(len(n)//2):]
if right_side[:1] == "0" and ((not "0" in left_side)and (not "0" in right_side[2:])):
return True
else:
return False
print (test(0)) # True
print (test(101)) # True
print (test(123)) # False
print (test(21031)) # True
n = 12345
digits = []
while n:
digit = n % 10
digits.append(digit)
n //= 10
digit_count = len(digits)
if digit_count % 2:
middle = digit_count // 2
print(digits[middle])
Output:
3
Alternatively, using math.log10:
from math import log10
n = 12345
digit_count = int(log10(n)) + 1
middle = digit_count // 2
print(n // 10 ** middle % 10)
See these two answers:
Length of an integer in Python
How to take the nth digit of a number in python
this should do it. it does convert it to a string, but honestly it's faster, easier, and just more efficient.
num = int(input("number too test: "))
def test(number):
num_len = len(str(number))
print(num_len)
if num_len % 2 == 0:
return False
else:
number = str(number)
half = int((num_len-1)/2)
print(number[half])
if int(number[half]) is 0:
return True
else:
return False
test(num)
Not that it will make much difference in terms of performance, but you can use the log function to compute the number of zeros in a number and remove the rightmost half by dividing to the correct power of 10. For example:
import math
def test(n):
if n == 0:
return True
digits = math.ceil(math.log(n + 1, 10)) - 1
return digits % 2 == 0 and not (n // 10**(digits / 2) % 10)
I am trying to use the modulo operator in this function that prints the highest even number in a list, but I always get this error:
TypeError: not all arguments converted during string formatting
Code:
def largest_even():
"""
-------------------------------------------------------
Returns the largest even number.
Use: result = largest_even()
-------------------------------------------------------
Preconditions:
Postconditions:
returns
result - largest even number
-------------------------------------------------------
"""
num = int(input('Enter a number:'))
n_list = []
while num != "":
n_list.append(num)
num = input('Next number:')
print(n_list)
n = 0
e_list = []
while n < len(n_list):
a = (n_list[n]) % 2
if a == 0:
e_list.append(n_list[n])
n = n + 1
print(n)
print(e_list)
if len(e_list) == 0:
result = 'False'
result = e_list[0]
n = 0
while n < len(e_list):
if e_list[n] > result:
result = e_list[n]
print("{} is the largest even number in that list.".format(result))
You only add one number to the list; inside the loop, you are adding strings.
num = input('Enter a number:')
n_list = []
while num != "":
n_list.append(int(num))
num = input('Next number:')
Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum 2+3+4+5 = 14 which is not a single digit so repeat with 1+4 = 5 which is a single digit.
This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another while statement
n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
this is a sample output of the code
Input an integer: 98765678912398
8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88
8 + 8 = 16
1 + 6 = 7
This should work, no division involved.
n = int(input("Input an integer:"))
while n > 9:
n = sum(map(int, str(n)))
print(n)
It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.
You could utilize recursion.
Try this:
def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
if s > 9:
return sum_of_digits(s)
return s
n = int(input("Enter an integer: "))
print(sum_of_digits(n))
you can try this solution,
if n=98 then your output will be 8
def repitative_sum(n):
j=2
while j!=1:
n=str(n)
j=len(n)
n=list(map(int,n))
n=sum(n)
print(n)
You don't need to convert your integer to a float here; just use the divmod() function in a loop:
def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
return newnum
By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:
n = int(input("Input an integer:"))
while n > 9:
n = sum_digits(n)
print(n)
def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
A simple, elegant solution.
I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.
n = int(input("Input an integer:"))
def sum_int(num):
numArr = map(int,str(num))
number = sum(numArr)
if number < 10:
print(number)
else:
sum_int(number)
sum_int(n)
Again I am unsure about the recursion within a function in Python, but hey, it works :)
If you like recursion, and you must:
>>> def sum_digits_rec(integ):
if integ <= 9:
return integ
res = sum(divmod(integ, 10))
return sum_digits(res)
>>> print(sum_digits_rec(98765678912398))
7
def digit_sum(num):
if num < 10:
return num
last_digit = num % 10
num = num / 10
return digit_sum(last_digit + digit_sum(num))
input_num = int(input("Enter an integer: "))
print("result : ",digit_sum(input_num))
This may help you..!
Try with strings comprehension:
new = input("insert your number: ")
new = new.replace(" ","")
new =sum([int(i) for i in new])
if new not in range (10):
new = str(new)
new = sum ([int(i) for i in new])
print (new)
Note that the answers which convert int to str are relying on the python conversion logic to do internally the divmod calculations that we can do explicitly as follows, without introducing the non-numeric string type into an intrinsically numerical calculation:
def boilItDown(n):
while n >= 10:
t = 0
while n:
d, m = divmod(n, 10)
n, t = d, t + m
n = t
return n
n = 98765678912398
print(boilItDown(n))
Output:
7