I\'m having trouble figuring out what to do for an assignment in Python 3. This
ID: 3564471 • Letter: I
Question
I'm having trouble figuring out what to do for an assignment in Python 3. This is the prompt:
Read in a list of numbers entered by the user. The user will enter integers, and when they are done they will type "end". You should print out the length of the longest subsequence of repeated elements. That is, the largest number of times something is repeated. So for the list [1, 4, 4, 3], you should print out "2", because there are two fours in a row. For the list [1, 2, 3, 3, 4, 1, 1, 1] you should print out "3", because there are three 1s in a row. Please format your results as follows:
Enter a number: 1
Enter a number: 1
Enter a number: 2
Enter a number: 5
Enter a number: 5
Enter a number: 5
Enter a number: end
Longest run was 3 long.
My code so far looks like this:
def main ():
while True:
line = input ('> ')
if line == "done":
print ("number of times something was repeated")
I'm unsure what to do next. Please, help.
Explanation / Answer
import functools def cached(func): cache = {} def template(*args): #: template is wrapper; func is wrapped key = (func, )+args try: ret = cache[key] except KeyError: ret = func(*args) cache[key] = ret else: pass return ret functools.update_wrapper(template, func) return template @cached def LCSLength(str1, str2): if len(str1)==0 or len(str2)==0: return 0 if str1[-1] == str2[-1]: return LCSLength(str1[:-1], str2[:-1])+1 else: return max(LCSLength(str1, str2[:-1]), LCSLength(str1[:-1], str2)) @cached def LCS(str1, str2): if len(str1)==0 or len(str2)==0: return '' if str1[-1] == str2[-1]: return ''.join([LCS(str1[:-1], str2[:-1]), str1[-1]]) else: candidate1 = LCS(str1[:-1], str2) candidate2 = LCS(str1, str2[:-1]) if len(candidate1) >= len(candidate2): return candidate1 else: return candidate2 if __name__=='__main__': # a simple example lcs = LCS('abcbdab', 'bdcaba') assert len(lcs) == LCSLength('abcbdab', 'bdcaba') print 'Length of Longest common subsequence: %d' %(len(lcs),) print 'Longest common subsequence: %s' % (lcs,) # a complex example: strA = '''abcdefgabcdefgaabcdefgabcdefgabcdesdqfgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg''' strB = '''gdebcdehhglkjlkabvhgdebcdehhgdebcdehhgdebcdeoshhgdebcdehhgdebcdehhgdebcdehhgdebcdehh''' lcs = LCS(strA, strB) assert len(lcs) == LCSLength(strA, strB) print 'Length of Longest common subsequence: %d' %(len(lcs),) print 'Longest common subsequence: ' print lcs
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.