简体   繁体   中英

How can I create compress function in Python?

I need to create a function called StringZip that compresses a string by replacing repeated letters with number of repeats. Ex) aaaaabbbbbccccccaaaddddd -> a5b5c6a3d5

I want to change this code into function:

 s = 'aaaaabbbbbccccccaaaddddd'
 result = s[0]  
 count  = 0

 for i in s:
     if i == result[-1]:
         count += 1
     else:
         result += str(count) + i
         count = 1
 result += str(count)

 print(result)

How can I create function using def?

syl! The way that you can create a function with def is like this:

def myFunctionName(myParam, myOtherParam):
   # your function
   return endResult

Or in your case:

# lower_with_under() is the standard for functions in python
def string_zip(inString):
    s = inString
    result = s[0]  
    count  = 0
    for i in s:
        if i == result[-1]:
            count += 1
        else:
            result += str(count) + i
            count = 1
    result += str(count)
    print(result)

And you would call it like:

theResult = myFunctionName(1, 3)

Or in your case:

print(string_zip("aaaaabbbbbccccccaaaddddd"))

I hope this helps!
By the way, next time, can you try searching on Google for what you want before asking it on Stack Overflow? It helps keep it organized. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM