I've been learning from Geeksforgeeks.org and tried to write this C code into python and run it
"""
recursive implementation
"""
#arr = []
def leftRotate(arr, d, n):
# Return if number of elements to be rotated is zero or equal to array size
if(d == 0 or d == n):
return
# if number of elements to be rotated if exactly half of array size/
if ( n - d == d):
swap(arr, 0, n-d, d)
return
# if A is shorter
if(d < n-d):
swap(arr, 0, n-d, d)
leftRotate(arr, d, n-d)
else: # if B is shorter
swap(arr, 0, d, n-d)
leftRotate(arr[0]+n-d, 2*d-n, d)
def printArray(arr, size):
i = 0
for i in range(size):
print("%d"% arr[i], end=' ')
print("\n")
def swap(arr, fi, si, d):
i = 0
temp = list
for i in range(d):
temp = arr[fi + i]
arr[fi + i] = arr[si+i]
arr[si + i] = temp
# Driver program to test above function
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)
Upon running this code it says a error saying TypeError: 'int' object is not subscriptable
[Running] python "b:\\Shall\\Practice\\Geeksforgeeks.org\\recursiveblockswap.py"
Traceback (most recent call last): File "b:\\Shall\\Practice\\Geeksforgeeks.org\\recursiveblockswap.py", line 38, in <module> leftRotate(arr, 2, 7)
File "b:\\Shall\\Practice\\Geeksforgeeks.org\\recursiveblockswap.py", line 17, in leftRotate leftRotate(arr, d, nd)`
File "b:\\Shall\\Practice\\Geeksforgeeks.org\\recursiveblockswap.py", line 17, in leftRotate leftRotate(arr, d, nd) `
File "b:\\Shall\\Practice\\Geeksforgeeks.org\\recursiveblockswap.py", line 20, in leftRotate leftRotate(arr[0]+nd, 2*dn, d) `
File "b:\\Shall\\Practice\\Geeksforgeeks.org\\recursiveblockswap.py", line 12, in leftRotate swap(arr, 0, nd, d)
File "b:\\Shall\\Practice\\Geeksforgeeks.org\\recursiveblockswap.py", line 32, in swap temp = arr[fi + i]
TypeError: 'int' object is not subscriptable`
[Done] exited with code=1 in 0.209 seconds
leftRotate(arr[0]+nd, 2*dn, d)
in this you are passing an integer value to the variable arr
this is causing an error at temp = arr[fi + i]
TypeError: 'int' object is not subscriptable`
basically means that you are accessing index of an int object.
Side Note:
in python you can swap values using
arr[1], arr[2] = arr[2], arr[1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.