List index out of range when moving - python-3.x

This is my code for the game of fifteen, excluding the 'won' function:
import sys
d = int(sys.argv[1])
dimension = (d * d) - 1
board = [[0 for x in range(d)] for y in range(d)]
def main():
global d
if len(sys.argv) != 2 or 0 > d or d > 9:
print("usage: python fifteen.py size")
exit()
def init():
global d
global dimension
global board
for row in range(d):
for col in range(d):
board[row][col] = dimension
dimension -= 1
if d % 2 == 0:
board[d-1][d-3] = 1
board[d-1][d-2] = 2
def draw():
global d
global dimension
global board
for row in range(d):
for col in range(d):
if board[row][col] == 0:
print("__", end="")
else:
print("{:0=2d} ".format(board[row][col]), end="")
print("")
def move():
global d
global dimension
global board
while True:
tile = int(input("Tile to move: "))
if tile > 0:
break
for row in range(d):
for col in range(d):
if board[row][col] == tile:
colleft = col - 1
colright = col + 1
rowup = row - 1
rowdown = row + 1
if board[row][colleft] == 0 and colleft >= 0:
board[row][colleft] = tile
board[row][col] = 0
return True
elif board[row][colright] == 0 and colright < d:
board[row][colright] = tile
board[row][col] = 0
return True
elif board[rowup][col] == 0 and rowup >= 0:
board[rowup][col] = tile
board[row][col] = 0
return True
elif board[rowdown][col] == 0 and rowdown < d:
board[rowdown][col] = tile
board[row][col] = 0
return True
return False
return True
main()
init()
draw()
move()
draw()
When I want to move 2 or 3 for instance, I keep getting "IndexError: list index out of range":
Erorr message:
python3 fifteen.py 3
Traceback (most recent call last):
File "fifteen.py", line 83, in <module>
move()
File "fifteen.py", line 72, in move
elif board[rowdown][col] == 0 and rowdown < d:
IndexError: list index out of range
What do I have to do to make this work properly?

because rowdown and colright could be bigger than the max index of your board.
for example, d = 3.
when row = 2, rowdown = 3 which is out of index of board.

Related

I've tried running the code but it says list index is out of range

from typing import List
# You are given an integer n, denoting the no of people who needs to be seated, and a list of m integer seats, where 0 represents a vacant seat. Find whether all people can be seated, provided that no two people can sit together
When I run this code in geeks for geeks for submission I get a error that List index is out of range.
but seems to work fine when I run it as a script.
class Solution:
def is_possible_to_get_seats(self, n: int, m: int, seats: List[int]) -> bool:
vacant_seats = 0
if len(seats) == 2:
if seats[0] or seats[1] == 1:
print(seats)
return False
else:
print(seats)
return True
else:
for x in range(len(seats)):
if x == 0:
if seats[x] == 0 and seats[x+1] == 0:
seats[x] = 1
vacant_seats += 1
elif x == len(seats)-1:
if seats[x] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
else:
if seats[x] == 0:
if seats[x+1] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
if vacant_seats < n:
return False
else:
return True
# {
# Driver Code Starts
class IntArray:
def __init__(self) -> None:
pass
def Input(self, n):
arr = [int(i) for i in input().strip().split()] # array input
return arr
def Print(self, arr):
for i in arr:
print(i, end=" ")
print()
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
m = int(input())
seats = IntArray().Input(m)
obj = Solution()
res = obj.is_possible_to_get_seats(n, m, seats)
result_val = "Yes" if res else "No"
print(result_val)
# } Driver Code Ends

ModuleNotFoundError: No module named 'src'. Python 3 error

I'm facing the dreaded ModuleNotFoundError: No module named 'src' error. I've done quite some extensive reading into this problem and see that this is a common problem. I can't seem to wrap my head around this.
You can pull my repo at https://github.com/mustafahoda/data-structures-and-algos
Here is what my current project directory looks like.
I'm using pipenv and running commands from after entering the env shell.
I'm using python 3
DSandAlgoBenchmarkSuite
src
|---CommonProblems
|---DataStructures
|---SortingAlgorithms
|--sorting_algos.py
test
|---test_bubble_sort_1.py
.gitignore
.benchmarks
.pytest_cache
Pipfile
Pipfile.lock
test.py
test_bubble_sort_2.py
I have two files that I'd like to run:
test/test_bubble_sort_1.py
test_bubble_sort_2.py
Contents of each file.
# test/test_bubble_sort_1.py
from src.SortingAlgorithms import sorting_algos
import pytest
# test_bubble_sort_2.py
from src.SortingAlgorithms import sorting_algos
import pytest
# src/SortingAlgorithms/sorting_algos.py
# ---------BUBBLE SORT-------------
def bubble_sort(A: list) -> list:
sorted = len(A)
for i in range(len(A)):
L = 0
R = 1
while R != len(A) :
# if L > R, then swap
if A[L] > A[R]:
temp = A[L]
A[L] = A[R]
A[R] = temp
L = L + 1
R = R + 1
return A
# -----------------INSERTION SORT----------------------
def shift_items_to_right(B, start, stop):
for i in range(stop, start, -1):
B[i] = B[i - 1]
return B
def insertion_sort(A : list) -> list:
sorted = 0
while sorted != len(A):
hole = 0
for i in A[:sorted + 1]:
value = A[sorted]
if value < A[hole]:
# move all items to the right from the hole onwards
shift_items_to_right(A, hole, sorted)
# store the value in the hole
A[hole] = value
else:
hole = hole + 1
sorted = sorted + 1
return A
# ---------------------MERGE SORT--------------------------------------
def merge(A: list, B: list) -> list:
ptr_A = 0
ptr_B = 0
C = []
while ptr_A <= len(A) - 1 and ptr_B <= len(B) - 1:
if A[ptr_A] >= B[ptr_B]:
C.append(B[ptr_B])
ptr_B = ptr_B + 1
else:
C.append(A[ptr_A])
ptr_A = ptr_A + 1
if ptr_A == len(A):
for i in B[ptr_B:]:
C.append(i)
else:
for i in A[ptr_A:]:
C.append(i)
return C
def merge_sort(A: list) -> list:
print("A: %s" % A)
if len(A) == 1:
return A
# STEP 1: Divide
mid = len(A) // 2
L = A[:mid]
R = A[mid:]
if L is not None:
L = merge_sort(L)
if R is not None:
R = merge_sort(R)
merged = merge(L, R)
print("Merged: %s" % merged)
return merged
# ---------------------QUICK SORT--------------------------------------
def quicksort(A: list) -> list:
return _quicksort(A, 0, len(A) - 1)
def _quicksort(A: list, start: int, end: int) -> list:
if start >= end:
return A
print("A before partition: %s" % A)
pIndex = partition(A, start, end)
print("A after partition: %s" % A)
print("_____________________________")
_quicksort(A, start, pIndex - 1)
_quicksort(A, pIndex, end)
return A
def partition(A, start: int, end: int):
# set_trace()
pivot = A[end]
i = start
pIndex = start
# set_trace()
while i < end:
# set_trace()
if pivot >= A[i]:
# implement swap between pIndex and A[i]
temp = A[i]
A[i] = A[pIndex]
A[pIndex] = temp
pIndex = pIndex + 1
i = i + 1
# once we reach the element before the pivot, we swap pivot into pIndex
temp = A[pIndex]
A[pIndex] = pivot
A[end] = temp
# set_trace()
print(A)
return pIndex
# ---------------------SELECTION SORT-------------------------------------
def find_min_not_in_place(A: list, visited) -> int:
for i in A:
if visited[i] == False:
min = i
break
for i in A[1:]:
# set_trace()
if i < min and visited[i] == False:
# set_trace()
min = i
# visited[min] = True
return min
def selection_sort_not_in_place(A: list) -> list:
B = []
# construct a dictionary that will keep track of visited numbers
visited = dict()
for i in A:
visited[i] = False
# keep repeating the process until theere are no values in dictionary with False
while False in visited.values():
for i in A:
min = find_min_not_in_place(A, visited)
# set_trace()
B.append(min)
visited[min] = True
print(B)
return B
def find_min_in_place(A: list, sorted_index: int) -> int:
min_index = sorted_index
min = A[sorted_index]
# for i in A[sorted_index:]:
for i in range(sorted_index, len(A)):
if A[i] < min:
min = A[i]
min_index = i
return (min, min_index)
def selection_sort_in_place(A: list) -> list:
sorted = 0
while sorted != len(A):
# min, min_index = find_min_in_place(A[sorted + 1:])
min, min_index = find_min_in_place(A, sorted)
# implement swapping
temp = A[sorted]
A[sorted] = min
A[min_index] = temp
sorted = sorted + 1
return A
Ideally, I want pytest-benchmark suite to work but I've isolated the problem to being an import error.
When I run test_bubble_sort_2.py from the main project directory, it works fine!
However, when I run test/test_bubble_sort_1.py from the main project directory, it doesn't work and throws the exception: ModuleNotFoundError: No module named 'src'
I'd like to run test/test_bubble_sort_1.py in order to maintain the project structure and access the functions from my sorting_algos.py file so I can benchmark them.

What am I doing wrong here?(Python)

Here is my code
def almostIncreasingSequence(sequence):
def count(sequence, item):
found = 0
for i in sequence:
if i == item:
found += 1
return (found)
def removeItemFromArray(sequence, item):
n = []
for i in sequence:
if i != item:
n.append(i)
return (n)
def isIncreasing(sequence):
if sorted(sequence) == sequence:
return (True)
else:
return (False)
count = 0
for i in range(len(sequence) - 1):
if sequence[i] >= sequence[i + 1]:
count += 1
for i in sequence:
sr = removeItemFromArray(sequence, i)
if (count(sequence, i) == 1 and count == 1 and isIncreasing(sr) == True) or (len(sequence) == 2 and count(sequence, i) == 2):
return (True)
else:
return (False)
print (almostIncreasingSequence([1,3,2,1]))
And here is my error
Traceback (most recent call last):
File "C:/Users/Harry/Documents/randompythonprograms/almostincreasingsequence.py", line 29, in
print (almostIncreasingSequence([1,3,2,1]))
File "C:/Users/Harry/Documents/randompythonprograms/almostincreasingsequence.py", line 25, in almostIncreasingSequence
if (count(sequence, i) == 1 and count == 1 and isIncreasing(sr) == True) or (len(sequence) == 2 and count(sequence, i) == 2):
TypeError: 'int' object is not callable
You have both a function and a variable named count. You're going to have to rename one of them.

Puzzler solver program: How many different solutions are there to (1/a)+(1/b)+(1/c)+(1/d)+(1/e)+(1/f)+(1/g) = 1?

I wrote the python code below that solves and prints each possible solution for anything under 6 unit fractions, but given how I programmed it, it takes infinitely long to check for 7 fractions. Any ideas on how to modify the code to find all the possible solutions more efficienty?
import sys
from fractions import Fraction
import os
#myfile = open('7fractions.txt', 'w')
max = 7 #>2 #THIS VARIABLE DECIDES HOW MANY FRACTIONS ARE ALLOWED
A = [0] * max
A[0] = 1
def printList(A):
return str(A).strip('[]')
def sumList(A):
sum = 0
for i in A:
if i != 0:
sum += Fraction(1, i)
return sum
def sumTest(A):
sum = 0
v = 0
for i in range(0, len(A)):
if A[i] == 0 and v == 0:
v = Fraction(1,A[i-1])
if v != 0:
sum += v
else:
sum += Fraction(1, A[i])
return sum
def solve(n, A):
if n == max - 2:
while (sumTest(A) > 1):
print(A)
if sumList(A) < 1:
e = 1 - sumList(A)
if e.numerator == 1 and e.denominator>A[n-1]:
A[n+1] = e.denominator
#myfile.write(printList(A) + '\n')
print(A)
A[n+1] = 0
A[n] += 1
else:
while (sumTest(A) > 1):
if sumList(A) < 1:
A[n+1] = A[n] + 1
solve(n+1, A)
A[n+1] = 0
A[n] += 1
#execute
solve(0, A)

Sort a user input list of numbers using python bubble sort

I've just started to learn python and I've decided to try and do a bubble sort. I've used the code below which works ok if the numbers to be sorted are 0 to 9. After that, it doesn't sort them correctly. I think, in my limited knowledge that this is because it is a 'list'.
I would like the user to be able to input the numbers but for the program to sort them regardless of the length of the number. Any help would be appreciated.
def bubble_sort(items):
changes=0
for i in range(len(items)):
for j in range(len(items)-1-i):#-i = optimised??
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j] # Swap
changes=changes+1
print(items)
print("Number of passes =",i)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers=input()
items=numbers.split()
Try this:
print('welcome to the automatic bubble sorter')
inputted_list = input('please enter a list of numbers seperated by commas: ')
list = inputted_list.split(',')
number_of_items = int(len(list))
sorting_method = input('if you would like your list to be sorted in ascending order, press 1, if you would like it to be sorted in descending order, press 2')
print(list)
if sorting_method == '1':
position = 0
Pass = 0
counter = 1
while counter == 1:
number_of_swaps = 1
counter2 = 0
permanent_numbers = []
while number_of_swaps > 0:
counter2 = counter2 + 1
number_of_swaps = 0
while position < number_of_items - 1:
if int(list[position]) > int(list[position + 1]):
number_of_swaps = number_of_swaps + 1
item1 = int(list[position])
item2 = int(list[position + 1])
list[position] = item2
list[position + 1] = item1
position = position + 1
Pass = Pass + 1
print('pass',Pass,':',list)
position = 0
if Pass == number_of_items - 1:
number_of_swaps = 0
permanent_numbers.append(list[number_of_items - counter2])
if number_of_swaps == 0:
counter = 0
print('total number of passes:', Pass)
elif sorting_method == '2':
position = 0
Pass = 0
counter = 1
while counter == 1:
number_of_swaps = 1
while number_of_swaps > 0:
number_of_swaps = 0
while position < number_of_items - 1:
if int(list[position]) > int(list[position + 1]):
number_of_swaps = number_of_swaps + 1
item1 = int(list[position])
item2 = int(list[position + 1])
list[position] = item2
list[position + 1] = item1
position = position + 1
Pass = Pass + 1
print('pass',Pass,':',list)
position = 0
if Pass == number_of_items - 1:
number_of_swaps = 0
if number_of_swaps == 0:
counter = 0
print('total number of passes:', Pass)
try map:
I suggested using map before, but I just remembered that map in python 3.x* yields a generator rather than a list, so that is why you cannot take the length of it. The updated answer is below
numbers = input("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
items = [int(num) for num in numbers.split()]
Modified existing code:
#!/usr/bin
def bubble_sort(items):
changes = passes = 0
last = len(items)
swapped = True
while swapped:
swapped = False
passes += 1
for j in range(1, last):
if items[j - 1] > items[j]:
items[j], items[j - 1] = items[j - 1], items[j] # Swap
changes += 1
swapped = True
last = j
print(items)
print("Number of passes =",passes)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers = input()
items = [int(num) for num in numbers.split() if num.isdigit()]
if items: bubble_sort(items)
def b_sort(list):
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx] > list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
str_input= input("Enter numbers: ")
list = [int(x) for x in str_input.split()]
b_sort(list)
print('sorted elements are: ')
print(list)
def sort():
try:
n = [1,8,6]
l = len(n)
print("Original list:", n)
for i in range(l - 1):
for j in range(0,l - i - 1):
if n[j] > n[j + 1]:
n[j], n[j + 1] = n[j + 1], n[j]
print("List after sorting is:", n)
except:
print("Error in inputing values")
sort()

Resources