Question

PLEASE CODE IN PYTHON Run-length encoding is a simple compression scheme best used when a data-set...

PLEASE CODE IN PYTHON

Run-length encoding is a simple compression scheme best used when a data-set consists primarily of numerous, long runs of repeated characters. For example, AAAAAAAAAA is a run of 10 A’s. We could encode this run using a notation like *A10, where the * is a special flag character that indicates a run, A is the symbol in the run, and 10 is the length of the run. As another example, the string

KKKKKKKKKKKKKBCCDDDDDDDDDDDDDDDKKKKKMNUUUGGGGG

would be encoded

$K13BCC$D15$K5MNUUU$G5

assuming in this case that $ is the flag character. For the sake of this problem we will assume that the input strings to be encoded contain only uppercase letters from the Latin alphabet and that no run is longer than 99 characters long. Flag characters will be chosen only from the set {#, $, &, *}. Note that single letters (’M’), runs of two letters (’CC’), and runs of three letters (’UUU’) are not encoded, as doing so does not save memory or actually compress the data. Do you see why that is the case?

Write the function def rle(string, flag) that takes a non-empty string to encode and a character to use as the flag character. The function returns the run-length encoded argument string. If the string to encode contains any characters except uppercase letters, the function should return the string ’ERROR’ (without the quotation marks). If the flag character is not one of the symbols in the set {#, $, &, *}, the function should return the string ’ERROR’. Consider using a while-loop instead of a for-loop to iterate over the string. Start with an empty string (which will eventually contain the returned result) and keep a counter for the number of identical characters you find in each run. When a run ends, append (i) the flag character, (ii) the count, and (iii) the character itself to the result. Remember that only runs of length 4 or greater should be encoded; single characters, pairs and triples should simply be appended to the result.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
"""

Author:ravi
Date :5/4/17
File Name:run_length_encoding.py
Description:

"""


def rle(string, flag):
    """

    :param string:
    :param flag:
    :return:
    """
    count = 0  # store the count of repeated character
    prev = string[0]  # store previous character
    result = ''  # store resultant string
    index = 0  # store the next index to process
    while index < len(string):  # iterate the string using while loop
        # if string has  lower case character  or other than alphabet or flag has
        # character other than #$&*
        if not string[index].isalpha() or string[index].islower() or flag not in '#$&*':
            return "ERROR"  # return ERROR
        if prev == string[index]:
            count += 1

        else:
            if count > 3:
                result += flag + prev + str(count)

            else:
                result += prev * count
            count = 1

        prev = string[index]
        index += 1
        if index == len(string):  # check index is equal to string length
            if count > 3:
                result += flag + prev + str(count)

            else:
                result += prev * count

    return result


if __name__ == '__main__':
    print("\n" + rle("GGGGG", "#"))
    print("\n" + rle("XYZAAAAAAGGTCCCCCCTTTAAAAAAAAAAAAAAKK", "*"))
    print("\n" + rle("ABCCDEFGGG", "$"))
    print("\n" + rle("ABCCDEFGGGG", "$"))
    print("\n" + rle("XYZAAAAAAGGTCCCCCCTTTaAAAAAAAAAAAAAKK", "*"))
    print("\n" + rle("XYZAAAAAAGGTCCCCCCTTTAAAAAAAAAAAAAAKK", "!"))

output:

#G5 XYZ*A6GGT C6TTT*A14KK ABCCDEFGGG ABCCDEF$G4 ERROR ERROR Process finished with exit code 0

Add a comment
Know the answer?
Add Answer to:
PLEASE CODE IN PYTHON Run-length encoding is a simple compression scheme best used when a data-set...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Run-length encoding (RLE) is a simple "compression algorithm" (an algorithm which takes a block of data...

    Run-length encoding (RLE) is a simple "compression algorithm" (an algorithm which takes a block of data and reduces its size, producing a block that contains the same information in less space). It works by replacing repetitive sequences of identical data items with short "tokens" that represent entire sequences. Applying RLE to a string involves finding sequences in the string where the same character repeats. Each such sequence should be replaced by a "token" consisting of: the number of characters in...

  • Run-length encoding is a relatively simple technique for compressing data; if a particular value (or substring)...

    Run-length encoding is a relatively simple technique for compressing data; if a particular value (or substring) appears multiple times in a row, it is only represented once, followed by an integer indicating the number of times it should be repeated. For example, the string "AAAAA" can be compressed to "A5" (5 occurrences of 'A'), saving three characters in the process. Define a Java method named expand() that takes a single String argument. You may assume that this String is run-length...

  • JAVA: Run length encoding is a simple form of data compression. It replaces long sequences of...

    JAVA: Run length encoding is a simple form of data compression. It replaces long sequences of a repeated value with one occurrence of the value and a count of how many times to repeat it. This works reasonably well when there are lots of long repeats such as in black and white images. To avoid having to represent non-repeated runs with a count of 1 and the value, a special value is often used to indicate a run and everything...

  • Please solve in Python. You would like to set a password for an email account. However,...

    Please solve in Python. You would like to set a password for an email account. However, there are two restrictions on the format of the password. It has to contain at least one uppercase character and it cannot contain any digits. You are given a string S consisting of N alphanumerical characters. You would like to find the longest substring of Sthat is a valid password. A substring is defined as a contiguous segment of a string. For example, given...

  • Help please this is C/C++ code /* * Lab12, the purpose of this lab is to...

    Help please this is C/C++ code /* * Lab12, the purpose of this lab is to improve your skills in handling c strings * with pointers . * use of : strlen ,string concatenation strcat, compare strcmp, * copy strcpy and search strrchr * */ #include <cstdlib> #include <iostream> #include<cstring> using namespace std; /** * Create a method that prompts the user for only lowercase letters to represent * a name. * Start a Label, then prompt the user to...

  • Please read the problem carefully and answer the 2 questions below code: /***************************************************************** * Program: palindrome.c...

    Please read the problem carefully and answer the 2 questions below code: /***************************************************************** * Program: palindrome.c * * Purpose: implements a recursive function for determining *   if a string is a palindrome * * Authors: Steven R. Vegdahl, Tammy VanDeGrift, Martin Cenek * *****************************************************************/ #include #include #include /***************************************************************** * is_palindrome - determines whether a string of characters is a palindrome * * calling sequence: *    result = is_palindrome(str, first_index, last_index) * * parameters - *    str - the string to test *    first_index -...

  • For this assignment, you will write a program to work with Huffman encoding. Huffman code is...

    For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...

  • You will be writing a simple Java program that implements an ancient form of encryption known...

    You will be writing a simple Java program that implements an ancient form of encryption known as a substitution cipher or a Caesar cipher (after Julius Caesar, who reportedly used it to send messages to his armies) or a shift cipher. In a Caesar cipher, the letters in a message are replaced by the letters of a "shifted" alphabet. So for example if we had a shift of 3 we might have the following replacements: Original alphabet: A B C...

  • Please write code using Python. Rubric Assignment Solution Total: 100 pts Program successfully retrieves and validates...

    Please write code using Python. Rubric Assignment Solution Total: 100 pts Program successfully retrieves and validates user input 15 pts Morse Code Function Created 10 pts Function Uses Parameters to get input message 15 pts Function successfully converts passed message to Morse Code and returns the Morse Code equivalent of message 45 pts Program calls Morse Code function and outputs the result of the function (i.e. the actual Morse Code) 15 pts Main Function Requirement Part 2 MUST have a...

  • cs55(java) please Part 1: You are a programming intern at the student transfer counselor's office. Having...

    cs55(java) please Part 1: You are a programming intern at the student transfer counselor's office. Having heard you are taking CS 55, your boss has come to ask for your help with a task. Students often come to ask her whether their GPA is good enough to transfer to some college to study some major and she has to look up the GPA requirements for a school and its majors in a spreadsheet to answer their question. She would like...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT