What am I doing wrong here?(Python) - python-3.x

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.

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

Median of sorted arrays of equal length

I am trying to find the median of two sorted array of same length for this I am using divide and conquer algorithm. But my code returns None instead of a value
Here is code to find median of single array:
def getmedian(li):
x = len(li)
if x%2 == 0:
return (li[x//2] + li[(x//2)-1])/2
else:
return li[(len(li)-1)//2]
and then I'm using following function for two arrays:
def TwoList(list1,list2):
if len(list1) == 1:
return (list1[0] + list2[0])/2
elif len(list2)== 2:
return (max(list1[0],list2[0]) + min(list2[1], list1[1]))/2
else:
#pdb.set_trace()
x = getmedian(list1)
y = getmedian(list2)
if x == y:
return x
elif x > y:
if len(list1)%2==0:
TwoList(list1[:len(list1)//2], list2[len(list1)//2:])
else:
TwoList(list1[:len(list1)//2+1], list2[len(list1)//2:])
else:
if len(list1)%2==0:
TwoList(list1[len(list1)//2:], list2[:len(list1)//2])
else:
TwoList(list1[len(list1)//2:], list2[:len(list1)//2+1])
Looks like you are doing it right except returning value in TwoList recursive calls.
Please see below code, commented where you have to return value.
def getmedian(li):
x = len(li)
if x%2 == 0:
return (li[x//2] + li[(x//2)-1])/2
else:
return li[(len(li)-1)//2]
def TwoList(list1,list2):
if len(list1) == 1:
return (list1[0] + list2[0])/2
elif len(list2)== 2:
return (max(list1[0],list2[0]) + min(list2[1], list1[1]))/2
else:
#pdb.set_trace()
x = getmedian(list1)
y = getmedian(list2)
if x == y:
return x
elif x > y:
if len(list1)%2==0:
return TwoList(list1[:len(list1)//2], list2[len(list1)//2:]) # return value
else:
return TwoList(list1[:len(list1)//2+1], list2[len(list1)//2:]) # return value
else:
if len(list1)%2==0:
return TwoList(list1[len(list1)//2:], list2[:len(list1)//2]) # return value
else:
return TwoList(list1[len(list1)//2:], list2[:len(list1)//2+1]) # return value
print(TwoList([1,2,3,4],[5,6,7,8]))

My minesweeper program works just fine until I click on the top left tile. Everything looks fine

I am attempting to make minesweeper in Python by using tkinter. When the program checks for bombs, it works just fine unless the tile clicked is at 0, 0 (top left), in which case the program always has tileNorth and tileWest True, causing the program to check a variable that doesn't exist. This causes an error and leaves the 0, 0 tile blank. The checking works in every other tile, including corners, just not the top left. This should not be happening.
TLDR:
My minesweeper program works just fine, but it always messes up at 0, 0 and creates an error. I don't understand what's wrong...
The Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "<string>", line 11, in <lambda>
File "/home/pi/Documents/Python/Minesweeper/Minesweeper.py", line 133, in tileClicked
stringVar_{x}_{y}.set(tileValue)""")
File "<string>", line 56
if bomb_-1_-1 == True:
^
SyntaxError: invalid token
It mentions bomb_-1_-1 which doesn't exist and can't exist... This is why that one if statement needs to work.
My Code:
import random
import tkinter
# Functions
def tileClicked(x, y): # Function is ran when a tile is clicked. The tile is defined by the inputted 'x' and 'y' values.
exec(f"""
global tileNorth, tileEast, tileSouth, tileWest
if y > 0:
tileNorth = True
else:
tileNorth = False
if x < game.size[0] - 1:
tileEast = True
else:
tileEast = False
if y < game.size[1] - 1:
tileSouth = True
else:
tileSouth = False
if x > 0:
tileWest = True
else:
tileWest = False""")
print(f"""{tileNorth}
{tileEast}
{tileSouth}
{tileWest}
DIV""")
exec(f"""
print("{x}, {y}")
if bomb_{x}_{y} == True:
stringVar_{x}_{y}.set("Bomb")
game.failed = True
if x == 0 and y == 0:
tileValue = int(0)
if tileNorth == True:
if tileEast == True:
if bomb_{x + 1}_{y - 1} == True:
tileValue += 1
if tileEast == True:
if bomb_{x + 1}_{y} == True:
tileValue += 1
if tileSouth == True:
if tileEast == True:
if bomb_{x + 1}_{y + 1} == True:
tileValue += 1
if tileWest == True:
if bomb_{x - 1}_{y + 1} == True:
tileValue += 1
if bomb_{x}_{y + 1} == True:
tileValue += 1
if tileWest == True:
if bomb_{x - 1}_{y} == True:
tileValue += 1
else:
tileValue = int(0)
if tileNorth == True:
if tileEast == True:
if bomb_{x + 1}_{y - 1} == True:
tileValue += 1
if tileWest == True:
if bomb_{x - 1}_{y - 1} == True:
tileValue += 1
if bomb_{x}_{y - 1} == True:
tileValue += 1
if tileEast == True:
if bomb_{x + 1}_{y} == True:
tileValue += 1
if tileSouth == True:
if tileEast == True:
if bomb_{x + 1}_{y + 1} == True:
tileValue += 1
if tileWest == True:
if bomb_{x - 1}_{y + 1} == True:
tileValue += 1
if bomb_{x}_{y + 1} == True:
tileValue += 1
if tileWest == True:
if bomb_{x - 1}_{y} == True:
tileValue += 1
if tileValue == 0:
tileValue = "Clear"
stringVar_{x}_{y}.set(tileValue)""")
# Classes
class game:
title = "Minesweeper"
bg = "white"
fg = "black"
size = [10, 10]
tileWidth = 3
tileHeight = 2
failed = False
bombFrequency = 4
flagMode = False
# Execution
window = tkinter.Tk() # The window.
window.title(game.title)
window.config(bg = game.bg)
mainFrame = tkinter.Frame(window, bg = game.bg) # Main frame that everything is located in.
titleFrame = tkinter.Frame(mainFrame, bg = game.bg) # Title frame.
titleLabel = tkinter.Label(titleFrame, bg = game.bg, fg = game.fg, text = game.title, font = "none 20").grid(row = 0, column = 0)
titleFrame.grid(row = 0, column = 0)
tileFrame = tkinter.Frame(mainFrame, bg = game.bg) # Frame where tiles are located.
x = 0
y = 0
for tiles_x in range(game.size[0]): # Generates tiles.
for tiles_y in range(game.size[1]):
exec(f"""global tile_{x}_{y}, stringVar_{x}_{y}, bomb_{x}_{y}
bomb_{x}_{y} = random.randint(1, game.bombFrequency)
if bomb_{x}_{y} == 1:
bomb_{x}_{y} = True
else:
bomb_{x}_{y} = False
stringVar_{x}_{y} = tkinter.StringVar(tileFrame)
tile_{x}_{y} = tkinter.Button(tileFrame, bg = 'lightgrey', fg = 'black', width = game.tileWidth, height = game.tileHeight, textvariable = stringVar_{x}_{y}, command = lambda: tileClicked({x}, {y})).grid(row = {y}, column = {x})""")
y += 1
x += 1
y = 0
tileFrame.grid(row = 1, column = 0)
mainFrame.pack() # The main frame is packed so everything is centered.
window.mainloop()
I don't care if you think dynamic variables are inefficient, it's my choice. I don't want people to comment on my methods of accomplishing a task... unless it's causing the problem...
Thanks!
Using dynamic variables is bad practice, and your experience is a good demonstration why.
Variable names cannot have a minus sign in them. The minus sign is interpreted as the arithmetic operator. So bomb_-1_-1 is interpreted as bomb_ - 1_ - 1. The bomb_ part is understood as a variable name, the 1 as a number, but the underscore following that number is triggering the syntax error.
This also demonstrates that dynamic code is not that great: syntax errors only pop up when certain circumstances are created (like selecting a particular cell).
A quick fix, just to show a work around, is to test first the values of x and y:
if {x} >= 0 and {y} >= 0 and bomb_{x}_{y} == True:
You would have to do similar tests for any other place where you create a dynamic reference like that. So also:
if {x} >= 1 and {y} >= 1 and bomb_{x-1}_{y-1} == True:
...etc.
But this is really patching a terrible design.
Note that even if only one of the variables is negative, you'll evaluate an expression that you did not really intend. You could get this for when only y == -1: bomb_5_-1. This produces no syntax error, but it evaluates as bomb_5_ minus 1. Obviously that is not intended by the algorithm.
Instead of dynamic variables and parsing code at run-time, use lists. They can be nested to have the 2D coverage.

List index out of range when moving

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.

error when executing the program python

def main():
get_value =get_display_info('5 6 0','7 0 0 0 5')
print(get_value)
def get_display_info(dice_to_roll_again_str, dice_set_aside_str):
length1 =len(dice_to_roll_again_str)
d = dice_set_aside_str
if dice_set_aside_str == None:
return 0
else :
return len(dice_set_aside_str)
if length1 and dice_set_aside_str > 0:
return "(Dice to roll again:" + str(dice_to_roll_again_str) +','+
"Dice set aside:" + str(d) + ')'
elif length1 > 0:
return "(Dice to roll again:" + str(dice_to_roll_again_str) + ')'
elif dice_set_aside_str > 0:
return "(Dice set aside:" + str(d) + ')'
Why does my program stop executing upon reaching this statement?
if length1 and dice_set_aside_str > 0:
Your code will return unconditionally after this block:
def get_display_info(dice_to_roll_again_str, dice_set_aside_str):
length1 =len(dice_to_roll_again_str)
d = dice_set_aside_str
if dice_set_aside_str == None:
return 0
else :
return len(dice_set_aside_str)
Hello Adrian,
Solution
Try this below code,
def main():
get_value =get_display_info('5 6 0','7 0 0 0 5')
print "Value : ",get_value
def get_display_info(dice_to_roll_again_str, dice_set_aside_str):
length1 = len(dice_to_roll_again_str)
d = dice_set_aside_str
if dice_set_aside_str == "":
return 0
else :
return len(dice_set_aside_str)
if length1 and dice_set_aside_str > 0:
return "(Dice to roll again:{}".format(str(dice_to_roll_again_str))+",Dice set aside:{}".format(str(dice_set_aside_str))+")"
elif length1 > 0:
return "(Dice to roll again:{}".format(str(dice_to_roll_again_str))+")"
elif dice_set_aside_str > 0:
return "Dice set aside:{}".format(str(dice_set_aside_str))+")"
# Call the main() function
main()
# Call and Print get_display_info() function.
print "Display information : ",get_display_info("mayur","vora")
I hope my answer is helpful.
If any query so comment please.

Resources