Convert user input to time which changes boolean value for the duration entered? - python-3.x

I'm working on this side project game to grasp python better. I'm trying to have the user enter the amount of time the character has to spend busy, then not allow the user to do the same thing until they have completed the original time entered. I have tried a few methods with varying error results from my noob ways. (timestamps, converting input to int and time in different spots, timeDelta)
def Gold_mining():
while P.notMining:
print('Welcome to the Crystal mines kid.\nYou will be paid in gold for your labour,\nif lucky you may get some skill points or bonus finds...\nGoodluck in there.')
print('How long do you wish to enter for?')
time_mining = int(input("10 Gold Per hour. Max 8 hours --> "))
if time_mining > 0 and time_mining <= 8:
time_started = current_time
print(f'You will spend {time_mining} hours digging in the mines.')
P.gold += time_mining * 10
print(P.gold)
P.notMining = False
End_Time = (current_time + timedelta(hours = 2))
print(f'{End_Time} time you exit the mines...')
elif time_mining > 8:
print("You can't possibly mine for that long kid, go back and think about it.")
else:
print('Invalid')
After the set amount of time i would like for it to change the bool value back to false so that you can mine again.
"Crystal Mining" is mapped to a different key for testing so my output says "Inventory" but would say "Crystal Mining" when it works properly and currently looks like this:
*** Page One ***
Intro Page
02:15:05
1 Character Stats
2 Rename Character
3 Inventory
4 Change Element
5 Menu
6 Exit
Num: 3
Welcome to the Crystal mines kid.
You will be paid in gold for your labour,
if lucky you may get some skill points or bonus finds...
Goodluck in there.
How long do you wish to enter for?
10 Gold Per hour. Max 8 hours --> 1
You will spend 1 hours digging in the mines.
60
Traceback (most recent call last):
File "H:\Python ideas\input_as_always.py", line 176, in <module>
intro.pageInput()
File "H:\Python ideas\input_as_always.py", line 45, in pageInput
self.pageOptions[pInput]['entry']()
File "H:\Python ideas\input_as_always.py", line 134, in Gold_mining
End_Time = (current_time + timedelta(hours = 2))
TypeError: can only concatenate str (not "datetime.timedelta") to str

Related

The logical error or test case error in python

Handling Expection
The full question is of Hackerrank. I have passed all the test cases but one test case is failing. I don't know why. Logic is correct. Please help me
test case in given question
*
4500(membership fee)
3(number of installments)
Welcome boy(name)
*
my code is
def Library(memberfee, installment, book):
if(installment > 3):
print("Maximum Permitted Number of Installments is 3")
else:
if(installment == 0):
print("Number of Installments cannot be Zero.")
else:
print("Amount per Installment is {}".format(memberfee/installment))
ListOfBooks = ["philosophers stone", "chamber of sec rets", "prisoner of azkaban", "goblet of fire", "order of phoenix", "half blood price", "deathly hallows 1", "deathly hallows2"]
book = book.lower()
if book in ListOfBooks:
print("It is available in this section")
else:
print("No such book exists in this section")
if __name__ == '__main__':
memberfee = int(input())
installment = int(input())
book = input()
try:
Library(memberfee,installment,book)
except ZeroDivisionError as e:
print(e)
except ValueError as e:
print(e)
except NameError as e:
print(e)
**i think the problem may be here
print("Amount per Installment is {}".format(memberfee/installment))
**
The question is.....
*Library
This exception handling scenario deals with the exceptional cases that arise in a typical library interface of a Town library.
O
1
About the Library Interface
This is a typical interface provided in the library, which takes 3 inputs from the library members, sequentially. They are:
memberfee - Membership fee for the library for the next financial year, which can be paid in installments.
installment - Number of installments chosen to pay the Membership fee. 3. book- Name of the book the member looks for in the 'Harry Potter' Section.
23
24
25
26
27
28
29
30
Note
All the above inputs except 'book' are Integers.
Write the function definition as follows, for the function 'Library', that takes all the above 3 inputs as its parameters:
The maximum permitted number of installments to pay the annual membership fee is '3'.
Raise ValueError exception if the input for the number of installments is greater than '3' and Print a Message. The message to the user must be, "Maximum Permitted Number of Installments is 3", The amount per installment is calculated by dividing the Membership fee by the number of installments. 2. Raise ZeroDivision Error exception if the input for the number of installments is equal to '0' and Print a Message. The message to the user must be, "Number of Installments cannot be Zero." else
1
#!/bin/python
10
11
def Library (
if(insta
prin
else:
if(
els
(memberfee
sec rets",
phoenix",
hallows 2"1
Print the amount per installment as "Amount per Installment is 3000.0".
12
13
The 'Harry Potter' book section contains the following books only:
14
ALL
1
15
philosophers stone
16
. chamber of secrets
17
• prisoner of azkaban
18
19
• goblet of fire
• order of phoenix
half blood prince
deathly hallows 1
21
23
20
24
• deathly hallows 2*
def Library(memberfee,installment,book):
# Write your code here
#print(memberfee)
#print(installment)
#print(book)
if installment > 3:
raise(ValueError("Maximum Permitted Number of Installments is 3"))
if installment == 0:
raise(ZeroDivisionError("Number of Installments cannot be Zero."))
else:
print ("Amount per Installment is ", memberfee / installment)
if book == 'philosophers stone' or book == 'Chamber of Secrets' or book == 'prisoner of azkaban' or book == 'Goblet of Fire' or book == 'order of phoenix' or book == 'Half Blood Prince' or book == 'Deathly Hallows 1' or book == 'deathly hallows 2':
print ("It is available in this section")
else:
raise(NameError("No such book exists in this section"))
Your ListofBooks contains some grammatical errors in the names of the books. Maybe that's what caused the error.
In my opinion, it is just a name not matching with listofbooks.
Please try to check all the book names from listofbooks.

Pine script - Security function not show correct on different timeframe

I'm newbie and try to get ichimoku data on 4 hour timeframe but it not showing the correct value when I shift.
//#version=4
study(title="test1", overlay=true)
conversionPeriods = input(9, minval=1, title="Conversion Line Length")
basePeriods = input(26, minval=1, title="Base Line Length")
laggingSpan2Periods = input(52, minval=1, title="Leading Span B Length")
displacement = input(26, minval=1, title="Displacement")
donchian_M240(len) => avg(security(syminfo.tickerid, 'D' , lowest(len)), security(syminfo.tickerid, 'D', highest(len)))
tenkanSen_M240 = donchian_M240(conversionPeriods)
kijunSen_M240 = donchian_M240(basePeriods)
senkoSpanA_M240 = avg(tenkanSen_M240, kijunSen_M240)
plot(senkoSpanA_M240[25], title="senkoSpanA_M240[25]")
The value senkoSpanA_M240[25] keep changing when I'm in M5, M15, M30, H1, H4 or D1.
Can you help please?
the reason it keeps changing when you change time frames is because you are using a historical bar reference [25] on your senkoSpanA_M240.
This means it will look for the senkoSpanA_M240 condition that occurred 25 bars ago.
Depending on which time frame you are selecting, it will look back 25 bars of that time frame and perform the calculation.
What exactly are you trying to achieve by using the [25]?

Time Duration in python

Given two strings :
ex:
start_time="3:00 PM"
Duration="3:10"
Start time is in 12-hour clock format (ending in AM or PM), and duration time
that indicates the number of hours and minutes
Assume that the start times are valid times.The minutes in the duration time will
be a whole number less than 60, but the hour can be any whole number.
I need to add the duration time to the start time and return the result
(WITHOUT ANY USE OF LIBRARIES).
The result should be in 12-hour clock format (ending in AM or PM) indicates the
number of hours and minutes
ex:
start_time = "6:30 PM"
Duration = "205:12"
# Returns: 7:42 AM
I Tried and finally got the required answer but unable to produce correct AM or PM for
the result after addition.
what I Tried:
start_time = "6:30 PM"
Duration = "205:12"
#My answer =7:42
#expected :7:42 AM
Can someone help me with the logic to produce correct AM or PM after addition of start
time and Duration.
def add_time(a,b):
a=a.split()
b=b.split()
be=int(a[0][:a[0].find(':')])
af=int(a[0][a[0].find(':')+1:])
be1 = int(b[0][:b[0].find(':')])
af1 = int(b[0][b[0].find(':') + 1:])
return(((be+be1)//24)+1)
s=be+(be1)%12
p=af+af1
if ((s>12) and (p<60)) :
return(str(s-12)+":"+str(p))
elif ((s<12) and (p>60)) :
f = p-60
if len(str(f))<=1:
return(str(s+1)+":"+str('0'+str(f)))
else:
return (str(s + 1)+":"+(str(f)))
elif ((s<12) and (p<60)) :
return(str(s)+":"+str(p))
elif ((s>12) and (p>60)):
f=p-60
if len(str(f)) <= 1:
return (str((s -12)+1)+":"+('0' + str(f)))
else:
return (str((s -12)+1)+":"+(str(f)))
print(add_time("10:10 PM", "3:30"))
# Returns: 1:40 AM
print(add_time("11:43 PM", "24:20"))
# Returns: 12:03 AM
Your code does not seem to cover all edge cases, e.g. add_time("11:43 PM", "1:20") returns None because the case s==12 is not covered.
Therefore one should put <= instead of < in the respective if conditions. The case where the addition of the minutes leads to hours greater than 12 although the addition of the hours itself did not, is not covered either. So we should check the minutes first and the hours after that instead of simultaneously.
To make the code more readable, we use f-strings and can use str.split() with an argument, forgive me for changing the code quite a bit:
def add_time(a,b):
start = a.split()
start_h, start_m = [int(val) for val in start[0].split(':')]
start_app = start[1]
dur_h, dur_m = [int(val) for val in b.split(':')]
end_m = start_m+dur_m
end_h = end_m//60
end_m %= 60
end_h += start_h+dur_h
if (end_h//12)%2==0:
end_app = start_app
else:
end_app = 'AM' if start_app=='PM' else 'PM'
return f'{end_h:02}:{end_m:02} {end_app}'

Parsing heterogenous data from a text file in Python

I am trying to parse raw data results from a text file into an organised tuple but having trouble getting it right.
My raw data from the textfile looks something like this:
Episode Cumulative Results
EpisodeXD0281119
Date collected21/10/2019
Time collected10:00
Real time PCR for M. tuberculosis (Xpert MTB/Rif Ultra):
PCR result Mycobacterium tuberculosis complex NOT detected
Bacterial Culture:
Bottle: Type FAN Aerobic Plus
Result No growth after 5 days
EpisodeST32423457
Date collected23/02/2019
Time collected09:00
Gram Stain:
Neutrophils Occasional
Gram positive bacilli Moderate (2+)
Gram negative bacilli Numerous (3+)
Gram negative cocci Moderate (2+)
EpisodeST23423457
Date collected23/02/2019
Time collected09:00
Bacterial Culture:
A heavy growth of
1) Klebsiella pneumoniae subsp pneumoniae (KLEPP)
ensure that this organism does not spread in the ward/unit.
A heavy growth of
2) Enterococcus species (ENCSP)
Antibiotic/Culture KLEPP ENCSP
Trimethoprim-sulfam R
Ampicillin / Amoxic R S
Amoxicillin-clavula R
Ciprofloxacin R
Cefuroxime (Parente R
Cefuroxime (Oral) R
Cefotaxime / Ceftri R
Ceftazidime R
Cefepime R
Gentamicin S
Piperacillin/tazoba R
Ertapenem R
Imipenem S
Meropenem R
S - Sensitive ; I - Intermediate ; R - Resistant ; SDD - Sensitive Dose Dependant
Comment for organism KLEPP:
** Please note: this is a carbapenem-RESISTANT organism. Although some
carbapenems may appear susceptible in vitro, these agents should NOT be used as
MONOTHERAPY in the treatment of this patient. **
Please isolate this patient and practice strict contact precautions. Please
inform Infection Prevention and Control as contact screening might be
indicated.
For further advice on the treatment of this isolate, please contact.
The currently available laboratory methods for performing colistin
susceptibility results are unreliable and may not predict clinical outcome.
Based on published data and clinical experience, colistin is a suitable
therapeutic alternative for carbapenem resistant Acinetobacter spp, as well as
carbapenem resistant Enterobacteriaceae. If colistin is clinically indicated,
please carefully assess clinical response.
EpisodeST234234057
Date collected23/02/2019
Time collected09:00
Authorised by xxxx on 27/02/2019 at 10:35
MIC by E-test:
Organism Klebsiella pneumoniae (KLEPN)
Antibiotic Meropenem
MIC corrected 4 ug/mL
MIC interpretation Resistant
Antibiotic Imipenem
MIC corrected 1 ug/mL
MIC interpretation Sensitive
Antibiotic Ertapenem
MIC corrected 2 ug/mL
MIC interpretation Resistant
EpisodeST23423493
Date collected18/02/2019
Time collected03:15
Potassium 4.4 mmol/L 3.5 - 5.1
EpisodeST45445293
Date collected18/02/2019
Time collected03:15
Creatinine 32 L umol/L 49 - 90
eGFR (MDRD formula) >60 mL/min/1.73 m2
Creatinine 28 L umol/L 49 - 90
eGFR (MDRD formula) >60 mL/min/1.73 m2
Essentially the pattern is that ALL information starts with a unique EPISODE NUMBER and follows with a DATE and TIME and then the result of whatever test. This is the pattern throughout.
What I am trying to parse into my tuple is the date, time, name of the test and the result - whatever it might be. I have the following code:
with open(filename) as f:
data = f.read()
data = data.splitlines()
DS = namedtuple('DS', 'date time name value')
parsed = list()
idx_date = [i for i, r in enumerate(data) if r.strip().startswith('Date')]
for start, stop in zip(idx_date[:-1], idx_date[1:]):
chunk = data[start:stop]
date = time = name = value = None
for row in chunk:
if not row: continue
row = row.strip()
if row.startswith('Episode'): continue
if row.startswith('Date'):
_, date = row.split()
date = date.replace('collected', '')
elif row.startswith('Time'):
_, time = row.split()
time = time.replace('collected', '')
else:
name, value, *_ = row.split()
print (name)
parsed.append(DS(date, time, name, value))
print(parsed)
My error is that I am unable to find a way to parse the heterogeneity of the test RESULT in a way that I can use later, for example for the tuple DS ('DS', 'date time name value'):
DATE = 21/10/2019
TIME = 10:00
NAME = Real time PCR for M tuberculosis or Potassium
RESULT = Negative or 4.7
Any advice appreciated. I have hit a brick wall.

How do I extract a particular section from textfile in python3

This is my python file
path = '/my/file/list.txt'
with open(path,'rt') as file:
print("step 1")
collected_lines = []
started = False
for line in file:
for n in range(1, 10):
if line.startswith('PLAY NO.{}'.format(n)):
started = True
print("started at line {}".format(line[0]))
continue
if started:
collected_lines.append(line)
if started and line == 'PLAY NO.{}'.format(n+1):
print("end at line {}".format(line[0]))
break
print(collected_lines.append(line))
This is my code..
OUTPUT:
None
None
None
None
None
None
Now I want the lines starting from play No2 to play No3.... But I am getting None.. Please any suggestions... I am using Python 3.5
Sorry this is the first time asking question on this site..
My file looks like this..
textfile.txt
Hello and Welcome This is the list of plays being performed here
PLAY NO. 1
1. adknjkd
2. skdi
3. ljdij
PLAY NO. 2
1. hsnfhkjdnckj
2. sjndkjhnd and so on
path = 'list.txt'
collected_lines = []
with open(path,'rt') as file:
print("step 1")
started = False
lineNo = 0
for line in file:
lineNo += 1
for n in range(1, 10):
# print('PLAY NO. {}'.format(n))
if started and line.lstrip().startswith('PLAY NO. {}'.format(n)):
print("### end at line {}".format(lineNo))
started = False
break
if line.lstrip().startswith('PLAY NO. {}'.format(n)):
started = True
print("### started at line {}".format(lineNo))
break
if started:
collected_lines.append(line)
print("collected_lines: \n\n", *[ item for item in collected_lines ])
gives:
step 1
### started at line 2
### end at line 7
collected_lines:
PLAY NO. 1
1. adknjkd
2. skdi
3. ljdij
NOTES about fixed issues:
used .lstrip() in order to make .startswith() working as expected
added a space between NO. and {} in startswith('PLAY NO. {}'.format(n) so that the if condition can find the line
rearranged the order of ifs in order to avoid that the end line is considered found at the start line
added started = False to the loop to stop collecting the lines.
The problem with the leading spaces was already enough to prevent the code from finding the line. Fixing this alone wouldn't fix the problem because of the missing space in the format string, so both issues had to be fixed to make the code work as expected. And so on ... see NOTES above.
If you want a dict with as labels the play number and as items a list with the lines about the play you can use a defaultdict
Defining the text
text = """Hello and Welcome This is the list of plays being performed here
PLAY NO. 1
1. adknjkd
2. skdi
3. ljdij
PLAY NO. 2
1. hsnfhkjdnckj
2. sjndkjhnd and so on"""
Defining the regular expression
regex = re.compile('^\s*PLAY NO. (\d+)$')
Parsing the lines
label = None # no play to start with
recorded_lines = defaultdict(list)
for line_no, line in enumerate(StringIO(text)):
# In the real code replace the 'StringIO(text)' with 'file'
try:
play_no = int(regex.findall(line)[0])
# If this regex does not match, it will throw an IndexError
# The code underneath is only executed when a new play starts
if label: # if there is no play underway, there can be no ending
print('PLAY NO. %i ended at line number %i' % (label, line_no-1))
label = play_no
print('PLAY NO. %i started at line number %i' % (play_no, line_no))
except IndexError:
# no new play started
if label and line.strip():
recorded_lines[play_no].append(line.strip())
print(line_no, line)
print(recorded_lines)
yields
defaultdict(list,
{1: [(2, '1. adknjkd'), (3, '2. skdi'), (4, '3. ljdij')],
2: [(7, '1. hsnfhkjdnckj'), (8, '2. sjndkjhnd and so on')]})
and this output on the stout:
0 Hello and Welcome This is the list of plays being performed here
PLAY NO. 1 started at line number 1
1 PLAY NO. 1
2 1. adknjkd
3 2. skdi
4 3. ljdij
5
PLAY NO. 1 ended at line number 5
PLAY NO. 2 started at line number 6
6 PLAY NO. 2
7 1. hsnfhkjdnckj
8 2. sjndkjhnd and so on

Resources