Python Class Setters Not Changing Variables - python

The closest thread I could find to my problem was this: Python setter does not change variable
It didn't really help, the volume and the channels are not changing at all. The first fucntion which is to "watch TV" works perfectly fine.
class TV(object):
def __init__(self, channel, volume):
self.__channel = channel
self.__volume = volume
def __str__(self):
out = ""
out += "You're on channel #" + str(self.__channel) + ", " + self.channelNetwork()
out += "\nVolume is currently at: " + str(self.__volume) + "/20"
return out
# a method that determines the name for each channel from 1-10
def channelNetwork(self):
c = self.__channel
if c == 1:
return "CBS"
elif c==2:
return "NBC"
elif c==3:
return "ABC"
elif c==4:
return "Fox"
elif c==5:
return "ESPN"
elif c==6:
return "PBS"
elif c==7:
return "CNN"
elif c==8:
return "Comedy Central"
elif c==9:
return "Cartoon Network"
elif c==10:
return "Nicklodeon"
# a volume slider that has a range from 0-20
def volumeSlider(self, newVolume):
v = self.__volume
if newVolume == "+":
v += 1
else:
v -= 1
if v < 0:
v = 0
if v > 20:
v = 20
def channelChanger(self, newChannel):
c = self.__channel
if newChannel == "+":
c += 1
else:
c -= 1
if c < 0:
c = 0
if c > 10:
c = 10
def main():
import random
randomChannel = random.randint(1,10)
randomVolume = random.randrange(21)
televsion = TV(randomChannel, randomVolume)
choice = None
while choice != "0":
print \
("""
TV Simulator
0 - Turn off TV
1 - Watch TV
2 - Change channel
3 - Change volume
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Have a good day! :)")
elif choice == "1":
print("You relax on your couch and watch some TV")
print(televsion)
elif choice == "2":
newChannel = None
while newChannel not in ('+', '-'):
newChannel = input("\nPress '+' to go up a channel and press '-' to go down a channel: ")
televsion.channelChanger(newChannel)
elif choice == "3":
newVolume = None
while newVolume not in ('+', '-'):
newVolume = input("\nPress '+' to increase volume and press '-' to decrease volume: ")
televsion.volumeSlider(newVolume)
else:
print("\nSorry, but", choice, "isn't a valid choice.")
main()
input("\n\nPress enter to exit.")

The problem is, that when you do:
v = self.__volume
In:
def volumeSlider(self, newVolume):
v = self.__volume
if newVolume == "+":
v += 1
else:
v -= 1
if v < 0:
v = 0
if v > 20:
v = 20
Assigning to v won't affect self.__volume. You need to use self.__volume = 20 or whatever.
As an aside, don't use double-underscore name-mangling unless you actually need it. E.g. self.volume is fine.

Related

Can't print binary heap in python

I try to make a binary heap in python but I get trouble printing it. I make sure that the logic in the program is right but when I want to try printing it I get the wrong result. This is what I want for program output:
Input:
6
1 2
1 3
1 7
2
3
2
Output:
7
3
command 1 to insert number
command 2 to display the highest number
command 3 to delete the highest number
This is my program:
class BinaryHeap:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def parent(self, i):
return (i - 1)//2
def left(self, i):
return 2*i + 1
def right(self, i):
return 2*i + 2
def get(self, i):
return self.items[i]
def get_max(self):
if self.size() == 0:
return None
return self.items[0]
def extract_max(self):
if self.size() == 0:
return None
largest = self.get_max()
self.items[0] = self.items[-1]
del self.items[-1]
self.max_heapify(0)
return largest
def max_heapify(self, i):
l = self.left(i)
r = self.right(i)
if (l <= self.size() - 1 and self.get(l) > self.get(i)):
largest = l
else:
largest = i
if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
largest = r
if (largest != i):
self.swap(largest, i)
self.max_heapify(largest)
def swap(self, i, j):
self.items[i], self.items[j] = self.items[j], self.items[i]
def insert(self, key):
index = self.size()
self.items.append(key)
while (index != 0):
p = self.parent(index)
if self.get(p) < self.get(index):
self.swap(p, index)
index = p
bheap = BinaryHeap()
n = int(input())
for i in range (n):
operation= input('What would you like to do? ').split()
if operation == 1:
data = int(operation[1])
bheap.insert(data)
elif operation == 2:
print('Maximum value: {}'.format(bheap.get_max()))
elif operation == 3:
print('Maximum value removed: {}'.format(bheap.extract_max()))
elif operation == 4:
break
I need your opinion to fixed it.
operation is a list (you called split), but you compare it as an int in your if statements. Also, you should compare it against "1", "2", ... not 1, 2, ...
So:
operation = input('What would you like to do? ').split()
if operation[0] == "1":
data = int(operation[1])
bheap.insert(data)
elif operation[0] == "2":
print('Maximum value: {}'.format(bheap.get_max()))
elif operation[0] == "3":
print('Maximum value removed: {}'.format(bheap.extract_max()))
elif operation[0] == "4":
break
If you just want 7 and 3 in the output, and only after the input has been completely processed, then you should remove those verbose print statement (where you output phrases), and instead collect the output -- for instance in a list:
output = []
n = int(input())
for i in range(n):
operation = input('What would you like to do? ').split()
if operation[0] == "1":
data = int(operation[1])
bheap.insert(data)
elif operation[0] == "2":
output.append(bheap.get_max())
elif operation[0] == "3":
bheap.extract_max()
elif operation[0] == "4":
break
print("\n".join(map(str, output)))

Issue with variable defining

When I execute the following code, I get the error "player_normal_defense is not defined". I get what the issue is but if I had to define the variable inside the Defense function, it would be totally pointless since the variable stores the initial defense value for further usage. How should I solve this?
import random
import sys
import os
import time
from Entity import *
class Battle():
def Attack(self, attacker, defender):
damage = attacker.atk - defender.dif
defender.hp -= damage
def Defense(self, owner, defending, entity_id):
defense_boost = 10
if defending:
owner.dif += defense_boost
elif not defending:
if entity_id == 1:
owner.dif = player_normal_defense
elif entity_id == 2:
owner.dif = enemy_normal_defense
def Turn_Generator(self, pl, en):
turns_list = []
speed_product = pl.speed / en.speed
first_speed_product = speed_product
if speed_product >= 1:
turns_list.append("P")
elif speed_product < 1:
turns_list.append("E")
while len(turns_list) < 100:
if speed_product >= 2:
turns_list.append("P")
turns_list.append("P")
speed_product = 0.6
elif speed_product < 2 and speed_product >= 1:
turns_list.append("P")
if first_speed_product <= 0.5:
speed_product = first_speed_product
else:
speed_product = 0.6
elif speed_product <= 0.5:
turns_list.append("E")
turns_list.append("E")
speed_product = 1
elif speed_product > 0.5 and speed_product < 1:
turns_list.append("E")
if first_speed_product >= 2:
speed_product = first_speed_product
else:
speed_product = 1
return turns_list
def Combat(self, player, enemy):
turn_counter = 1
player_normal_defense = player.dif
enemy_normal_defense = enemy.dif
fighting = True
while fighting:
print(f"Turn {turn_counter}")
turns = self.Turn_Generator(player, enemy)
for current_turn in turns:
print(f"""
======================
YOUR HPs: ENEMY HPs:
{player.hp} {enemy.hp}
======================""")
print(f"""
================
Current turn: {current_turn}
================
===========
Next turns:
{turns[1]}
{turns[2]}
{turns[3]}
{turns[4]}
===========
""")
if current_turn == "P":
choice = input("1. Attack\n2. Defend\n")
if choice == "1":
self.Attack(player, enemy)
self.Defense(player, False, 1)
elif choice == "2":
self.Defense(player, True, 1)
else:
print("Lost your chance!")
elif current_turn == "E":
enemy_choice = random.randint(1, 2)
if enemy_choice == 2:
print("He attacks you!")
self.Attack(enemy, player)
self.Defense(enemy, False, 2)
else:
print("He defends himself.")
self.Defense(enemy, True, 2)
time.sleep(3)
os.system("clear")
turns.pop(0)
if player.hp <= 0:
print("You died!")
sys.exit(0)
elif enemy.hp <= 0:
print("YOU WON!")
fighting = False
break
turn_counter += 1
When entity is defending, instead of running a Defence function to add a bonus to entitys Defence score only if it is true, I would just not run the Defence function when attacking. When entity is defending then you can run the Defense (Bonus) function as;
def Defending():
defence_boost = 10
in the decision check;
if choice == "2":
self.dif += Defending()
One issue I believe you will have with the code is that you are raising the entitys .dif stat with each occurrence of defending. This means that when this has cycled multiple times the base dif may be too high for any attackers damage to do anything to the opponents health.

Connect 4 implemented with python AI alpha-beta-pruning (Recursion/MemoryError)?

I'm trying to create a game called Connect Four with AI which uses the alpha-beta pruning algorithm in python. Here is the code I have managed to write:
# -*- coding: utf-8 -*-
import sys
class ConnectFour:
def __init__(self):
self.board = [[],[],[],[],[],[]]
for i in range(7):
for j in range(6):
self.board[j].append(" ")
self.moves = 0
self.colstack = [0,0,0,0,0,0,0]
self.node = 0
self.move = 0
def PrintGameBoard(self):
print(' 0 1 2 3 4 5 6')
for i in range(5, -1, -1):
print('|---|---|---|---|---|---|---|')
print("| ",end="")
for j in range(7):
print(self.board[i][j],end="")
if j != 6:
print(" | ",end="")
else:
print(" |")
print('`---------------------------´')
def CanPlay(self, col):
return self.colstack[col] < 6
def Play(self, col, board):
board[self.colstack[col]][col] = 2
self.colstack[col] += 1
self.moves += 1
return board
def IsWinning(self, currentplayer):
for i in range(6):
for j in range(4):
if self.board[i][j] == currentplayer and self.board[i][j+1] == currentplayer and self.board[i][j+2] == currentplayer and self.board[i][j+3] == currentplayer:
return True
for i in range(3):
for j in range(7):
if self.board[i][j] == currentplayer and self.board[i+1][j] == currentplayer and self.board[i+2][j] == currentplayer and self.board[i+3][j] == currentplayer:
return True
for i in range(3):
for j in range(4):
if self.board[i][j] == currentplayer and self.board[i+1][j+1] == currentplayer and self.board[i+2][j+2] == currentplayer and self.board[i+3][j+3] == currentplayer:
return True
for i in range(3,6):
for j in range(4):
if self.board[i][j] == currentplayer and self.board[i-1][j+1] == currentplayer and self.board[i-2][j+2] == currentplayer and self.board[i-3][j+3] == currentplayer:
return True
return False
def AlphaBeta(self, alpha, beta):
self.node += 1
if self.moves == 42:
return 0
for col in range(7):
if self.CanPlay(col) and self.IsWinning(2):
return (43 - self.moves)/2
max = (41 - self.moves)/2
if beta > max:
beta = max
if alpha >= beta:
return beta
for col in range(7):
if self.CanPlay(col):
self.board[self.colstack[col]][col] = 2
self.move = col
score = -self.AlphaBeta(-alpha, -beta)
if score >= beta:
return score
elif score > alpha:
alpha = score
self.board[self.colstack[col]][col] = " "
def Solve(self, table, week=False):
self.node = 0
self.board = table
if week:
self.AlphaBeta(-1, 1)
self.board = self.Play(self.move, table)
return self.board
else:
self.AlphaBeta(-21, 21)
self.board = self.Play(self.move, table)
return self.board
def PlayerMove(self, table):
self.board = table
try:
allowedmove = False
while not allowedmove:
print("Choose a column where you want to make your move (0-6): ",end="")
col =input()
if self.CanPlay(int(col)):
self.board[self.colstack[int(col)]][int(col)] = 1
self.moves += 1
self.colstack[int(col)] += 1
allowedmove = True
else:
print("This column is full")
except (NameError, ValueError, IndexError, TypeError, SyntaxError) as e:
print("Give a number as an integer between 0-6!")
else:
return self.board
def PlayerMark():
print("Player 1 starts the game")
mark = ''
while not (mark == "1" or mark == "2"):
print('Do you want to be 1 or 2: ',end="")
mark = input()
if mark == "1":
return 1
else:
return 2
def PlayAgain():
print('Do you want to play again? (yes or no) :',end="")
return input().lower().startswith('y')
def main():
sys.setrecursionlimit(2000)
print("Connect4")
while True:
mark = PlayerMark()
connectfour = ConnectFour()
if mark==1:
print("You are going to start the game\r\n\r\n")
else:
print("Computer (negamax) starts the game")
gameisgoing = True
table = [[],[],[],[],[],[]]
for i in range(7):
for j in range(6):
table[j].append(" ")
while gameisgoing:
connectfour.PrintGameBoard()
if mark == 1:
table = connectfour.PlayerMove(table)
if connectfour.IsWinning(1):
connectfour.PrintGameBoard()
print('You won the game!')
gameisgoing = False
else:
if connectfour.moves==42:
connectfour.PrintGameBoard()
print('Game is tie')
break
else:
mark = 2
else:
move = connectfour.Solve(table)
if connectfour.IsWinning(2):
connectfour.PrintGameBoard()
print('Computer won the game')
gameisgoing = False
else:
if connectfour.moves==42:
connectfour.PrintGameBoard()
print('Game is tie')
break
else:
mark = 1
if not PlayAgain():
print("Game ended")
break
if __name__ == '__main__':
main()
I'm not sure if the algorithm is working properly, but the problem is that I get RecursionError: maximum recursion depth exceeded in comparison. If I increase recursionlimit I get in around 10000 MemoryError: Stack Overflow. I think that the problem is that there is too many states to handle for my computer. That's why I changed the negamax algorithm to alpha-beta pruning, but there seem to be still to many states. Is there a effective technique that does algorithmic search, for example max depth 10 and still the computer is almost invincible? I'm waiting your solutions.

MVC infrastructure

import random
class Spinner(object):
#staticmethod
def getSpin():
newSpin = random.randint(1,6)
return newSpin
class Player(object):
def __init__(self,name):
self.position = 1
self.name = name
def setName(self,name):
self.name = name
def changePosition(self,number):
self.position = self.position + number
def setPosition(self,pos):
self.position = pos
return self.position
def getPosition(self):
return self.position
def getName(self):
return self.name
def spin(self):
newSpin = Spinner.getSpin()
self.position = self.position + newSpin
print(str(self.name) + "'s spin was: " + str(newSpin))
class Display():
def buildLadders():
ladders = [[0 for x in range(2)] for x in range(2)]
ladders[0][0] = 2
ladders[0][1] = 7
ladders[1][0] = 4
ladders[1][1] = 5
return ladders
def buildChutes():
chutes = [[0 for x in range(2)] for x in range(2)]
chutes[0][0] = 9
chutes[0][1] = 2
chutes[1][0] = 6
chutes[1][1] = 3
return chutes
class Check(Player):
def checkLadders(self):
ladders = Display.buildLadders()
for i in range(0,len(ladders),1):
if self.getPosition() == ladders[i][0]:
self.position = self.setPosition(ladders[i][1])
print(str(self.name) + " Landed on a Ladder! from " + \
str(ladders[i][0]) +" to " + str(ladders[i][1]))
def checkChutes(self):
chutes = Display.buildChutes()
for i in range(0,len(chutes),1):
if self.getPosition() == chutes[i][0]:
self.position = self.setPosition(chutes[i][1])
print(str(self.name) + " Landed on a Chutes! from " + \
str(chutes[i][0]) + " to " + str(chutes[i][1]))
def checkQuestions(num):
one = random.randint(num,num*10)
two = random.randint(num,num*10)
listqq = [one,two]
return listqq
class Controller(object):
def __init__(self,names):
self.winner = ''
self.players = []
for n in names:
p = Player(n)
self.players.append(p)
def move(self):
players = self.players
winner = self.winner
click = ''
count = 1
while True:
for i in range(0,len(players)):
if winner == '' and click != 'e':
print("----" + str(players[i].getName()) + "'s TURN----")
click = input("Press r to roll or e to exit: ")
while click != 'r' and click != 'e':
click = input("Press r to roll or e to exit: ")
if click == 'r' and click != 'e':
count = count + 1
listqq = Check.checkQuestions(count)
answer = input(str(listqq[0]) + ' + ' + str(listqq[1]) +' is:')
if answer == str(listqq[0]+listqq[1]):
print(str(players[i].getName()) + "'s initial position is " \
+ str(players[i].getPosition()))
View(players).display()
players[i].spin()
Check.checkLadders(players[i])
Check.checkChutes(players[i])
else:
pass
if players[i].getPosition() >= 12:
players[i].position = players[i].setPosition(12 - (players[i].getPosition() - 12))
print(str(players[i].getName()) + "'s new position is " \
+ str(players[i].getPosition()))
View(players).display()
if players[i].getPosition() == 12:
winner = players[i].getName()
if click == 'e' and click != 'r':
print('Bye')
break
if winner != '':
print(str(winner) + " is the winner!!!")
break
class View(Player):
def __init__(self,player):
self.players = player
def display(self):
players = self.players
listof = [9,10,11,12,8,7,6,5,1,2,3,4]
ladders = Display.buildLadders()
chutes = Display.buildChutes()
board = [[]] * 3
for i in range(len(players)):
for j in range(len(listof)):
if self.players[i].position == listof[j]:
listof[j] = 'X'
for j in range(len(listof)):
for i in range(len(ladders)):
if ladders[i][0] == listof[j]:
listof[j] = 'L'
for j in range(len(listof)):
for i in range(len(chutes)):
if chutes[i][0] == listof[j]:
listof[j] = 'C'
for i in range(0,4):
board[0] = board[0] + [listof[i]]
for i in range(4,8):
board[1] = board[1] + [listof[i]]
for i in range(8,12):
board[2] = board[2] + [listof[i]]
for row in board:
for num in row:
if num == 'X':
print(" X", end=" ")
if num == 'L':
print(" L", end= " ")
if num == 'C':
print(" C", end= " ")
if num != 'X' and num != 'L' and num != 'C':
if 10 <= num <= 20:
print(num,end=" ")
if num != 'X' and num != 'L' and num!= 'C':
if 1 <= num <= 9:
print(str(num).rjust(2), end= " ")
print()
def main():
n = input("Please enter number of players: ")
names = []
for i in range (0,int(n)):
name = input("Please input your name: ")
names.append(name)
game = Controller(names)
game.move()
while True:
ask = input("Do you want to play again? (y/n)")
if ask == 'y':
game = Controller(names)
game.move()
if ask == 'n':
print("Bye, see you again!")
break
main()
fixed version:
import random
class Player(object):
def __init__(self,name):
self.position = 1
self.name = name
def setName(self,name):
self.name = name
def changePosition(self,number):
self.position = self.position + number
def setPosition(self,pos):
self.position = pos
return self.position
def spin(self):
newSpin = self.getSpin()
self.position = self.position + newSpin
print(str(self.name) + "'s spin was: " + str(newSpin))
def checkLadders(self):
ladders = self.buildLadders()
for i in range(0,len(ladders),1):
if self.position == ladders[i][0]:
self.position = self.setPosition(ladders[i][1])
print(str(self.name) + " Landed on a Ladder! from " + \
str(ladders[i][0]) +" to " + str(ladders[i][1]))
def checkChutes(self):
chutes = self.buildChutes()
for i in range(0,len(chutes),1):
if self.position == chutes[i][0]:
self.position = self.setPosition(chutes[i][1])
print(str(self.name) + " Landed on a Chutes! from " + \
str(chutes[i][0]) + " to " + str(chutes[i][1]))
#staticmethod
def checkQuestions(num):
one = random.randint(num,num*10)
two = random.randint(num,num*10)
listqq = [one,two]
return listqq
#staticmethod
def getSpin():
newSpin = random.randint(1,6)
return newSpin
#staticmethod
def buildLadders():
ladders = [[0 for x in range(2)] for x in range(2)]
ladders[0][0] = 2
ladders[0][1] = 7
ladders[1][0] = 4
ladders[1][1] = 5
return ladders
#staticmethod
def buildChutes():
chutes = [[0 for x in range(2)] for x in range(2)]
chutes[0][0] = 9
chutes[0][1] = 2
chutes[1][0] = 6
chutes[1][1] = 3
return chutes
class Controller(object):
def __init__(self,names):
self.winner = ''
self.players = []
for n in names:
p = Player(n)
self.players.append(p)
def move(self):
players = self.players
winner = self.winner
click = ''
count = 1
while True:
for i in range(0,len(players)):
if winner == '' and click != 'e':
print("----" + str(players[i].name) + "'s TURN----")
click = input("Press r to roll or e to exit: ")
while click != 'r' and click != 'e':
click = input("Press r to roll or e to exit: ")
if click == 'r' and click != 'e':
count = count + 1
listqq = Player.checkQuestions(count)
answer = input(str(listqq[0]) + ' + ' + str(listqq[1]) +' is:')
if answer == str(listqq[0]+listqq[1]):
print(str(players[i].name) + "'s initial position is " \
+ str(players[i].position))
View(players).display()
players[i].spin()
Player.checkLadders(players[i])
Player.checkChutes(players[i])
else:
pass
if players[i].position >= 12:
players[i].position = players[i].setPosition(12 - (players[i].getPosition() - 12))
print(str(players[i].name) + "'s new position is " \
+ str(players[i].position))
View(players).display()
if players[i].position == 12:
winner = players[i].name
if click == 'e' and click != 'r':
print('Bye')
break
if winner != '':
print(str(winner) + " is the winner!!!")
break
class View():
def __init__(self,player):
self.players = player
def display(self):
players = self.players
listof = [9,10,11,12,8,7,6,5,1,2,3,4]
ladders = Player.buildLadders()
chutes = Player.buildChutes()
board = [[]] * 3
for i in range(len(players)):
for j in range(len(listof)):
if self.players[i].position == listof[j]:
listof[j] = 'X'
for j in range(len(listof)):
for i in range(len(ladders)):
if ladders[i][0] == listof[j]:
listof[j] = 'L'
for j in range(len(listof)):
for i in range(len(chutes)):
if chutes[i][0] == listof[j]:
listof[j] = 'C'
for i in range(0,4):
board[0] = board[0] + [listof[i]]
for i in range(4,8):
board[1] = board[1] + [listof[i]]
for i in range(8,12):
board[2] = board[2] + [listof[i]]
for row in board:
for num in row:
if num == 'X':
print(" X", end=" ")
if num == 'L':
print(" L", end= " ")
if num == 'C':
print(" C", end= " ")
if num != 'X' and num != 'L' and num != 'C':
if 10 <= num <= 20:
print(num,end=" ")
if num != 'X' and num != 'L' and num!= 'C':
if 1 <= num <= 9:
print(str(num).rjust(2), end= " ")
print()
def main():
n = input("Please enter number of players: ")
names = []
for i in range (0,int(n)):
name = input("Please input your name: ")
names.append(name)
game = Controller(names)
game.move()
while True:
ask = input("Do you want to play again? (y/n)")
if ask == 'y':
game = Controller(names)
game.move()
if ask == 'n':
print("Bye, see you again!")
break
main()
Is this following the MVC infrastructure? How to know if it fits the MVC structure or not? Thanks. Does we have to put each model,view,and controller in different module for it to be described as following the MVC structure?
First off the program is not really object oriented. View is instanciated every time when the game state has to be displayed just to call the one and only method. Classes with just the __init__() and one other method are a code smell because, like in this case, it's just a function crammed into a class for no good reason. The same can be said about Control — also just the __init__() and one additional method that get's called exactly once right after instanciating the object and directly after the call the object isn't used anymore.
Taking those ”fake” classes and considering the amount of static methods it seems you are under the impression classes automatically lead to object oriented programs — they don't. And there is nothing wrong with using functions instead of artificially introducing unnecessary complexity with classes that are just syntactically classes. Functions are objects too in Python, so when you have a display function it's okay to pass that around as „view” part of an MVC pattern. It's a callable object.
Which brings us to the MVC question: Supposing Player is the model then it should not interact with the user by printing stuff. Display and input is for the view to handle. So Control isn't a controller because the function in disguise also heavily interacts with the user via print() and input().

How to return the nth value of a Dict?

I have this dict for example and i wish to return the nth value of it
d = {'Hello':4, 'World':17, 'Hi':2, 'Again':46}
Note: I know that dicts are unordered, and i don't care i just want to return all the keys one after the other.
In my program I just want to make calculations with the values, and the keys will be a user input so we don't know the keys.
How can i return the nth value in this dict like this?
Hereis the full code of y progam, error is located in 2nd def function, on line 23
#Subroutines
def dumptodaydate():
import pickle
with open('LastOpenDate.txt', 'wb') as DOT:
import time
ODate = time.strftime('%d')
OMonth = time.strftime('%m')
OYear = time.strftime('%Y')
List = {'Day':ODay, 'Month':OMonth, 'Year':OYear}
pickle.dump(List, DOT)
def caltimelefttask():
import pickle
with open('LastOpenDate.txt', 'rb') as LOD:
List = pickle.load(LOD)
from datetime import date
Today = date.today()
ODay = List['Day']
OMonth = List['Month']
OYear = List['Year']
DifDay = (Today(eval(OYear),eval(OMonth), eval(ODay)).days
for key in Lesson:
OTimetask = Lesson[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Lesson[key]['Rating'] = Rating
for key in Exercises.keys():
OTimetask = Exercises[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Exercises[key]['Rating'] = Rating
for key in Assignment.keys():
OTimetask = Assignment[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Assignment[key]['Rating'] = Rating
def loadtxt():
import pickle
with open('LessonOut.txt', 'rb') as Li:
Lesson = pickle.load(Li)
with open('ExercisesOut.txt', 'rb') as Ei:
Exercises = pickle.load(Ei)
with open('AssignmentOut.txt', 'rb') as Ai:
Assignment = pickle.load(Ai)
def ADD():
print('Name of task? (Keep it short for convenience Example: Math1)\n(Must be diferent from any other non deleted tasks)')
Name = input('>>>')
print('Description of task? (this can be as long as you want)')
Desc = input('>>>')
print('Rate the time it takes you to do the task on a scale from 1 to 20')
Time = input('>>>')
print('Rate the importance of the task on a scale from 1 to 20')
Imp = input('>>>')
print('Rate how much you want to do it on a scale from 1 to 5 \n(1= want to do it, 5= don\'t want to')
Want = input('>>>')
print('enter deadline (day)')
TimeDay = input('>>>')
print('enter deadline (month)')
TimeMonth = input('>>>')
print('enter deadline(year)')
TimeYear = input('>>>')
print('what type of homework is it? (Lesson/Exercises/Assignment)')
TaskType = input('>>>')
from datetime import date
Today = date.today()
TaskForDate = date(eval(TimeYear), eval(TimeMonth), eval(TimeDay))
TimeLeftTemp = abs((TaskForDate - Today).days)
print ('You have', TimeLeftTemp, 'days to finish this task.')
Rating = eval(Time) + eval(Imp) + eval(Want) - (TimeLeftTemp * 2)
if TimeLeftTemp < 4:
Rating = Rating + 50
if TimeLeftTemp <= 0:
Rating = Rating + 50
if TaskType == 'Lesson':
Lesson[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Exercises':
Exercises[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Assignment':
Assignment[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
def DEL():
print ('What type of task is it? \nLesson, Exercises or Assignment)')
WhatDict = input('>>>')
if WhatDict == Lesson:
print(Lesson.keys())
if WhatDict == Exercises:
print(Exercises.keys())
if WhatDict == Assignment:
print(Assignment.keys())
print ('What task do you want do delete?')
WhatDel = input('>>>')
if WhatDict == 'Lesson':
try:
del Lesson[WhatDel]
except:
pass
elif WhatDict == 'Exercises':
try:
del Exercises[WhatDel]
except:
pass
elif WhatDict == 'Assignment':
try:
del Assignment[WhatDel]
except:
pass
pass
else:
print('Sorry, the type of task is not recognised, please try again.')
def sort_by_subdict(dictionary, subdict_key):
return sorted(dictionary.items(), key=lambda k_v: k_v[1][subdict_key])
def SHOW():
ShowWhat = input('What type of task do you want to do?\nLesson/Exercises/Assignment)\n>>>')
if ShowWhat == 'Lesson' or 'lesson':
print (sort_by_subdict(Lesson, 'Rating'))
elif ShowWhat == 'Exercises' or 'exercises':
print (sort_by_subdict(Exercises, 'Rating'))
elif ShowWhat == 'Assignment' or 'assignment':
print (sort_by_subdict(Assignment, 'Rating'))
else:
print('Type of task not recognosed, please try again')
def dumptxt():
import pickle
with open('LessonOut.txt', 'wb') as Lo:
pickle.dump(Lesson, Lo)
with open('ExercisesOut.txt', 'wb') as Eo:
pickle.dump(Exercises, Eo)
with open('AssignmentOut.txt', 'wb') as Ao:
pickle.dump(Assignment, Ao)
loadtxt()
while True:
print ('WARNING NEVER EXIT PROGRAM WITHOUT USING THE quit COMMAND,\nOR ALL ACTIONS DONE WILL BE LOST')
print ('Commands:')
print ('add (to add a task)')
print ('del (to delete a task)')
print ('quit (to exit program)')
print ('show (to see your tasks)')
Input = input('>>>')
if Input == 'add':
ADD()
elif Input == 'del':
DEL()
elif Input == 'show':
SHOW()
elif Input == 'quit':
print ('are you sure you want to quit? y/n')
Input = input('>>>')
if Input == 'y':
dumptxt()
quit()
elif Input == 'n':
print ('Not exiting')
else:
print ('Error, command not recognised')
This gives me a syntax error:
for key in Lesson:
#syntax error ^
# here
You can just enumerate over all the keys in the dict directly by using for key in d:
for key in d:
if d[key] < 20:
d[key] -= 4
else:
d[key] += 4

Categories