|
Post by xcessive on Oct 17, 2012 7:59:12 GMT -5
Write a function that takes two strings, a "key" and a "heap". It counts how many times the "key" occurs in the "heap". For example: Say the heap is "always more and always more after that", and the key is "more" There are two matches, so the answer is two.
Come up with the most efficient possible solution you can.
|
|
iPokemon
Incredibly Beginning
[M0n:400]
Posts: 40
|
Post by iPokemon on Oct 25, 2012 17:32:05 GMT -5
PHP: substr_count($heap,$key);
|
|
|
Post by xcessive on Oct 25, 2012 18:59:06 GMT -5
PHP: substr_count($heap,$key);
I said "Write a function..." which infers that you write one from scratch. Nice try though
|
|
Ween
Incredibly Slacking
Posts: 8
|
Post by Ween on Nov 29, 2012 0:10:08 GMT -5
Seeing as no one's attempted this, I thought I would post something. I haven't used Python for a few years so I decided to try to use it again.
Python 2:
def pattern_match(key, heap):
substring = "" count = 0
for x in range(0, len(heap)): substring = heap[x:x+len(key)] if (substring == key): count+=1
return count
print pattern_match("apple", "banana apple orange apple banana apple apple hotdog")
Edit: My indents are gone and I can't seem to make them show up
Returns 4. Just loops though each character of the heap string and compares a substring started at the current character to the key string. Not efficient but at least it's something.
|
|
Jordan
Incredibly Beginning
Posts: 36
|
Post by Jordan on Nov 29, 2012 19:29:23 GMT -5
Seeing as no one's attempted this, I thought I would post something. I haven't used Python for a few years so I decided to try to use it again. Python 2: def pattern_match(key, heap):
substring = "" count = 0
for x in range(0, len(heap)): substring = heap[x:x+len(key)] if (substring == key): count+=1
return count
print pattern_match("apple", "banana apple orange apple banana apple apple hotdog")
Edit: My indents are gone and I can't seem to make them show up Returns 4. Just loops though each character of the heap string and compares a substring started at the current character to the key string. Not efficient but at least it's something. You're still using a function not written by you. The substring method is doing all the work for you.
|
|