0

I am working through a problem on Hackerrank, Arrays: Left Rotation. I have created a dictionary but am trying to create a second dictionary with new keys but same values. The problem is I keep creating my second dictionary as a list but can't see why. For Instance, the code below

def rotLeft(a, d):
    dic = Counter()
    dic2 = Counter()
    for i in range(len(a)):
        dic[i] += a[i]
    for k,v in dic.items():
        if k-d < 0:
            k_new = len(a)+k-d
        else:
            k_new = k-d
        dic2[k_new] += v
    dic2 = sorted(dic2)
    return dic2.items()

I get

AttributeError: 'list' object has no attribute 'items'

I'm using Python 3. Thanks in advance for any advice!

jlod
  • 13
  • 6

1 Answers1

0

sorted() returns list. Here your trying to add items() to list so it's giveing u the error AttributeError: 'list' object has no attribute 'items'

The Below Code Should Work Fine

from collections import Counter
def rotLeft(a, d):
    dic = Counter()
    dic2 = Counter()
    for i in range(len(a)):
        dic[i] += a[i]
    for k,v in dic.items():
        if k-d < 0:
            k_new = len(a)+k-d
        else:
            k_new = k-d
        dic2[k_new] += v
    return [k for i,k in dic2.items()]
print(rotLeft([1,2,3,4,5], 2))

The Same Code Can Be Written In Few Lines As below

def rotLeft(a,d):
    ArrA = a[:d]
    a = a[d:]
    a.extend(ArrA)
    return a
print(rotLeft([1,2,3,4,5], 4))
Sunilsai
  • 68
  • 6