My task is to a read file named tasks.txt(where there are the tasks assign to each user and then I have compared with the username_storage list, if their names are in the tasks.txt files it should increase by one and then move to the other user, until the list is completed .
My task is to output the number of tasks assigned to each user.
I have tried to do that but it doesn't show me the exact number of tasks for each user, below you can see my code.
THIS IS THE TEXT FILE
admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will be using this program., 10 Oct 2019, 20 Oct 2019, No
admin, Assign initial tasks, Use taskManager.py to assign each team member with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No
banta, FCB, This task is to find new young talents for futbol club barcelona, 20 Jan 2023, 2023-01-07, Yes
banta, Programming, Why do you love to program, 31 Jan 2023, 2023-01-08, No
I have included that answer in the previous question`
MY FIRST TRY:
tasks_for_user = 0
username_storage = ['admin', 'banta', 'david,', 'hyperionDev', 'rebeca']
tasks = open("tasks.txt", "r")
i = 0
for task in tasks:
split = task.strip().split(", ")
while i < len(username_storage):
if username_storage[i] == split[0]:
tasks_for_user += 1
print(f"There are {tasks_for_user} tasks assigned to {username_storage[i]}")
i += 1
else:
tasks_for_user = 0
print(f"There are {tasks_for_user} tasks assigned to {username_storage[i]}")
i += 1
THIS IS THE OUTPUT
There are 1 tasks assigned to admin
There are 0 tasks assigned to banta
There are 0 tasks assigned to david,
There are 0 tasks assigned to hyperionDev
There are 0 tasks assigned to rebeca
MY SECOND TRY
for users_ in username_storage:
for task in tasks:
split = task.strip().split(", ")
if users_ == split[0]:
tasks_for_user += 1
else:
tasks_for_user += 0
print(f"There are {tasks_for_user} tasks assigned to {users_}")
THIS IS THE OUTPUT
There are 2 tasks assigned to admin
There are 2 tasks assigned to banta
There are 2 tasks assigned to david,
There are 2 tasks assigned to hyperionDev
There are 2 tasks assigned to rebeca
The problem is that the task_for_user is being applied to all of the different users. So it will keep being incremented not depending on who it is being incremented for. You could instead use a dictionary to map the tasks assigned to the user, this keeps the number of tasks localised to just that user.
Create an empty dictionary called task_count which will be used to store the number of tasks for each user.
tasks = open("tasks.txt", "r")
task_count = {}
for line in tasks:
task_info = line.strip().split(",")
username = task_info[0]
if username in task_count:
task_count[username] += 1
else:
task_count[username] = 1
for user in task_count:
print(f"There are {task_count[user]} tasks assigned to {user}")
Related
I am creating a flask web app which has a background task of making an API Calls every x seconds.The interval is decided based on a value coming from the API,if the value is True then and if the database don't have any data for counter it will insert a counter value 1.If it has a counter value it will increment the counter and update it on the database and the next call for this task will be after 40 seconds but if it is false the the next call will be in 10 seconds.Here is my code
import time
import threading
def writemotiondata():
processing = False
while True:
deviceid = 'eb4f7839b63063bdec3ikc'
openapi = authorization()
openapi.connect()
response = openapi.get("/v1.0/devices/{}".format(deviceid))
result = response['result']
status = result['status']
value = status[0]['value']
print(value)
if (value == True):
tempdata = motiondata.find()
previousdata = [{item: key[item] for item in key if item != '_id'} for key in tempdata]
if len(previousdata) == 0:
data = {"sensorname": "pir",
"numberofpeople": 1}
motiondata.insert_one(data).inserted_id
else:
count = previousdata[0]['numberofpeople']
count += 1
filter = {"sensorname": "pir"}
updateddata = {"$set": {"numberofpeople": count}}
motiondata.update_one(filter, updateddata)
time.sleep(40)
else:
time.sleep(10)
if __name__ == '__main__':
t1 = threading.Thread(target=writemotiondata)
t1.start()
app.run(debug=True)
Here the expected output is if the value is True the task should increment the counter and update the database.For example if the previous count was 1,after completing the task the new count should be 2 and the task should be called to execute again in 40 seconds. If the value is false the task will be called again in 10 seconds.
However The output I am getting is the counter in my database gets incremented inconsistently,sometimes it gets incremented by 1 ,sometimes it gets incremented by 2 or 3.I have printed out the value and saw in 40 seconds sometimes the value true is being printed 2/3 times instead of one,same goes for false.Basically the task is being executed more than once,in that time interval.Can anyone please help me figure out why is this happening and what I am doing wrong.
I am using a single thread,no more threads has been used in the code.
Im trying to add a function that will check the number of messages sent by a user within the last 2 days, right now im looping through all the channels history and checking the message 1 at a time, but with a guild that gets thousands of messages a day this takes a long time, is there a way that i can specify a max amount of time to look back?
heres my current code
# This is also inside of a cog
now = datetime.datetime.now()
joined_on = ctx.author.joined_at
delta = datetime.timedelta(joined_on, now)
if delta.days >= 2:
message = 0
for channel in ctx.guild.channels:
if channel.id != 863871156298055751:
for message in channel.messages:
sent_at = message.created_at
delta = datetime.timedelta(sent_at, now)
if delta.days <= 2 and message.author.id == ctx.author.id:
messages += 1
There is a version of the history that works on the channels. You can also specify a time frame to look at.
See TextChannel.history.
counter = 0
for channel in ctx.guild.channels:
try:
if not isinstance(channel, discord.TextChannel):
continue
# set a hard limit on the messages taken, or limit the amount of time to search
async for msg in channel.history(limit=100, after=datetime.datetime.utcnow()-datetime.timedelta(hours=1)):
# change this
if msg.author.id == ctx.author.id:
counter += 1
except discord.errors.Forbidden:
pass
await ctx.send(counter)
I hope someone can finally help. I am trying to write code to save tasks to a text file. The text file takes input from the user and stores the info. I would like to find a very simple way to change my following code to add a number to the task so that I will be able to call on the specific task later. After the first task is labelled User assigned to task 1: the next task should be labelled User assigned to task 2: and then task User assigned to task 3:
task example:
User assigned to task:
jack
Task Title:
jog
Task Description:
Go jogging
Task Due Date:
2020-02-08
Date Assigned:
2020-02-07
Task Completed:
No
requested output:
User assigned to task 1:
jack
Task Title:
jog
Task Description:
Go jogging
Task Due Date:
2020-02-08
Date Assigned:
2020-02-07
Task Completed:
No
The code i have so far is as follows. It is writing numbers to the text file but they are all labelled task 1 and the next task is not changing to task 2:
def add_task(count):
if menu == "a" or menu == "A":
with open( 'user.txt' ) as fin :
usernames = [i.split(',')[0] for i in fin.readlines() if len(i) > 3]
task = input ("Please enter the username of the person the task is assigned to.\n")
while task not in usernames :
task = input("Username not registered. Please enter a valid username.\n")
else:
task_title = input("Please enter the title of the task.\n")
task_description = input("Please enter the task description.\n")
task_due = input("Please input the due date of the task. (yyyy-mm-dd)\n")
date = datetime.date.today()
task_completed = False
if task_completed == False:
task_completed = "No"
else:
task_completed = ("Yes")
with open('tasks.txt', 'a') as task1:
count=count+1
task1.write("\nUser assigned to task: "+ str(count) + "\n" + task + "\nTask Title :" + "\n" + task_title + "\n" + "Task Description:\n" + task_description + "\n" + "Task Due Date:\n" + task_due + "\n" + "Date Assigned:\n" + str(date) + "\n" + "Task Completed:\n" + task_completed + "\n")
print("The new assigned task has been saved")
count = 0
add_task(count)
It's because the variable count is only changed within the scope of add_task(). The change is not seen outside of that function, so count is always 0 when you call add_task(count).
To learn more about scope in Python, check out this link: https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#more-about-scope-crossing-boundaries
EDIT:
You can either access the global count variable (see this answer), or - and this is what I would recommend - you can return the local variable count and use it to update the other variable like this: count = add_task(count)
I am studying Python and now I'm doing a small project on my own. The for loop in the second function is not run through the whole code. When I run the code I get just the last element of the dictionary.
In order to solve it I have tried to use while but I got the same answer.
def enter_task():
global num_task
num_task = int(input("Please, enter number of tasks: "))
calendar = {}
for i in range(0, num_task):
global task
task=input("Please, enter task: ")
set_time = input("Please, enter time for {}: ". format(task))
calendar[task] = set_time
print(calendar)
def conclusion():
count = 0
for i in range(0, num_task):
is_done = input("Is task {} completed? Enter Yes/No: ".format(task))
if is_done == "yes":
count += 1
return count
print('Nicely done. {} of {} tasks were completed today'. format(count, num_task))
When I call conclusion, the input is_done is shown just once and the task is equal to the last task I typed in the function enter_task. Also the count is not counting and the statement is not printed. The input is_done should appear as many times as nun_task and each time with a different task on it.
My below loop in python which goes through a list of customers seems to once it removes a customer from the list go back to the start of the while loop instead of repeating through for the rest of the customers. Can somebody please have a look at what I am doing wrong? Entire code is below and attached.
author = 'Alan Doonan'
import random
import time
class Building: # defines class building
number_of_floors = 0 # sets number_of_floors variable to 0
customer_list = [] # creates an empty array for customer_list
elevator = 0 # sets elevator variable to 0
def __init__(self, floors, customers): # initialize Building
self.number_of_floors = floors # assigns floors entered to number_of_floors
for customerID in range(1, customers + 1): # assigns number of customers entered to customer_list in order
new = Customer(customerID,self.number_of_floors) # creates an instance called new of Customer class for number of customers entered in input
self.customer_list.append(new) # appends new instance of customer to customer_list
self.customer_list.sort(key = lambda x: x.current_floor) # sorts customer_list by current_floor customer is on # prints
self.elevator = Elevator(floors,self.customer_list) # creates instance of elevator with inputted floors and assigns customer_list to register_list # prints
self.run() # runs run method below
def run(self): # method to operate the elevator
print('++++++++++++++++++++++++++ELEVATOR IS NOW STARTING+++++++++++++++') # prints
print('There are %d customers in the building' % (len(self.customer_list))) # prints
number_of_customers = len(self.customer_list) # assigns current number of customers to number_of_customers variable
self.output() # runs output method below
def output(self):
for customer in self.customer_list: #prints lists of customers in building and their details
print("Customer",customer.customerID,"is on floor",customer.current_floor,"and wants to go to",customer.destination_floor)
#ELEVATOR MOVING UP LOOP
while (self.elevator.current_floor < self.elevator.number_of_floors):
self.elevator.current_floor +=1
print('ELEVATOR MOVING UP')
print(len(self.customer_list),'Customers in lift.')
print('++++++++++++++++++++++++++++++++++++++++++++++++++++')
print('FLOOR',self.elevator.current_floor)
for customer in self.customer_list: # Loop for each instance of Custumer in customer_list
if (self.elevator.current_floor == customer.current_floor) & customer.customer_direction == 1:
customer.in_elevator = True
print('Customer',customer.customerID,'has entered the lift')
if (self.elevator.current_floor == customer.destination_floor) & (customer.in_elevator == True) & customer.customer_direction ==1:
customer.in_elevator = False
self.customer_list.remove(customer)
print(customer.customerID,'has reached their destination')
#ELEVATOR MOVING DOWN LOOP
while (self.elevator.current_floor <= self.number_of_floors) & (self.elevator.current_floor > 1):
self.elevator.current_floor -= 1
print(len(self.customer_list),'Customers in lift.')
print('ELEVATOR MOVING DOWN')
print('++++++++++++++++++++++++++++++++++++++++++++++++++++')
print('FLOOR',self.elevator.current_floor)
for customer in self.customer_list:
if (customer.in_elevator == True):
customer.current_floor = self.elevator.current_floor
if (self.elevator.current_floor == customer.destination_floor) & (customer.in_elevator == True) & (customer.customer_direction == -1):
customer.in_elevator = False
self.customer_list.remove(customer)
print('Customer',customer.customerID,'has reached their destination')
print('There are',len(self.customer_list),'trapped in the elevator') #prints
print('There are',len(Elevator.register_list),'people left on the register')
print('Elevator run is done!!!') #prints
print('CUSTOMERS STUCK IN LIFT ARE BELOW')
for stuck in self.customer_list:
print('Cust. ID:',stuck.customerID,'Dest. Floor:',stuck.destination_floor,'Curr. Floor:',stuck.current_floor,'In Elevator',stuck.in_elevator,'Direction',stuck.customer_direction)
class Elevator:
number_of_floors = 0 # the number of floors
register_list = [] # the list of customers in the elevator
current_floor = 0 # the current floor of the elevator
up = 1 # moves the elevator up
down = -1 # moves the elevator down
def __init__(self, number_of_floors, register_list):
self.number_of_floors = number_of_floors
self.register_list = register_list
def move(self): # method to move the elevator by 1 floor
pass;
def register_customer(self, customers): # customer goes into elevator
for reg in customers:
self.register_list.append(reg)
def cancel_customer(self, customers): # customer goes out of the elevator
pass;
class Customer:
current_floor = 0 # the current floor of the elevator
destination_floor = 0 # the destination floor of the elevator
customerID = 0 # the customers ID
in_elevator = False # denotes whether customer is in the elevator
finished = False # denotes whether customer has reached the destination floor
customer_direction = 0
def __init__(self, customerID, floors): # initilize Customer class
self.customerID = customerID # assigns self.customerID to customerID
self.current_floor = random.randint(1, floors) # assigns self.current_floor to random int between 1 and floors entered
self.destination_floor = random.randint(1, floors) # assigns seslf.destination_floor to random int between 1 and floors entered
while self.destination_floor == self.current_floor:
self.destination_floor = random.randint(1, floors)
if self.current_floor < self.destination_floor:
self.customer_direction = 1
else:
self.customer_direction = -1
def header(): # elevator animation at beginning of program
print(" ELEVATOR OPENING ")
time.sleep(.2)
print("+++++++++++++++++++++++++++++||+++++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++| |++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("++++++++++++++++| |+++++++++++++++++++")
time.sleep(.2)
print("++++++| |+++++++++")
time.sleep(.2)
print(" ")
time.sleep(.2)
print(" ELEVATOR CLOSING ")
time.sleep(.2)
print("++++++| |+++++++++")
time.sleep(.2)
print("++++++++++++++++| |+++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++| |++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++++++||+++++++++++++++++++++++++++++++++++")
def main(): # main method
try: # try/except for user input menu
floors = int(input('Enter the number of floors: ')) # enter floors and assign to floors
customers = int(input('Enter number of customers: ')) # enter customers and assign to customers
building = Building(floors, customers) # instance of building created with inputs of floors and customers # create instance of Building class (building)
except ValueError:
print('YOU DIDNT ENTER A NUMBER. START AGAIN.')
main()
if __name__ == "__main__":
# header()
main()
LINK TO FILE ON GITHUB
It is hard to answer your question without providing more scope. Please be more specific. Without a more exact question, I cannot say for sure-so please provide examples of input and output that lead you to believe this. However, if it looks like it is starting at the beginning of your while loop because it keeps printing out the same information, it may have to do with how you declared your classes; you have overloaded customerID as both a class variable and an instance variable. For more information see the docs. https://docs.python.org/2/tutorial/classes.html#class-objects
Basically, I would get rid of the class variables inside customer that are also instance variables and then I would also refactor the sections below the comments #ELEVATOR MOVING UP LOOP and the going down loop to consolidate them, since you are reusing a lot of code needlessly here. Then refine the question that you are asking so that it is clearer