Home > database >  Python list of integers as input and searches for a 'symmetrical [closed]
Python list of integers as input and searches for a 'symmetrical [closed]

Time:10-07

What the code does: Takes a Python list of integers as input and searches for a 'symmetrical' inner-portion of the list then it takes that inner portion and gets the sum of it.

Symmetry occurs if the value of the nth element from the start of the list is equal to the value of the nth element from the end of the list.

Examples of what I want:

>>> symmetrical_sum([10,11,12,11,12])  # Input to the function
([11, 12, 11], 34)  # Returns the symmetrical portion and the sum respectively

>>> symmetrical_sum([9, 99, 88, 8, 77, 7, 77, 8, 88, 10, 100])
([88, 8, 77, 7, 77, 8, 88], 353)

>>> symmetrical_sum([10, 8, 9, 5, 9, 8, 15])
([8, 7, 5, 9, 8], 37)

CodePudding user response:

Here is one potential solution.

The algorithm is quite simple, start from the center, and take elements until the list is no longer symmetrical:

def sym_sum(l):
    from itertools import takewhile
    mid = len(l)//2 # take midpoint
    # get indices (right part) where the list is symmetrical
    sym_idx = list(takewhile(lambda x: l[x]==l[len(l)-x-1], range(mid, len(l))))
    # last symmetrical indice
    last = sym_idx[-1]
    sublist = l[len(l)-last-1:last 1]
    # output sublist and sum
    return (sublist, sum(sublist))

examples:

>>> sym_sum([9,99,88,8,77,7,77,8,88,10,100])
([88, 8, 77, 7, 77, 8, 88], 353)

>>> sym_sum([10,11,12,11,12])
([11, 12, 11], 34)

Now that you have a working algorithm you can try to code this with classical python loops ;)

CodePudding user response:

This looks like homework and since you haven't shown what you've tried so far I'd prefer to get you to think about your problem. Your lack of effort in asking the question is why people are downvoting your question. Often homework has some special constraints, like not to use any built in functions--keep this in mind when asking your questions in future. Plus, the point is to get you to think.

My general advice is try to breakdown your problem.

  1. Find the palindrome. How might you go about this in real life? Does it make sense to just go through the array, looking at just one number at a time? Perhaps a second variable would be helpful... Maybe you don't need to start from the ends of the array?

  2. Add the subset. This is a basic task that you've likely already done before. Usually people will used built-in functions, but you're likely just learning the basics of programming now, so you're likely not "allowed" to use them.

  • Related