delete 0 value in list - python

hello I try to make an app- personality test, but i have a problem with evaluation,..
there is a dificult evaluation of test but in short in theese reduce version you just write some values into a given variable, and i want to delete every 0 value from list as a result.. I tried it (programe after # but there is an error), could anybody please help me?
error
File "C:/Users/Stanko/PycharmProjects/pythonProjectDISK/main.py", line 73, in dele
self._data[self.item.key]= list(filter(lambda num: num != 0, self._data[self.item.key]))
AttributeError: 'Test' object has no attribute 'item'
here is a reduce program
class Empty(Exception):
pass
class PriorityVal(ABC):
class _Item:
def __init__(self, key, value):
self.key, self.value = key, value
def __lt__(self, other):
return self.key < other.key
def __repr__(self):
return str((self.key, self.value))
#abstractmethod
def add(self, key, value):
pass
#abstractmethod
def max(self):
pass
#abstractmethod
def min(self):
pass
#abstractmethod
def remove_min(self):
pass
class Test(PriorityVal):
def __init__(self):
self._data = []
def add(self, key, value):
self._data.append(self._Item(key, value))
def max(self):
index = self.find_max()
item = self._data[index]
return item.key, item.value
def find_max(self):
index = 0
for i in range(1, len(self._data)):
if self._data[index] < self._data[i]:
index = i
return index
def _find_min(self):
index = 0
for i in range(1, len(self._data)):
if self._data[i] < self._data[index]:
index = i
return index
def min(self):
index = self._find_min()
item = self._data[index]
return item.key, item.value
def remove_min(self):
index = self._find_min()
item = self._data.pop(index)
return item.key, item.value
def dele(self):
self._data[self.item.key]= list(filter(lambda num: num != 0, self._data[self.item.key]))
test = str(input("test name"))
test = Test()
dzadane = int(input("input d"))
if dzadane <= 0:
dh = 0
elif 0 < dzadane <= 4:
dh = 60
elif 4 < dzadane <= 7:
dh = 70
elif 7 < dzadane <= 12:
dh = 80
elif 12 < dzadane <= 15:
dh = 90
else:
dh = 100
test.add(dh, "d")
izadane = int(input("input i"))
if izadane <= -1:
ih = 0
elif -1 < izadane <= 1:
ih = 60
elif 1 < izadane <= 3:
ih = 70
elif izadane == 4:
ih = 75
elif 4 < izadane <= 6:
ih = 80
elif izadane == 7:
ih = 85
elif 7 < izadane <= 9:
ih = 90
else:
dh = 100
test.add(ih, "i")
szadane = int(input("input s"))
if szadane <= -2:
sh = 0
elif -2 < szadane <= 0:
sh = 60
elif 0 < szadane <= 3:
sh = 70
elif 4 < szadane <= 7:
sh = 80
elif szadane == 8:
sh = 85
elif 8 < szadane <= 10:
sh = 90
else:
sh = 100
test.add(sh, "s")
kzadane = int(input("input k"))
if kzadane <= -3:
kh = 0
elif -3 < kzadane <= 1:
kh = 60
elif -1 < kzadane <= 1:
kh = 70
elif 1 < kzadane <= 4:
kh = 80
elif 4 < kzadane <= 7:
kh = 90
else:
kh = 100
test.add(kh, "k")
nzadane = int(input("input n"))
nh = 0
test.add(nh, "n")
print(dzadane, izadane, szadane, kzadane, nzadane, )
print("test", test._data)
print('max=', test.max())
print( "del all 0", test.dele())
print("test", test._data)

You could try
self._data = [value for value in self._data if value.key != 0]

Related

python IndexError that I cannot resolve with dictionaries

I have a simple problem, and I need a pari of fresh eyes for this. I have a dictionary for my world:
world = {}
and a function that fills rooms in that dictionary based on a 2d array:
def makeRoomsForLevel():
counter = 1
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[c][r] == 1:
world[f"room{counter}"] = Room(
f"room{counter}",
"",
{},
False,
None,
False,
None,
False,
None,
True,
(r, c)
)
counter += 1
And yet another function that I am working on to find the exits for the room:
def findExits():
counter = 1;
for x in range(len(world)):
if rooms[world[f"room{counter}"]].coords[0] + 1 == 1:
pass
I tried running this before I filled in the if statement, and it gave me this error:
IndexError: only integers, slices (':'), ellipsis ('...'), numpy.newaxis ('None') and integer or boolean arrays are valid indicies
I kinda know what it means, but it hasn't given me any problems with this before hand.
Here is the room class:
class Room():
def __init__(self, name, description, exits, hasWeapon, weapon, hasItem, item, hasEnemy, enemy, isFirstVisit, coords):
self.name = name
self.description = description
self.exits = exits
self.hasWeapon = hasWeapon
self.weapon = weapon
self.hasItem = hasItem
self.item = item
self.hasEnemy = hasEnemy
self.enemy = enemy
self.isFirstVisit = isFirstVisit
self.coords = coords
And here is what "rooms" is:
rooms = np.zeros((11, 11))
Here is the full generation code:
rooms = np.zeros((11, 11))
maxRooms = 7
possibleNextRoom = []
world = {}
def startLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
halfHeight = int(len(rooms[1]) / 2)
halfWidth = int(len(rooms[0]) / 2)
rooms[halfWidth][halfHeight] = 1
def resetLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
def countRooms():
roomCount = 0
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[r][c] == 1:
roomCount += 1
return roomCount
def findPossibleRooms():
for r in range(len(rooms) - 1):
for c in range(len(rooms) - 1):
if rooms[r][c] == 1:
if rooms[r][c+1] != 1:
possibleNextRoom.append((r, c+1))
if rooms[r][c-1] != 1:
possibleNextRoom.append((r, c-1))
if rooms[r-1][c] != 1:
possibleNextRoom.append((r-1, c))
if rooms[r+1][c] != 1:
possibleNextRoom.append((r+1, c))
def addRoom():
x = random.randrange(0, len(possibleNextRoom))
rooms[possibleNextRoom[x][0]][possibleNextRoom[x][1]] = 1
possibleNextRoom.pop(x)
def generateLevel():
global x, possibleNextRoom
startLevel()
while countRooms() < maxRooms:
countRooms()
findPossibleRooms()
addRoom()
def makeRoomsForLevel():
counter = 1
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[c][r] == 1:
world[f"room{counter}"] = Room(
f"room{counter}",
"",
{},
False,
None,
False,
None,
False,
None,
True,
(r, c)
)
counter += 1
def findExits():
counter = 1;
for x in range(len(world)):
if rooms[world[f"room{counter}"].coords[0]] + 1 == 1:
pass
def fillRooms():
counter = 1
for x in range(len(world)):
x = random.randrange(1, 2)
if x == 1:
world[f"room{counter}"].hasItem = True
x = random.randrange(1, 10)
if x == 1:
world[f"room{counter}"].hasWeapon = True
x = random.randrange(1, 4)
if x == 1:
world[f"room{counter}"].hasEnemy = True
counter += 1
And here is the entire code:
import random
import numpy as np
world = {}
class Player():
def __init__(self, health, maxHealth, baseDmg, dmg, name, weapons, items, isAlive, previousRoom, roomName):
self.health = health
self.maxHealth = maxHealth
self.baseDmg = baseDmg
self.dmg = dmg
self.name = name
self.weapons = weapons
self.items = items
self.isAlive = isAlive
self.previousRoom = previousRoom
self.room = world[roomName]
def Move(self, direction):
if direction not in self.room.exits:
print("Cannot Move In That Direction!")
return
newRoomName = self.room.exits[direction]
self.previousRoom = world[self.room.name]
print("Moving to", newRoomName)
self.room = world[newRoomName]
def MoveBack(self):
self.room = world[self.previousRoom.name]
print("Moving to", self.room.name)
class Enemy():
def __init__(self, health, dmg, hasLoot, lootItem, isAlive):
self.health = health
self.dmg = dmg
self.hasLoot = hasLoot
self.lootItem = lootItem
self.isAlive = isAlive
class Weapon():
def __init__(self, name, dmg, description):
self.name = name
self.dmg = dmg
self.description = description
class Item():
def __init__(self, name, amt, description):
self.name = name
self.amt = amt
self.description = description
class Room():
def __init__(self, name, description, exits, hasWeapon, weapon, hasItem, item, hasEnemy, enemy, isFirstVisit, coords):
self.name = name
self.description = description
self.exits = exits
self.hasWeapon = hasWeapon
self.weapon = weapon
self.hasItem = hasItem
self.item = item
self.hasEnemy = hasEnemy
self.enemy = enemy
self.isFirstVisit = isFirstVisit
self.coords = coords
#######################Dungeon Generation###################
rooms = np.zeros((11, 11))
maxRooms = 7
possibleNextRoom = []
def startLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
halfHeight = int(len(rooms[1]) / 2)
halfWidth = int(len(rooms[0]) / 2)
rooms[halfWidth][halfHeight] = 1
def resetLevel():
for r in range(len(rooms[0])):
for c in range(len(rooms[1])):
rooms[r][c] = 0
possibleNextRoom.clear()
def countRooms():
roomCount = 0
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[r][c] == 1:
roomCount += 1
return roomCount
def findPossibleRooms():
for r in range(len(rooms) - 1):
for c in range(len(rooms) - 1):
if rooms[r][c] == 1:
if rooms[r][c+1] != 1:
possibleNextRoom.append((r, c+1))
if rooms[r][c-1] != 1:
possibleNextRoom.append((r, c-1))
if rooms[r-1][c] != 1:
possibleNextRoom.append((r-1, c))
if rooms[r+1][c] != 1:
possibleNextRoom.append((r+1, c))
def addRoom():
x = random.randrange(0, len(possibleNextRoom))
rooms[possibleNextRoom[x][0]][possibleNextRoom[x][1]] = 1
possibleNextRoom.pop(x)
def generateLevel():
global x, possibleNextRoom
startLevel()
while countRooms() < maxRooms:
countRooms()
findPossibleRooms()
addRoom()
def makeRoomsForLevel():
counter = 1
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[c][r] == 1:
world[f"room{counter}"] = Room(
f"room{counter}",
"",
{},
False,
None,
False,
None,
False,
None,
True,
(r, c)
)
counter += 1
def findExits():
counter = 1;
for x in range(len(world)):
if rooms[world[f"room{counter}"].coords[0]] + 1 == 1:
pass
def fillRooms():
counter = 1
for x in range(len(world)):
x = random.randrange(1, 2)
if x == 1:
world[f"room{counter}"].hasItem = True
x = random.randrange(1, 10)
if x == 1:
world[f"room{counter}"].hasWeapon = True
x = random.randrange(1, 4)
if x == 1:
world[f"room{counter}"].hasEnemy = True
counter += 1
############################################################
generateLevel()
makeRoomsForLevel()
findExits()
WoodenSword = Weapon("Wooden Sword", 5, "A wooden sword. Looks like a kid's toy.")
IronDagger = Weapon("Iron Dagger", 8, "Small, sharp, and pointy. Good for fighting monsters!")
HealthPot = Item("Health Potion", 1, "A Potion of Instant Health. Restores 10 Health.")
goblin1 = Enemy(25, 2, True, [HealthPot, IronDagger], True)
player = Player(10, 10, 5, 5, "", [], [], True, "room1", "room1")
def ShowInv():
print("*******************************")
print("Name:", player.name)
print("Health:", player.health)
print("Weapons:")
for i in player.weapons:
print(" ===============================")
print(" Weapon:", i.name)
print(" Description:", i.description)
print(" Damage:", i.dmg)
print(" ===============================")
print("Items:")
for i in player.items:
print(" ===============================")
print(" Item:", i.name)
print(" Amount:", i.amt)
print(" Description:", i.description)
print(" ===============================")
print("*******************************")
def testItems(item):
exists = item in player.items
return exists
def fight(enemy):
print("Your Health:", player.health)
print("Enemy Health:", enemy.health)
ans = input("What would you like to do?\n>>")
if ans == "attack":
chance = random.randrange(1, 20)
if chance >= 10:
enemy.health -= player.dmg
else:
print("You did not roll high enough...\nYour turn has been passed...")
if ans == "heal":
chance = random.randrange(1, 20)
if testItems(HealthPot):
if chance >= 10:
x = 0
for item in player.items:
if item == HealthPot:
player.health += 10
if player.health > player.maxHealth:
player.health = player.maxHealth
item.amt -= 1
if item.amt <= 0:
player.items.pop(x)
break
x += 1
else:
print("You did not roll high enough...\nYour turn has been passed...")
if ans == "run":
chance = random.randrange(1, 20)
if chance >= 10:
player.MoveBack()
else:
print("You did not roll high enough...\nYour turn has been passed...")
if enemy.health > 0 and player.health > 0:
chance = random.randrange(1, 20)
if chance >= 10:
player.health -= enemy.dmg
else:
if enemy.health <= 0:
enemy.isAvile = False;
def testRoom():
if player.room.hasWeapon:
if player.room.isFirstVisit:
player.weapons.append(player.room.weapon)
if player.room.hasItem:
if player.room.isFirstVisit:
player.items.append(player.room.item)
if player.room.hasEnemy:
if player.room.isFirstVisit:
while player.room.enemy.health > 0:
fight(player.room.enemy)
player.room.isFirstVisit = False
while True:
command = input(">>")
if command in {"N", "S", "E", "W"}:
player.Move(command)
testRoom()
elif command == "look":
print(player.room.description)
print("Exits:", *','.join(list(player.room.exits.keys())))
elif command == "inv":
ShowInv()
elif command == "heal":
if testItems(HealthPot):
player.health += 10
if player.health > player.maxHealth:
player.health = player.maxHealth
else:
print("You don't have any", HealthPot.name, "\bs")
else:
print("Invalid Command")
IIUC, you need something like:
#find the name of the room given the coordinates
def findRoom(x, y):
for i in range(len(world)):
if world[f"room{i+1}"].coords == (x, y):
return f"room{i+1}"
return None
def findExits():
for i in range(len(world)):
x, y = world[f"room{i+1}"].coords
exits = dict()
#east
if rooms[x, y+1] == 1:
exits["E"] = findRoom(x, y+1)
#south
if rooms[x+1, y] == 1:
exits["S"] = findRoom(x+1, y)
#west
if rooms[x, y-1] == 1:
exits["W"] = findRoom(x, y-1)
#north
if rooms[x-1, y] == 1:
exits["N"] = findRoom(x-1, y)
world[f"room{i+1}"].exits = exits
After running the above, the exits for room1 look like:
>>> world["room1"].exits
{'E': 'room2', 'S': 'room4'}
You can work with the above structure, changing the keys and values as needed.

Python Scipy fsolve function returns roots which are equal to starting points

I need to get all roots of a scalar equation. But fsolve can only return 1 root for each call. So I design a self-call function find_root_recursively of fsolve. This function will call itself until the new root is equal the previous root, which means fsovle has found all roots and no more new roots will be added. I use this logic to end self calling. But in some cases fsolve will return a root which is exactly the same as starting point. one_root = start always. Obviously this start is not a root. So the list_root is always adding new roots, it never ends.
min_value = df_group['strike'].min()
start_point = int(float(min_value) * 0.8)
def find_root_by_small_step(function, start_0, increment):
start = start_0
one_root = fsolve(function, start)
def get_transaction_data(self, expiry_date, df_group):
return df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 1) & (df_group['position'] == 1)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 1) & (df_group['position'] == 0)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 0) & (df_group['position'] == 1)], \
df_group[df_group['expiration_date'] == expiry_date].loc[(df_group['type'] == 0) & (df_group['position'] == 0)]
def calculate_one_payoff(self, stock_price, df_long_call, df_short_call, df_long_put, df_short_put):
# buy call
df_buy_call_executed = df_long_call[stock_price >= df_long_call['strike']]
if len(df_buy_call_executed) > 0:
buy_call_executed_sum = ((stock_price - df_buy_call_executed['breakeven_price']) * df_buy_call_executed['option_amount']).sum()
else:
buy_call_executed_sum = 0
df_buy_call_noExec = df_long_call[stock_price < df_long_call['strike']]
if len(df_buy_call_noExec) > 0:
buy_call_noExec_sum = (-1 * df_buy_call_noExec['option_price'] * df_buy_call_noExec['option_amount']).sum()
else:
buy_call_noExec_sum = 0
# sell call
df_sell_call_executed = df_short_call[stock_price >= df_short_call['strike']]
if len(df_sell_call_executed) > 0:
sell_call_executed_sum = ((df_sell_call_executed['breakeven_price'] - stock_price) * df_sell_call_executed['option_amount']).sum()
else:
sell_call_executed_sum = 0
df_sell_call_noExec = df_short_call[stock_price < df_short_call['strike']]
if len(df_sell_call_noExec) > 0:
sell_call_noExec_sum = (df_sell_call_noExec['option_price'] * df_sell_call_noExec['option_amount']).sum()
else:
sell_call_noExec_sum = 0
# buy put
df_buy_put_executed = df_long_put[stock_price < df_long_put['strike']]
if len(df_buy_put_executed) > 0:
buy_put_executed_sum = ((df_buy_put_executed['breakeven_price'] - stock_price) * df_buy_put_executed['option_amount']).sum()
else:
buy_put_executed_sum = 0
df_buy_put_noExec = df_long_put[stock_price >= df_long_put['strike']]
if len(df_buy_put_noExec) > 0:
buy_put_noExec_sum = (-1 * df_buy_put_noExec['option_price'] * df_buy_put_noExec['option_amount']).sum()
else:
buy_put_noExec_sum = 0
# sell put
df_sell_put_executed = df_short_put[stock_price < df_short_put['strike']]
if len(df_sell_put_executed) > 0:
sell_put_executed_sum = ((stock_price - df_sell_put_executed['breakeven_price']) * df_sell_put_executed['option_amount']).sum()
else:
sell_put_executed_sum = 0
df_sell_put_noExec = df_short_put[stock_price >= df_short_put['strike']]
if len(df_sell_put_noExec) > 0:
sell_put_noExec_sum = (df_sell_put_noExec['option_price'] * df_sell_put_noExec['option_amount']).sum()
else:
sell_put_noExec_sum = 0
one_stock_price_sum = buy_call_executed_sum + buy_call_noExec_sum + sell_call_executed_sum + sell_call_noExec_sum + \
buy_put_executed_sum + buy_put_noExec_sum + sell_put_executed_sum + sell_put_noExec_sum
one_stock_price_sum = float(one_stock_price_sum)
return one_stock_price_sum
df_long_call, df_short_call, df_long_put, df_short_put = self.get_transaction_data(expiry_date, df_group)
find_root_by_small_step(function=calculate_one_payoff, start=start_point, increment=increment)
ticker type position expiration_date strike option_price option_amount breakeven_price
AAPL 1 0 2021-11-19 145.0000 5.1700 2500.0000 150.1700
AAPL 0 1 2021-11-19 145.0000 2.9700 2500.0000 142.0300
AAPL 0 1 2021-11-19 145.0000 2.7000 5000.0000 142.3000
AAPL 1 1 2021-11-19 145.0000 5.8500 5000.0000 150.8500
AAPL 1 1 2021-11-19 155.0000 1.6000 1050.0000 156.6000
True root = 139.9 and 159.0

I have multiple variables which sometimes have the same value, but not always, how to specify which part of the function to use python

I have this code:
AWomen = BWomen = CWomen = DWomen = EWomen = 1
def pointscalcwomen(value):
if value == AWomen:
print("AWomen")
if value < 12:
womenspoints = 105 - 5 * (int(AWomen))
elif value < 61:
womenspoints = 61 - AWomen
else:
womenspoints = 1
elif value == BWomen:
print("BWomen")
if value < 7:
womenspoints = 80 - 5 * (int(BWomen))
elif value < 56:
womenspoints = 56 - BWomen
else:
womenspoints = 1
elif value == CWomen:
print("CWomen")
if value < 51:
womenspoints = 51 - CWomen
else:
womenspoints = 1
elif value == DWomen:
print("DWomen")
if value < 31:
womenspoints = 31 - DWomen
else:
womenspoints = 1
elif value == EWomen:
print("EWomen")
if value < 12:
womenspoints = 105 - 5 * (int(EWomen))
elif value < 61:
womenspoints = 61 - EWomen
else:
womenspoints = 1
return womenspoints
for row in reader:
if "A" in row[0]:
points = pointscalcwomen(AWomen)
print(points)
AWomen = AWomen + 1
elif "B" in row[0]:
points = pointscalcwomen(BWomen)
print(points)
BWomen = BWomen + 1
elif "C" in row[0]:
points = pointscalcwomen(CWomen)
print(points)
CWomen = CWomen + 1
elif "D" in row[0]:
points = pointscalcwomen(DWomen)
print(points)
DWomen = DWomen + 1
elif "E" in row[0]:
points = pointscalcwomen(EWomen)
print(points)
EWomen = EWomen + 1
AWomen/BWomen etc. is category as Category A women, I have AMen, BMen etc. but with the men I am unlikely to ever encounter this problem.
However, I am facing the problem that if A is never in row[0], then the first B will get 100 points, not 75 etc.
This is because at that point value == AWomen == BWomen, is there a way to get around this. I have thought of changing my code to something like:
elif "B" in row[0]:
A = 10000
points = pointscalcwomen(BWomen)
B = B + 1
This would make the script work most of the time as in the CSV row[0] will generally follow the pattern:
A
A
A
A
B
B
B
C
C
However, if there is the case where it is:
A
A
B
A
B
B
then it would not work as the A in the fourth row who was beaten by a B would get 1 point instead of 90.

binary search implementation with python [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
I think I did everything correctly, but the base case return None, instead of False if the value does not exists. I cannot understand why.
def binary_search(lst, value):
if len(lst) == 1:
return lst[0] == value
mid = len(lst)/2
if lst[mid] < value:
binary_search(lst[:mid], value)
elif lst[mid] > value:
binary_search(lst[mid+1:], value)
else:
return True
print binary_search([1,2,4,5], 15)
You need to return the result of the recursive method invocation:
def binary_search(lst, value):
#base case here
if len(lst) == 1:
return lst[0] == value
mid = len(lst)/2
if lst[mid] < value:
return binary_search(lst[:mid], value)
elif lst[mid] > value:
return binary_search(lst[mid+1:], value)
else:
return True
And I think your if and elif condition are reversed. That should be:
if lst[mid] > value: # Should be `>` instead of `<`
# If value at `mid` is greater than `value`,
# then you should search before `mid`.
return binary_search(lst[:mid], value)
elif lst[mid] < value:
return binary_search(lst[mid+1:], value)
Because if return nothing!
if lst[mid] < value:
binary_search(lst[:mid], value)
# hidden return None
elif lst[mid] > value:
binary_search(lst[mid+1:], value)
# hidden return None
else:
return True
You need to return from if and elif too.
def binary_search(lst, value):
#base case here
if len(lst) == 1:
return lst[0] == value
mid = len(lst) / 2
if lst[mid] < value:
return binary_search(lst[:mid], value)
elif lst[mid] > value:
return binary_search(lst[mid+1:], value)
else:
return True
>>> print binary_search([1,2,4,5], 15)
False
Binary Search:
def Binary_search(num,desired_value,left,right):
while left <= right:
mid = (left + right)//2
if desired_value == num[mid]:
return mid
elif desired_value > num[mid]:
left = mid + 1
else:
right = mid - 1
return -1
num =[12,15,19,20,22,29,38,41,44,90,106,397,399,635]
desired_value = 41
result = Binary_search(num,desired_value,0,len(num)-1)
if result != -1:
print("Number found at " + str(result),'th index')
else:
print("number not found")
def rBinarySearch(list,element):
if len(list) == 1:
return element == list[0]
mid = len(list)/2
if list[mid] > element:
return rBinarySearch( list[ : mid] , element )
if list[mid] < element:
return rBinarySearch( list[mid : ] , element)
return True
def binary_search(lists,x):
lists.sort()
mid = (len(lists) - 1)//2
if len(lists)>=1:
if x == lists[mid]:
return True
elif x < lists[mid]:
lists = lists[0:mid]
return binary_search(lists,x)
else:
lists = lists[mid+1:]
return binary_search(lists,x)
else:
return False
a = list(map(int,input('enter list :').strip().split()))
x = int(input('enter number for binary search : '))
(binary_search(a,x))
def binary_search(arr, elm):
low, high = 0, len(arr) - 1
while low <= high:
mid = (high + low) // 2
val = arr[mid]
if val == elm:
return mid
elif val <= elm:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([2, 3, 4, 6, 12, 19, 20, 21], 12)) # 4
print(binary_search([2, 3, 4, 6, 12, 19, 20, 21], 3333)) # -1
def Binary_search(li, e, f, l):
mid = int((f+l)/2)
if li[mid] == e:
print("Found",li[mid] )
elif f == l-1 and li[mid] != e:
print("Not Found ")
elif e < li[mid]:
Binary_search(li, e, f,mid)
elif e > li[mid]:
Binary_search(li, e, mid,l)
elements = [1,2,4,6,8,9,20,30,40,50,60,80,90,100,120,130,666]
Binary_search(elements, 120, 0, len(elements))
class binar_search:
def __init__(self,arr , element):
self.arr = arr
self.element = element
def search(self):
n = len(self.arr)
low = 0
high = n-1
while(low <= high):
mid = (low+high)//2
if self.arr[mid] == self.element:
return mid
elif self.arr[mid] < self.element:
low = mid+1
else:
high = mid -1
return 0

How do I properly use a Callback in this code? (Kivy)

Why does this code not work? I think it's something to do with x1 being already defined because I get the error "UnboundLocalError: local variable 'x1' referenced before assignment" whenever I click b1. Please I've searched the entire Internet with no luck.... Sorry I'm relatively new to Python and programming.
import calendar
import datetime
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
now = datetime.datetime.now()
h = now.hour
m = now.minute
s = now.second
year = now.year
month = now.month
day = now.day
home = 'home.'
weekday1 = calendar.weekday(year, month, day)
if len(str(m)) == 1:
zero = '0'
else:
zero = ''
if len(str(s)) == 1:
zero1 = '0'
else:
zero1 = ''
if weekday1 == 0:
day = 'Monday'
time = '''Period 1/2/3/4 = History
Period 5/6 = Japanese'''
if h == 8 and m >= 40:
current = 'Homeroom.'
elif h == 9 or (h == 10 and m <= 40):
current = 'History.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 or (h == 12 and m <= 40):
current = 'History.'
elif (h == 12 and m > 40) or (h == 13 and m <= 20):
current = 'lunch.'
elif (h == 13 and m > 20) or h == 14:
current = 'Japanese.'
else:
current = home
elif weekday1 == 1:
day = 'Tuesday'
time = '''Period 1 = English
Period 2 = Maths
Period 3/4 = English
Period 5/6 = ICT'''
if h == 8 and m>= 40:
current = 'Homeroom.'
elif h == 9 and m <= 50:
current = 'English.'
elif (h == 9 and m > 50) or (h == 10 and m <= 40):
current = 'Maths.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 or (h == 12 and m <= 40):
current = 'English.'
elif (h == 12 and m > 40) or (h == 13 and m <= 20):
current = 'lunch.'
elif (h == 13 and m > 20) or h == 14:
current = 'ICT.'
else:
current = home
elif weekday1 == 2:
day = 'Wednesday'
time = '''Period 1/2 = Science Extended
Period 3 = English
Period 4 = Maths
Period 5/6 = Science'''
if h == 8 and m >= 40:
current = 'Homeroom.'
elif h == 9 or (h == 10 and m <= 40):
current = 'Science Extended.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 and m <= 50:
current = 'English.'
elif (h== 11 and m > 50) or (h == 12 and m <= 40):
current = 'Maths.'
elif (h == 12 and m > 40) or (h == 13 and m <= 20):
current = 'lunch.'
elif (h == 13 and m > 20) or h == 14:
current = 'Science.'
else:
current = home
elif weekday1 == 3:
day = 'Thursday'
time = '''Period 1/2 = Art
Period 3 = Science
Period 4 = Wellbeing
Period 5 = English
Period 6 = Maths'''
if h == 8 and m >= 40:
current = 'Homeroom.'
elif (h == 10 and m <= 40) or h == 9:
current = 'Art.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 and m <= 50:
current = 'Science.'
elif (h == 11 and m > 50) or (h == 12 and m <= 40):
current = 'Wellbeing.'
elif (h == 12 and m > 40) or (h == 13 and m < 20):
current = 'lunch.'
elif (h == 13 and m >= 20) or (h == 14 and m <= 10):
current = 'English.'
elif h == 14 and m > 10:
current = 'Maths.'
else:
current = home
elif weekday1 == 4:
day = 'Friday'
time = '''Period 1/2 = PE
Period 3 = English
Period 4 = Maths
Period 5/6 = Music'''
if h == 8 and m >= 40:
current = 'Homeroom.'
elif h == 9 or (h == 10 and m <= 40):
current = 'PE.'
elif h == 10 and m > 40:
current = 'recess.'
elif h == 11 and m <= 50:
current = 'English.'
elif (h == 11 and m > 50) or (h == 12 and m <= 40):
current = 'Maths.'
elif (h == 12 and m > 40) or (h == 13 and m < 20):
current = 'lunch.'
elif (h == 13 and m >= 20) or h == 14:
current = 'Music.'
else:
current = home
else:
day = 'a weekend'
time = 'You have none.'
if day == 'a weekend':
a = "You don't have to be anywhere."
else:
a = ('You should be at ' + current)
a1 = ('Today is ' + day + '.')
a2 = ('''Today your timetable is:
''' + time)
a3 = ('The current time is ' + str(h) + ':' + zero + str(m) + ':' + zero1 + str(s) + '.')
t1 = 'What is the day today?'
t2 = 'What is the current time?'
t3 = 'What is my timetable today?'
t4 = 'Where should I be?'
x1, x2, x3, x4 = '', '', '', ''
def callback1(object):
del x1
x1 = a1
def callback2(object):
x2 = a3
def callback3(object):
x3 = a2
def callback4(object):
x4 = a
b1 = Button(text = t1)
b1.bind(on_press = callback1)
layout = GridLayout(cols = 2)
layout.add_widget(b1)
layout.add_widget(Label(text = x1))
layout.add_widget(Button(text = t2))
layout.add_widget(Label(text = x2))
layout.add_widget(Button(text = t3))
layout.add_widget(Label(text = x3))
layout.add_widget(Button(text = t4))
layout.add_widget(Label(text = x4))
class TimeTable(App):
def build(self):
return layout
if __name__ == '__main__':
TimeTable().run()
Your error is because you try to delete a global variable (x1) in a local context (callback1), without declaring it as global before.
You could do:
global x1
del x1
But there is a more general issue with what you are trying to accomplish, when you say text = x1, it just passes the current value of x1 to the text property of the Label you create, and changing the value of x1 later has no effect on this, what you want is to change widget.text to the new value (and you should rename object to widget in these callbacks, object is the name of the base class in python, so you shouldn't use it as a parameter or anything).
Also, the way you structure your code won't work well in the long term, you should do more things in methods of your class (most of what you do before could be done in build).

Categories