Python:每日一题 78(答题领鱼币)
哈哈哈,我觉得这道题特别有意思~
求平均数任务:请你编写一个函数average_string(),这个函数可以接受一个字符串,这个字符串中都是英文数字,我们要通过一系列高端操作来得到英文字符串的平均数。注意:数字的范围是0到9,如果字符串中有超过这个范围的数字或者其他字符串,就返回'n / a'
例子:
average_string('one three two')
>>>two
average_string('five five five')
>>>five
average_string('ku fthj two')
>>>'n / a'
楼主解法:
**** Hidden Message *****
大神解法:
**** Hidden Message ***** 看看大神 本帖最后由 shinemic 于 2017-8-13 13:26 编辑
def average_string(s):
num_map = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4,
'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}
try:
out =sum( for x in s.strip().split(' ')]) / len(s.strip().split(' '))
return for x in num_map.items() if out == x]
except KeyError:
return 'n / a'
感谢@chunchun2017 的提醒,把上面不符题意的代码改成6楼所示 明明可以用列表却非要用字典{:10_247:} 最简单的写法,英文1-10以内
def average_string(string):
dic=dict(zip(('one','two','three','four','five','six','seven','eight','nine','ten'),range(1,11)))
lst=string.split(' ')
res=0
for i in lst:
tmp=dic.get(i,0)
if not tmp: return 'n/a'
res+=tmp
return res/len(lst)
print(average_string('one two three')) 本帖最后由 shinemic 于 2017-8-13 13:24 编辑
def average_string(s):
num_en = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
de_str = s.strip().split(' ')
return num_en) / len(de_str))] if \
all(item in num_en for item in de_str) and \
(sum() % len(de_str) == 0) else 'n / a' 大佬太看的起我了{:10_298:}继续跟着甲鱼哥走起~ shinemic 发表于 2017-8-13 09:43
大佬太看的起我了继续跟着甲鱼哥走起~
大神,列表推导式怎么如此熟练 jerryxjr1220 发表于 2017-8-13 09:35
最简单的写法,英文1-10以内
真要简化成一行输出都可以,只不过对于新手来说,还是先从理解程序逻辑开始比较好,基础打扎实再看简化方法。 # -*- coding: utf-8 -*-
def average_string(s):
num_map = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4,
'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}
try:
value=sum( for x in s.split()])/len(s.split())
new_map={v:k for k,v in num_map.items()}
return new_map
except KeyError:
return 'n/a'
s='one three two'
print(average_string(s)) 新手·ing 发表于 2017-8-13 09:45
大神,列表推导式怎么如此熟练
其实是先写for循环。。然后逐步压缩成列表推导式的{:10_263:} 简化成一行代码:
average_string=lambda string:'n/a' if sum()>=99999999 else sum()/len(string.split(' '))
print(average_string('one two three')) jerryxjr1220 发表于 2017-8-13 10:12
简化成一行代码:
{:10_275:} def average_string(mystr):
mystr=mystr.strip();#去掉前后空格
mystr=mystr+' '
mydata=['zero','one','two','three','four','five','six','seven','eight','nine']
All=0
count=0
mystrbeg=0
mystrend=0
oneword=''
while mystrbeg<len(mystr)-1:
mystrend=mystr.find(' ',mystrbeg)
oneword=mystr
if oneword not in mydata:
#end def
return 'n/a'
All+=mydata.index(oneword)
count+=1
mystrbeg=mystrend+1
return mydata
本帖最后由 sdsd 于 2017-8-13 12:24 编辑
def average_string(s):
tran_ed={'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6, 'seven':7,'eight':8,'nine':9}
lists=s.split(' ')
sum_=0
i=0
stri_=['zero','one','two','three','four','five','six','seven','eight','nine']
for lis in lists:
if lis not in stri_:
return 'n/a'
break
else:
sum_=sum_+tran_ed
i=i+1
return stri_
本帖最后由 hhhhhq 于 2017-8-13 12:41 编辑
python2写的def average_string(str1):
m = {'zero': '0',
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',}
M = {0:'zero',
1:'one',
2:'two',
3:'three',
4:'four',
5:'five',
6:'six',
7:'seven',
8:'eight',
9:'nine',}
sum = 0
list = ''
list = str1.split()
n = len(list)
for number in list:
sum += int(m)
average = M
print average
try函数还没学。。 def average_string(s):
digit = ['zero','one','two','three','four','five','six','seven','eight','nine']
lst =
return digit if len(lst) == len(s.split()) else 'N/A'
shinemic 发表于 2017-8-13 09:16
这段代码返回的是数字,而题目要求返回数字对应的英文 本帖最后由 chunchun2017 于 2017-8-13 12:47 编辑
def average_string(s):
list1 = ['zero','one','two','three','four','five','six','seven','eight','nine']
sum = 0
flag = 'n/a'
if (set(list1)>=set(s.split())):
for each in s.split():
sum += list1.index(each)
if(sum%len(s.split())==0): #考虑几个数的平均数不是整数的情况,如果几个数的平均数不是整数(比如:1,3,4)则同样返回n/a
flag = list1[(sum//len(s.split()))]
return flag
str0 = input("请输入一个字符串,以空格作为间隔(如:... ...):")
print(average_string(str0))
运行结果:
请输入一个字符串,以空格作为间隔:(如:... ...)one two three
two
>>>
============== RESTART: C:\Users\78.py ==============
请输入一个字符串,以空格作为间隔:(如:... ...)one aaa two
n/a
>>>
============== RESTART: C:\Users\78.py ==============
请输入一个字符串,以空格作为间隔:(如:... ...)one four two
n/a 本帖最后由 Ss_wW 于 2017-8-13 13:47 编辑
def average_string(string):
'''return the average of numbers in a string,
where numbers are in the form of english word, instead of digits'''
dict1={'zero':0,'one':0,'two':0,'three':0,'four':0,
'five':0,'six':0,'seven':0,'eight':0,'nine':0}
dict2={'zero':0,'one':1,'two':2,'three':3,'four':4,
'five':5,'six':6,'seven':7,'eight':8,'nine':9}
flag=True
list1=string.split()
for each in list1:
if each not in dict1:
falg=False
return 'n/a'
else:
dict1+=1
# print('dict1\n',dict1)
sumvalue=(dict1['zero']*0+dict1['one']*1+dict1['two']*2
+dict1['three']*3+dict1['four']*4+dict1['five']*5
+dict1['six']*6+dict1['seven']*7+dict1['eight']*8
+dict1['nine']*9)
# Python会将 圆括号,中括号和花括号中的行隐式的连接起来
# print('sumvalue\n',sumvalue)
items=sum(dict1.values())
#print('items\n',items)
average=sumvalue/items
#print('average\n',average)
def num2english(s):
s_list=list(s)
for i in range(len(s_list)):
for each2 in dict2:
if dict2==int(s_list):
s_list=each2
break
s_string=''
for each in s_list:
s_string=s_string+' '+each
s_string=s_string.strip()
return s_string
string2=str(average)
list2=string2.split('.')
integral=num2english(list2)
fractional=''
length=len(list2)
if length==2:
fractional=' point '+num2english(list2)
if fractional==' point zero':
fractional=''
string3=integral+fractional
return string3
return dict1
print(average_string('ten'),end='\n\n')
print(average_string('one two three'),end='\n\n')
print(average_string('five five five'),end='\n\n')
print(average_string('three five five'),end='\n\n')
print(average_string('one two three five'),end='\n\n')