即使位于数字的乘积的总和 [英] sum of the product of even positioned digits

查看:125
本文介绍了即使位于数字的乘积的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图像这样这个问题:

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 

它完美的作品,即使数字不但是对于数字奇没有像234它显示的总和为6和产品3

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

推荐答案

没有的明确的循环:

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)

产地:

Enter number : 234
add = 3 mul = 8 result = 11

这篇关于即使位于数字的乘积的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆