Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return string and int from a function

I have a function called item_order (order) that counts the number of char in order and then should returns something like this:

'Letter a: number of letter a letter b: number of letter b'

But I get an error saying I cannot concatenate str and int. How do I return str and int?

This is the code (I am using 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 

When I call the function with this argument ('salad, salad, hamburger, water') I want it to return this:

'salad:2 hamburger:1 water:1'

I can correctly find the number of times each word is listed but I cannot return it with the above format.

like image 972
Cosimo Avatar asked Jul 19 '26 14:07

Cosimo


1 Answers

The format string method is intended for this kind of task:

return 'salad: {} hamburger: {} water: {}'.format(s, h, w)

Unrelated: Your counting code is fragile. It happens to work correctly with this data set, because the letters shw only appear once each in the entire set of words. However, if you added a word like 'milkshake' this code would count an extra s and h every time it appeared.

A better way would be to split the string into words, then look at the first letter of each:

for word in order.split():
    char = word[0]
    if char == 's':
    etc.

Even more robust would be to count the words themselves and return a dict, but I’ll leave that to you when you get to dicts; it looks like you’re just beginning with Python.

like image 137
Tom Zych Avatar answered Jul 21 '26 04:07

Tom Zych