-3
def punctuation(x,y):
 if len(x) == 0:
     return y

 if '.' in x[0]:
     x[1] = x[1].capitalize()
     return punctuation(x[1:],y.append(x[0]))
 elif '!' in x[0]:
     x[1] = x[1].capitalize()
     return punctuation(x[1:],y.append(x[0]))
 elif '?' in x[0]:
     x[1] = x[1].capitalize()
     return punctuation(x[1:],y.append(x[1]))
 else:
     return punctuation(x[1:],x[0])


 z = ['!a','b'] 
 punctuation(z,[])

希望得到 ['!a','b'] ,这意味着如果第一项包含 (!,?,.),则第二项变为大写

Q3_p1 = "Enter the digit on the phone (0-9): "
Q3_p2 = "Enter the number of key presses (>0): "



def enter_msg(n):
    x=raw_input(Q3_p1)
    y=raw_input(Q3_p1)
    Jay = Jay_chou(x,y)
    return Jay

 def Jay_chou(d,n):

     if d==0: return " " 
     elif d==1: return [".", ",", "?"][n%3-1]
     elif d==2: return ["a", "b", "c"][n%3-1]
     elif d==3: return ["d", "e", "f"][n%3-1]
     elif d==4: return ["g", "h", "i"][n%3-1]
     elif d==5: return ["j", "k", "l"][n%3-1]
     elif d==6: return ["m", "n", "o"][n%3-1]
     elif d==7: return ["p", "q", "r", "s"][n%4-1]
     elif d==8: return ["t", "u", "v"][n%3-1]
     else: return ["w", "x", "y", "z"][n%4-1]


 enter_msg(2)

我不知道为什么我看到这个错误:

Enter the digit on the phone (0-9): 1

Enter the digit on the phone (0-9): 1

['1', '1']

TypeError: not all arguments converted during string formatting
4

2 回答 2

1

对于第二个问题:

你将字符串传递给Jay_Chou()in Jay = Jay_chou(x,y),而不是你应该传递整数。在您的情况下,该n%3部分实际上尝试进行字符串格式化而不是模数运算。

raw_input()返回字符串,您需要使用将它们转换为整数int()

所以你得到这个错误:

In [13]: '1'%3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-39edc619f812> in <module>()
----> 1 '1'%3

TypeError: not all arguments converted during string formatting

尝试这个:

Jay = Jay_chou(int(x),int(y))

然后它输出:

Enter the digit on the phone (0-9): 3
Enter the digit on the phone (0-9): 4
d

#and for 1,1:

Enter the digit on the phone (0-9): 1
Enter the digit on the phone (0-9): 1
.
于 2012-11-05T08:58:48.607 回答
0

对于第一个问题,您可以执行以下操作:

import itertools as it
the_list = ['a!', 'b']
result = [the_list[0]]
my_iter = iter(the_list)
next(my_iter)   #my_iter.next() for python2

for i,(a,b) in enumerate(it.izip(the_list, my_iter)):
    if set('.?!').intersection(a):
        result.append(b.capitalize())
    else:
        result.append(b)

您的代码中的问题是您调用:

punctuation(x, y.append(something))

append方法返回None,因此递归调用的第二个参数类型错误。

你必须这样做:

y.append(something)
punctuation(x, y)
于 2012-11-05T09:07:14.857 回答