返回字符串,并从功能
我呼吁item_order(顺序)计算,以字符数,然后一个函数int应该回报是这样的:返回字符串,并从功能
'Letter a: number of letter a letter b: number of letter b'
但我得到一个错误,说我不能连接str和int。 如何返回str和int?
这是代码(我使用python):
def item_order(order):
'''
order is a string containing words for the items a customer can order
returns the number of times each word is listed
with this format : name : number of times it is listed
'''
s=0
h=0
w=0
for char in order:
if char=='s':
s=s+1
if char=='h':
h=h+1
if char=='w':
w=w+1
answer='salad:', s 'hamburger:' h 'water:' w
return answer
当我调用该函数与这种说法('salad, salad, hamburger, water')
我希望它返回此:
'salad:2 hamburger:1 water:1'
我能找到正确的每个单词列出的次数,但不能用上述格式返回。
从你所提到的要求
基本上,我相信你可以尝试像这样在C#:
static string OrderInfo(string order)
{
int len = order.Length; int count;
StringBuilder builder = new StringBuilder();
for(int i=0;i<len;i++)
{
count = 0;
char toSearch = order[i];
foreach(char c in order)
{
if (c == toSearch)
count++;
}
builder.Append("Letter " + order[i] + ": " + count);
}
return builder.ToString();
}
注:这将包括repetitve信也。
的format
字符串的方法适用于这样的任务:
return 'salad: {} hamburger: {} water: {}'.format(s, h, w)
无关:您的计数的代码是脆弱的。它碰巧能正确地使用这个数据集 ,因为字母shw
只在 每个字符中出现一次。但是,如果您添加了一个字词,如'milkshake'
,则此代码在每次出现时都会计入一次额外的s
和h
。
一个更好的办法是分割字符串成的话,再看看每个 第一个字母:
for word in order.split():
char = word[0]
if char == 's':
etc.
更强大的是来算的话本身并返回一个 dict
,但当你得到字典时,我会把它留给你;它看起来像你刚刚从Python开始的 。
我意识到计算代码很弱,但没关系,因为只有沙拉,汉堡和水是允许的。 – Cosimo
@科西莫好吧。我希望这十行不相干的东西不会让你忽略回答你问题的两条线:) –
请提供代码片段。 –
你使用什么编程语言? –
请提供说明您的问题的[最低,完整示例](http://stackoverflow.com/help/mcve)。 – Sam