Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

An inversion in a sequence is a pair of entries that are out of order. For examp

ID: 3546935 • Letter: A

Question

                    An inversion in a sequence is a pair of entries that are out of order. For example, the characters F and D form and inversion string 'ABBFHDL' because F                     appears before D; so do characters H and D. The total number of inversions in a sequence (ie the number of pairs that are out of order) i a measure of how                     unsorted the sequence is. The total number of inversions in 'ABBFHDL' is 2. Implement function inverse() that takes a sequence (a string) of uppercase                     characters A through Z and returns the number of inversions in the sequence.                 

                

                    >>>inversions('ABBFHDL')                 

                

                    2                 

                

                    >>>inversions('ABCD')                 

                

                    0                 

                

                    >>>inversions('DCBA')                 

                                     6

Explanation / Answer

def inversions(s): count = 0 for i in range(len(s)-1): for j in range(i+1,len(s)): if s[i] > s[j]: print(s[i],s[j]) count += 1 break #remove 'break' if you want to count every possible #out of order pair for a particular character in the string print(count)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote