I was wondering how I'm supposed to get my "balance" variable to change depending on the value added or subtracted to it each time, without resetting for the next loop.
At the moment it will add or subtract a given value and return the correct number but on the next loop it will use the original base value instead of using the new value from the previous loop.
import time
print ("Welcome to balance tracker!")
sBal=float(input ("Starting balance: "))
float(sBal)
transactionAmounts = []
transactionTypes = []
print ("Your current balance is", '$',sBal)
while True:
input("Press enter to continue")
print ("""
------------
[A]ddition
[S]ubtraction
[H]istory
[I]nformation
[Q]uit
------------
""")
choice=input("What would you like to do? ")
choice = choice.upper()
if choice == "A":
aval=float(input ("Enter amount you would like to add here: "))
nBal=(sBal)+(aval)
transactionTypes.append('Addition')
transactionAmounts.append(float(aval))
balance = float(sBal) + aval
print ("Your current balance is $",balance)
elif choice == "S":
aval=input("Enter amount you would like to subtract here: ")
nBal=float(sBal)-float(aval)
transactionTypes.append('Subtraction')
transactionAmounts.append (float(aval))
balance = float(sBal) - aval
print ("Your current balance is $",balance)
elif choice == "H":
aCount = 1
tCount = 0
for i in transactionAmounts:
print ('Transaction',aCount,':',transactionTypes[tCount],i)
aCount = aCount + 1
tCount = tCount + 1
elif choice == "Q":
break
else:
print ("invalid choice")
The solution to your problem is that when your assigning your balance variable, your adding sBal(starting balance) every time to the amount they would like to add... This is causing the balance to always be set back to the starting balance plus or minus the amount added. Try defining sBal as balance also like so...
balance = float(input("Starting balance: ")) #line 5
float(sBal) #<<<can be deleted #line 6
Also don't forget to alter anywhere in the code that calls sBal to call balance.
print("Your current balance is ", "$", difference) #line 9
balance = float(balance) (+ or -) aval #lines 30 and 37
Also you can delete your nBal(new balance) as it is never called.
Related
So I am trying to make this continue from get_burger_choice to get_burger price to where it would flow and finish the program. I am trying to write this program to where I could get the type of burger then the price from get_burger_price. Heres the problem, I do not know how to intergrate it towards doing that. I am completely stuck after the part where it says "no" at the end part of get_burger_choice to where I can transition to get_burger_price
Here is the code that I used : the part highlighted is where Im having trouble transitioning:I would like it to where if the user says no, it would ask if they would like to see the price, and it would transition towards get_burger_price
def get_burger_choice():
SIZE = 3
burgers = ["Cheesy", "Regular", "Veggie" ]
search = True
while search == True:
index = 0
found = False
print("What type of burger would you like?")
searchValue = input()
while found == False and index <= SIZE - 1:
if burgers[index].lower()==searchValue.lower():
found = True
else:
index = index + 1
if found:
print("That is on our menu")
else:
print("That is not in our menu")
print("Do you want see another burger? yes/no: ")
tryagain = input()
if tryagain.lower() =='no':
print("Would you like to see the price? yes or no: ")
if
def price_burger(burger_choice, burger_price):
if burger_price == 'cheesy':
burger_price = 3.00
elif burger_choice == 'regular':
burger_price = 2.00
elif burger_choice == 'veggie':
burger_price = 2.00
else:
print("we do not have that, sorry")
return burger_price
def total_price(burger_price, burger_choice=None):
print("The burger cost $", burger_price)
def closing(burger_choice):
if burger_choice == 'cheesy':
print("Nice selection, This is our best!")
else:
print("enjoy!")
def main(burger_price = 0):
choice = "yes"
while choice != "no":
burger_choice = get_burger_choice()
burger_price = price_burger(burger_choice,burger_price)
total_price(burger_price)
closing(burger_choice)
choice = input("\nWould you like to try again? yes or no: ")
main()
I am struggling to find a text comparison tool or algorithm that can compare an expected text against the current state of the text being typed.
I will have an experimentee typewrite a text that he has in front of his eyes. My idea is to compare the current state of the text against the expected text whenever something is typed. That way I want to find out when and what the subject does wrong (I also want to find errors that are not in the resulting text but were in the intermediate text for some time).
Can someone point me in a direction?
Update #1
I have access to the typing data in a csv format:
This is example output data of me typing "foOBar". Every line has the form (timestamp, Key, Press/Release)
17293398.576653,F,P
17293398.6885,F,R
17293399.135282,LeftShift,P
17293399.626881,LeftShift,R
17293401.313254,O,P
17293401.391732,O,R
17293401.827314,LeftShift,P
17293402.073046,O,P
17293402.184859,O,R
17293403.178612,B,P
17293403.301748,B,R
17293403.458137,LeftShift,R
17293404.966193,A,P
17293405.077869,A,R
17293405.725405,R,P
17293405.815159,R,R
In Python
Given your input csv file (I called it keyboard_records.csv)
17293398.576653,F,P
17293398.6885,F,R
17293399.135282,LeftShift,P
17293399.626881,LeftShift,R
17293401.313254,O,P
17293401.391732,O,R
17293401.827314,LeftShift,P
17293402.073046,O,P
17293402.184859,O,R
17293403.178612,B,P
17293403.301748,B,R
17293403.458137,LeftShift,R
17293404.966193,A,P
17293405.077869,A,R
17293405.725405,R,P
17293405.815159,R,R
The following code does the following:
Read its content and store it in a list named steps
For each step in steps recognizes what happened and
If it was a shift press or release sets a flag (shift_on) accordingly
If it was an arrow pressed moves the cursor (index of current where we insert characters) – if it the cursor is at the start or at the end of the string it shouldn't move, that's why those min() and max()
If it was a letter/number/symbol it adds it in curret at cursor position and increments cursor
Here you have it
import csv
steps = [] # list of all actions performed by user
expected = "Hello"
with open("keyboard.csv") as csvfile:
for row in csv.reader(csvfile, delimiter=','):
steps.append((float(row[0]), row[1], row[2]))
# Now we parse the information
current = [] # text written by the user
shift_on = False # is shift pressed
cursor = 0 # where is the cursor in the current text
for step in steps:
time, key, action = step
if key == 'LeftShift':
if action == 'P':
shift_on = True
else:
shift_on = False
continue
if key == 'LeftArrow' and action == 'P':
cursor = max(0, cursor-1)
continue
if key == 'RightArrow' and action == 'P':
cursor = min(len(current), cursor+1)
continue
if action == 'P':
if shift_on is True:
current.insert(cursor, key.upper())
else:
current.insert(cursor, key.lower())
cursor += 1
# Now you can join current into a string
# and compare current with expected
print(''.join(current)) # printing current (just to see what's happening)
else:
# What to do when a key is released?
# Depends on your needs...
continue
To compare current and expected have a look here.
Note: by playing around with the code above and a few more flags you can make it recognize also symbols. This will depend on your keyboard. In mine Shift + 6 = &, AltGr + E = € and Ctrl + Shift + AltGr + è = {. I think this is a good point to start.
Update
Comparing 2 texts isn't a difficult task and you can find tons of pages on the web about it.
Anyway I wanted to present you an object oriented approach to the problem, so I added the compare part that I previously omitted in the first solution.
This is still a rough code, without primary controls over the input. But, as you asked, this is pointing you in a direction.
class UserText:
# Initialize UserText:
# - empty text
# - cursor at beginning
# - shift off
def __init__(self, expected):
self.expected = expected
self.letters = []
self.cursor = 0
self.shift = False
# compares a and b and returns a
# list containing the indices of
# mismatches between a and b
def compare(a, b):
err = []
for i in range(min(len(a), len(b))):
if a[i] != b[i]:
err.append(i)
return err
# Parse a command given in the
# form (time, key, action)
def parse(self, command):
time, key, action = command
output = ""
if action == 'P':
if key == 'LeftShift':
self.shift = True
elif key == 'LeftArrow':
self.cursor = max(0, self.cursor - 1)
elif key == 'RightArrow':
self.cursor = min(len(self.letters), self.cursor + 1)
else:
# Else, a letter/number was pressed. Let's
# add it to self.letters in cursor position
if self.shift is True:
self.letters.insert(self.cursor, key.upper())
else:
self.letters.insert(self.cursor, key.lower())
self.cursor += 1
########## COMPARE WITH EXPECTED ##########
output += "Expected: \t" + self.expected + "\n"
output += "Current: \t" + str(self) + "\n"
errors = UserText.compare(str(self), self.expected[:len(str(self))])
output += "\t\t"
i = 0
for e in errors:
while i != e:
output += " "
i += 1
output += "^"
i += 1
output += "\n[{} errors at time {}]".format(len(errors), time)
return output
else:
if key == 'LeftShift':
self.shift = False
return output
def __str__(self):
return "".join(self.letters)
import csv
steps = [] # list of all actions performed by user
expected = "foobar"
with open("keyboard.csv") as csvfile:
for row in csv.reader(csvfile, delimiter=','):
steps.append((float(row[0]), row[1], row[2]))
# Now we parse the information
ut = UserText(expected)
for step in steps:
print(ut.parse(step))
The output for the csv file above was:
Expected: foobar
Current: f
[0 errors at time 17293398.576653]
Expected: foobar
Current: fo
[0 errors at time 17293401.313254]
Expected: foobar
Current: foO
^
[1 errors at time 17293402.073046]
Expected: foobar
Current: foOB
^^
[2 errors at time 17293403.178612]
Expected: foobar
Current: foOBa
^^
[2 errors at time 17293404.966193]
Expected: foobar
Current: foOBar
^^
[2 errors at time 17293405.725405]
I found the solution to my own question around a year ago. Now i have time to share it with you:
In their 2003 paper 'Metrics for text entry research: An evaluation of MSD and KSPC, and a new unified error metric', R. William Soukoreff and I. Scott MacKenzie propose three major new metrics: 'total error rate', 'corrected error rate' and 'not corrected error rate'. These metrics have become well established since the publication of this paper. These are exaclty the metrics i was looking for.
If you are trying to do something similiar to what i did, e.g. compare the writing performance on different input devices this is the way to go.
I want to know approach about, how can I compress the string like if I given some string ABCABCABC than as I am thinking that I can find sub-string as ABC which is frequently occurs so it will be compressed as 3ABC. Another way if string like ABCABCBC is given than here ABC is the frequently occurring sub-string, so it compressed as 2ABC1BC. As you can see I am taking only consideration of adjacent substrings.
s='FLFLAFLAFLAF'
def check(str_check,str):
try:
index=str.index(str_check)
except Exception:
index=9999
return index
def max_index(i,j,sub_str):
if(i>=0 and j<=len(count)):
try:
j=count.index(max(count[i:j]))
except Exception:
j=-1
try:
sub_str_index=int(sub_str.index(sub_list[j]))
except Exception:
sub_str_index=-1
temp=int(count[j])
if len(sub_str)==0:
return ""
elif(count[j]==1 or int(count[j])*len(sub_list[j])>len(sub_str)):
for i in range (len(sub_str)):
count[j+i]=0
return "1"+ sub_str
else:
#count[j]=0
return max_index(0,sub_str_index,sub_str[0:sub_str_index]) + str(temp) + sub_list[j] + max_index(len(sub_str[0:sub_str_index])+(int(temp)*len(sub_list[j])),len(sub_str),sub_str[len(sub_str[0:sub_str_index])+(int(temp)*len(sub_list[j])): len(sub_str)])
sub_list=sorted(set([s[i:i+j] for j in range(1,len(s)+1) for i in range(len(s)-j+1)]))
length=len(s)
length1=len(sub_list)
count=[]
for i in range (length1):
cnt=0
j=0
while(j<length):
k=check(sub_list[i],s[j:])
if k==9999:
break
if (s[j+k:j+k+len(sub_list[i])]==sub_list[i]):
if(cnt>=1 and s[j+k-len(sub_list[i]):j+k]==sub_list[i]):
j=j+k+1
cnt=cnt+1
elif (cnt==0):
j=j+k+1
cnt=cnt+1
else:
j=length
else:
j=length
count.append(cnt)
print "SUBLIST"
print sub_list
print "count"
count1=count
print count1
j=len(count)
i=0
max_ele=max(count)
while(max_ele in count):
max_in=count.index(max(count[i:j]))
print max_index(i,j,s)
count=count1
count[max_in]=0
I am working on a larger project to write a code so the user can play Connect 4 against the computer. Right now, the user can choose whether or not to go first and the board is drawn. While truing to make sure that the user can only enter legal moves, I have run into a problem where my function legal_moves() takes 1 positional argument, and 0 are given, but I do not understand what I need to do to male everything agree.
#connect 4
#using my own formating
import random
#define global variables
X = "X"
O = "O"
EMPTY = "_"
TIE = "TIE"
NUM_ROWS = 6
NUM_COLS = 8
def display_instruct():
"""Display game instructions."""
print(
"""
Welcome to the second greatest intellectual challenge of all time: Connect4.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a column number, 1 - 7. Your move
(if that column isn't already filled) will move to the lowest available position.
Prepare yourself, human. May the Schwartz be with you! \n
"""
)
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question,low,high):
"""Ask for a number within range."""
#using range in Python sense-i.e., to ask for
#a number between 1 and 7, call ask_number with low=1, high=8
low=1
high=NUM_COLS
response = None
while response not in range (low,high):
response=int(input(question))
return response
def pieces():
"""Determine if player or computer goes first."""
go_first = ask_yes_no("Do you require the first move? (y/n): ")
if go_first == "y":
print("\nThen take the first move. You will need it.")
human = X
computer = O
else:
print("\nYour bravery will be your undoing... I will go first.")
computer = X
human = O
return computer, human
def new_board():
board = []
for x in range (NUM_COLS):
board.append([" "]*NUM_ROWS)
return board
def display_board(board):
"""Display game board on screen."""
for r in range(NUM_ROWS):
print_row(board,r)
print("\n")
def print_row(board, num):
"""Print specified row from current board"""
this_row = board[num]
print("\n\t| ", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num],"|")
print("\t", "|---|---|---|---|---|---|---|")
# everything works up to here!
def legal_moves(board):
"""Create list of column numbers where a player can drop piece"""
legals = []
if move < NUM_COLS: # make sure this is a legal column
for r in range(NUM_ROWS):
legals.append(board[move])
return legals #returns a list of legal columns
#in human_move function, move input must be in legal_moves list
print (legals)
def human_move(board,human):
"""Get human move"""
legals = legal_moves(board)
print("LEGALS:", legals)
move = None
while move not in legals:
move = ask_number("Which column will you move to? (1-7):", 1, NUM_COLS)
if move not in legals:
print("\nThat column is already full, nerdling. Choose another.\n")
print("Human moving to column", move)
return move #return the column number chosen by user
def get_move_row(turn,move):
move=ask_number("Which column would you like to drop a piece?")
for m in range (NUM_COLS):
place_piece(turn,move)
display_board()
def place_piece(turn,move):
if this_row[m[move]]==" ":
this_row.append[m[move]]=turn
display_instruct()
computer,human=pieces()
board=new_board()
display_board(board)
move= int(input("Move?"))
legal_moves()
print ("Human:", human, "\nComputer:", computer)
Right down the bottom of the script, you call:
move= int(input("Move?"))
legal_moves()
# ^ no arguments
This does not supply the necessary board argument, hence the error message.
Now, I'm working on making a program in Python that can pull events from all the calendars in my Google account; however, I'm trying to make the program potentially as commercial as possible. With that said, it's quite simple to customize the code for myself, when I know that all the US Holidays events attached to my calendar are all day events, so I can set up a simple if statement that checks if it's a Holiday calendar and specify the events request as such:
def get_main_events(pageToken=None):
events = gc_source.service.events().list(
calendarId=calendarId,
singleEvents=True,
maxResults=1000,
orderBy='startTime',
pageToken=pageToken,
).execute()
return events
So, that works for all day events. After which I'd append the results to a list and filter it to get only the events I want. Now getting events from my primary calendar is a bit easier to specify the events I want because they're generally not all day events, just my work schedule so I can use:
now = datetime.now()
now_plus_thirtydays = now + timedelta(days=30)
def get_main_events(pageToken=None):
events = gc_source.service.events().list(
calendarId=calendarId,
singleEvents=True,
maxResults=1000,
orderBy='startTime',
timeMin=now.strftime('%Y-%m-%dT%H:%M:%S-00:00'),
timeMax=now_plus_thirtydays.strftime('%Y-%m-%dT%H:%M:%S-00:00'),
pageToken=pageToken,
).execute()
return events
Now, the problem I run into with making the program available for commercial use, as well as myself, is the above will ONLY return NON-all day events from my primary calendar. I'd like to find out if there's a way - if so, how - to run the get events request and return ALL results whether they're all day or if they're just a timed event that takes place in a portion of the day. In addition part of this issue is that in another part of the code where I print the results I would need to use:
print event['start']['date']
for an all day event, and:
print event['start']['dateTime']
for a non all day event.
So, since 'dateTime' wont work on an all day event, I'd like to figure out a way to set it up so that I can evaluate whether an event is all day or not. i.e. "if said event is an all day event, use event['start']['date'], else use event['start']['dateTime']
So, through much testing, and finding a way to use a log feature to see what error was happening with:
print event['start']['date']
vs:
print event['start']['dateTime']
I found that I could use the error result to my advantage using 'try' and 'except'.
Here is the resulting fix:
First the initial part as earlier with the actual query to the calendar:
now = datetime.now()
now_plus_thirtydays = now + timedelta(days=30)
def get_calendar_events(pageToken=None):
events = gc_source.service.events().list(
calendarId=cal_id[cal_count],
singleEvents=True,
orderBy='startTime',
timeMin=now.strftime('%Y-%m-%dT%H:%M:%S-00:00'),
timeMax=now_plus_thirtydays.strftime('%Y-%m-%dT%H:%M:%S-00:00'),
pageToken=pageToken,
).execute()
return events
Then the event handling portion:
# Events Portion
print "Calendar: ", cal_summary[cal_count]
events = get_calendar_events()
while True:
for event in events['items']:
try:
if event['start']['dateTime']:
dstime = dateutil.parser.parse(event['start']['dateTime'])
detime = dateutil.parser.parse(event['end']['dateTime'])
if dstime.strftime('%d/%m/%Y') == detime.strftime('%d/%m/%Y'):
print event['summary'] + ": " + dstime.strftime('%d/%m/%Y') + " " + dstime.strftime('%H%M') + "-" + detime.strftime('%H%M')
# Making a list for the respective items so they can be iterated through easier for time comparison and TTS messages
if cal_count == 0:
us_holiday_list.append((dstime, event['summary']))
elif cal_count == 1:
birthday_list.append((dstime, event['summary']))
else:
life_list.append((dstime, event['summary']))
else:
print event['summary'] + ": " + dstime.strftime('%d/%m/%Y') + " # " + dstime.strftime('%H%M') + " to " + detime.strftime('%H%M') + " on " + detime.strftime('%d/%m/%Y')
# Making a list for the respective items so they can be iterated through easier for time comparison and TTS messages
if cal_count == 0:
us_holiday_list.append((dstime, event['summary']))
elif cal_count == 1:
birthday_list.append((dstime, event['summary']))
else:
life_list.append((dstime, event['summary']))
else:
return
except KeyError:
dstime = dateutil.parser.parse(event['start']['date'])
detime = dateutil.parser.parse(event['end']['date'])
print event['summary'] + ": " + dstime.strftime('%d/%m/%Y')
# Making a list for the respective items so they can be iterated through easier for time comparison and TTS messages
if cal_count == 0:
us_holiday_list.append((dstime, event['summary']))
elif cal_count == 1:
birthday_list.append((dstime, event['summary']))
else:
life_list.append((dstime, event['summary']))
page_token = events.get('nextPageToken')
if page_token:
events = get_calendar_events(page_token)
else:
if cal_count == (len(cal_id) - 1): # If there are no more calendars to process
break
else: #Continue to next calendar
print "-----"
cal_count += 1
print "Retrieving From Calendar: ", cal_summary[cal_count]
events = get_calendar_events()