0

It's actually a string but I just converted it to a list because the answer is supposed to be returned as a list. I've been looking at this problem for hours now and cannot get it. I'm supposed to take a string, like "Mary had a little lamb" for example and another string such as "ab" for example and search through string1 seeing if any of the letters from string2 occur. So if done correctly with the two example it would return ["a=4","b=1"]

I have this so far:

def problem3(myString, charString):
    myList = list(myString)
    charList = list(charString)
    count = 0
    newList = []
    newString = ""
    for i in range(0,len(myList)):
        for j in range(0,len(charList)):
            if charList[j] == myList[i]:
                count = count + 1
                newString = charList[j] + "=" + str(count)
    newList.append(newString)
    return newList

Which returns [a=5] I know it's something with the newList.append(string) and where it should be placed, anyone have any suggestions?

AChampion
  • 29,683
  • 4
  • 59
  • 75

3 Answers3

1

You can do this very easily with list comprehensions and the count function that strings (and lists!) have:

  1. Split the search string into a list of chars.
  2. For each character in the search string, loop over the input string and determine how much it occurs (via count).

Example:

string = 'Mary had a little lamb'
search_string = 'ab'
search_string_chars = [char for char in search_string]
result = []
for char in search_string_chars:
    result.append('%s=%d' % (char, string.count(char)))

Result:

['a=4', 'b=1']

Note that you don't need to split the search_string ('ab') into a list of characters, as strings are already lists of characters - the above was done that way to illustrate the concept. Hence, a reduced version of the above could be (which also yields the same result):

string = 'Mary had a little lamb'
search_string = 'ab'
result = []
for char in search_string:
    result.append('%s=%d' % (char, string.count(char)))
jrd1
  • 10,358
  • 4
  • 34
  • 51
  • Looks like a good way but I'm supposed to use loop iteration and not count/search –  Nov 12 '16 at 00:32
  • @jaymoney: I see. In actuality, the `count` function encapsulates that bit of code where one loops over the string to find the corresponding character, and can be reconstructed / implemented with plain python as desired. I implemented it as such, since your current iteration of the question doesn't address this concern. – jrd1 Nov 12 '16 at 01:04
0

Here's a possible solution using Counter as mentioned by coder,

from collections import Counter
s = "Mary had a little lambzzz"

cntr = Counter(s)
test_str = "abxyzzz"

results = []
for letter in test_str:
    if letter in s:
        occurrances = letter + "=" + str(cntr.get(letter))
    else:
        occurrances = letter + "=" + "0"

    if occurrances not in results:
        results.append(occurrances)


print(results)

output

['a=4', 'b=1', 'x=0', 'y=1', 'z=3']
chatton
  • 596
  • 1
  • 3
  • 8
  • 2
    Why `if letter in s:`? Returning `z=0` is an appropriate response. Also `cntr[letter]` would be sufficient (and it's already a `str`). – AChampion Nov 12 '16 at 00:21
  • yep you're right, I made an update to the answer! Thanks for spotting that. – chatton Nov 12 '16 at 00:37
  • You've made it more complicated than necessary `cntr[letter]` already returns `0` for keys that don't exist, so you can completely eliminate the `if` condition. – AChampion Nov 12 '16 at 00:39
  • Looks like a good method but Im supposed to use loop iteration and we haven't learned Counter yet –  Nov 12 '16 at 00:44
0
import collections

def count_chars(s, chars):
    counter = collections.Counter(s)
    return ['{}={}'.format(char, counter[char]) for char in set(chars)]

That's all. Let Counter do the work of actually counting the characters in the string. Then create a list comprehension of format strings using the characters in chars. (chars should be a set and not a list so that if there are duplicate characters in chars, the output will only show one.)

Noah
  • 1,329
  • 11
  • 21
  • In reference to your suggested edit on [this answer](http://stackoverflow.com/a/27251855/5211833), please refrain from adding code from newer methods to existing answers. Either post your own answer, or ping the author of the answer with your proposed new solution. For a full reference on meta on do's and don'ts when editing especially code [see the relevant meta page](http://meta.stackoverflow.com/questions/260245/when-should-i-make-edits-to-code). If you like more information, please come talk to us in the [SOCVR chatroom](http://chat.stackoverflow.com/rooms/41570/so-close-vote-reviewers). – Adriaan Nov 13 '16 at 11:27