I would like to convert the input into a range with interval. Can anyone please help me.
Ask the user what will be the input of the user either in Celsius or Fahrenheit. If the input is invalid, print invalid and ask to try again.
Ask the user to input the start, range, and interval separated by an asterisk. For example 0*10*2. This means that the start of the conversion will be from 0 to 10 with an interval of 2, thus the value to be converted will be 0, 3, 6, 9
If the start<end, then the interval should be 0<interval otherwise, your program will display an error and ask to try again for #2. Or
If the start>end, then the interval should be 0>interval otherwise, your program will display an error and ask to try again for #2.
If the user inputs only one value, like 10. This means that the start is equal to 1 which will be the default value for start, up to 10, and the interval is 2 which will be the default value of the interval if start<end.
If the user input has two values like 10*2, this means that the start is equal to 10 up to 2. The interval is set to the default value which is equal to -2 since start>end.
ask = input("What would you like to choose? Celcius = 1, Fahrenheit = 2. \nPick option 1 or 2: ")
asks = float(ask)
if asks == 1:
rng = input("Enter the start, range, interval. \n example 0*10*2:").split("*")
rng = range(rng)
print(rng)
answer1_flag = 0
while answer1_flag == 0:
ask = input("What would you like to choose? Celcius = 1, Fahrenheit = 2. \nPick option 1 or 2: ").strip()
if ask == '1' or ask=='2':
answer1_flag = 1
answer2_flag = 0
while answer2_flag==0:
rng = input("Enter the start, range, interval. \n example 0*10*2:").strip()
count = rng.count('*')
if count==0:
start = 1
end = int(rng)
interval = 2
elif count==1:
start,end = map(int,rng.split("*"))
if start<end:
interval = 2
elif start>end:
interval = -2
elif count==2:
start,end,interval = map(int,rng.split("*"))
if start>end and interval>0:
print('Error! If start>end then interval should be a negative number! Please enter the input again.')
elif start<end and interval<0:
print('Error! If start<end then interval should be a positive number! Please enter the input again.')
else:
rng = range(start,end,interval)
answer2_flag = 1
else:
print('Invalid! Try again.')
print(rng)
import sys
def get_celsisu_or_fahrenheit():
print("What would you like to choose: \n1. Celsius\n2. Fahrenheit\n")
cf = input("Enter (1/2): ")
if cf not in ["1", "2"]:
err()
get_celsisu_or_fahrenheit()
return cf
def get_value(is_celsuis):
values = input(f"Enter the value in {'Celsius' if is_celsuis else 'Fahrenheit'}: ").split("*")
values = list(map(lambda x: int(x), values))
start, end, interval = assign_values(values)
# conditions
if start < end and not 0 < interval:
err() and sys.exit(0)
if start > end and not 0 > interval:
err() and sys.exit(0)
return start, end, interval
def assign_values(val):
start, end, interval = 1, None, None
if len(val) == 1:
end = val[0]
elif len(val) == 2:
start, end = val
elif len(val) == 3:
start, end, interval = val
else:
err()
get_value()
if interval is None:
interval = -2 if start > end else 2
return start, end, interval
def err():
print("ERROR: Please check your input and try again.")
print("----------------------------------------------")
def convert(grade, is_celsuis):
return (grade * 9 / 5) + 32 if is_celsuis else (grade - 32) * 5 / 9
def start():
is_celsuis = True if get_celsisu_or_fahrenheit() == "1" else False
start, end, interval = get_value(is_celsuis)
rng = range(start, end, interval)
print(rng)
for x in rng:
is_celsuis and print(f"{x} Celsuis == {round(convert(x, is_celsuis), 2)} Fahrenheit")
not is_celsuis and print(f"{x} Fahrenheit == {round(convert(x, is_celsuis), 2)} Celsuis")
start()
Related
After it validates the date and time for the appointment I need to make sure it doesn't overlap with a pre-existing appointment in the appontmentList[] and I'm stuck as to where to start.
I'm thinking somewhere along the lines of:
for x in appointmentList:
if start <= x:
print('invalid, overlapping appointment! ')
else:
break
See my full code below:
appointmentList = []
def add_sort():
choice = input ('Add item to diary (a) or sort (s)')
if choice == 's':
print ('sorting')
sortRecords()
elif choice == 'a':
print ('adding')
add_record()
else:
add_sort()
def add_record():
while True:
Priority = input ('What is the priority of your appointment? ')
if 'low' != Priority != 'Low' and 'high' != Priority != 'High':
print('invalid, must be low or high! ')
else:
break
# is_valid_date():
while True:
dt = input('enter date of appointment in dd/mm/yyyy format. ')
day_string, month_string, year_string = dt.split('/')
day = int(day_string)
month = int(month_string)
year = int(year_string)
if month in [1, 3, 5, 7, 8, 10, 12]:
max_days=31
elif month in [4, 6, 9 ,11]:
max_days=30
elif year%4==0 and year%100!=0 or year%400==0:
max_days=29
else:
max_days=28
if month<1 or month>12:
print('invalid, enter a number between 1 - 12')
elif day<1 or day>max_days:
print('invalid, check day')
elif 10000 > year <2022:
print('invalid, enter a year greater than 2021')
# is_valid_time():
Start = int(input('What is the starting time of your appointment? '))
if Start < 7 or Start > 22:
print('invalid, enter a time between 7 - 22. ')
End = int(input('What is the ending time of your appointment? '))
if End < Start or End > 22:
print('invalid, please choose a time after starting time. ')
# def is_concurrent():
from datetime import datetime
start = datetime.combine(datetime.strptime(dt, '%d/%m/%Y'), datetime.strptime(str(Start), '%H').time())
end = datetime.combine(datetime.strptime(dt, '%d/%m/%Y'), datetime.strptime(str(End), '%H').time())
current = datetime.now()
if start < current:
print('invalid, enter a time & date in the future! ')
elif end < start:
print('invalid, enter an end time after the start time! ')
else:
break
Subject = input ('What is the subject of your appointment?')
appointment = ['{}; {}; {}; {}; {};'.format(Priority, dt, Start, End, Subject)]
appointmentList.append(appointment)
print(appointmentList)
add_sort()
def sortRecords():
choice = input ('Do you want to sort by priority or time or END. ')
if choice.lower() == 'priority':
print ('priority')
print(appointmentList)
plist = sorted(appointmentList, key = lambda x: x[0])
print(plist)
sortRecords()
elif choice.lower() == 'time':
print('time')
print(appointmentList)
tlist = sorted(appointmentList, key = lambda x: x[1])
print(tlist)
sortRecords()
elif choice.lower() != 'end':
print ('invalid')
sortRecords()
add_sort()
for x in appointmentList:
print (x)
add_sort()
the idea is the user inputs an appointment with priority, date, start time, end time and subject, it first prints like this '[['high; 15/7/2022; 8; 9; Hello;']]' and then saves it to the appointment list, I need to find out how to see if a previously made appointment overlaps with the appointment the user is currently trying to enter.
There seems to be a problem with my logic as it does not always give the right output. for example when I enter 2 and 2 I get [0, 0, 0, 0, 0, 1, 0, 1] and i should get [0, 0, 0, 0, 0, 1, 0, 0]
I think that there is a logical error in my code when it takes the 2 inputs but I cannot see where it is coming from.
8-bit-binary adder
code below
#if you have questions about the code just ask
array
# arrays and funtions
Array1 = []
Array2 = []
#Input A and Validation
def vaildNumberA():
Array1 = []
a = int(input("Enter your A value:"))
if (a < 0):
print("Please Enter A Valid Number For Input A")
elif (a > 255):
print("Please Enter A Valid Number For Input A")
else:
Array1 = [int(x) for x in list('{0:08b}'.format(a))]
#Return the array
return Array1
#Input B and Validation
def vaildNumberB():
Array2 = []
b = int(input("Enter your B value:"))
if (b < 0):
print("Please Enter A Valid Number For Input B")
elif (b > 255):
print("Please Enter A Valid Number For Input B")
else:
Array2 = [int(x) for x in list('{0:08b}'.format(b))]
#Return the array
return Array2
# AND Gate
def AND (a,b):
if (a == 1 and b == 1):
return 1
else:
return 0
#OR Gate
def OR(a,b):
if (a == 1 or b == 1):
return 1
else:
return 0
#XOR Gate
def XOR (a,b):
if (a == b):
return 0
else:
return 1
#carry formula
def carryformula(a,b,c,d):
return OR(AND(a,b), AND(c,d))
# this is where the calculation should be done
loop1
#formula for sum
def calculateSum(Array1,Array2):
carry = ""
sumof = []
for index in range(len(Array1)):
list2 = Array2[index]
sec_xor_form = XOR(Array1[index],Array2[index])
sumof.append(XOR(sec_xor_form,carry))
carry = carryformula(Array1[index],Array2[index],sec_xor_form,carry)
return list(reversed(sumof))
loop
while True:
#Call the function from within the while True loop
Array1 = vaildNumberA()
Array2 = vaildNumberB()
total = calculateSum(list(reversed(Array1)),list(reversed(Array2)))
print(total)
quit = input("if want to quit type q: ")
quit
if quit == 'q':
break
The carry variable should be initialized as 0 instead of an empty string "", so that your XOR function can evaluate a == b as True and properly return 0 when the first bit is 0.
Change:
carry = ""
to:
carry = 0
I'm attempting to create a menu-driven program where python will accept a collection of non-negative integers. It will calculate the mean and median and display the values on the screen. I want my first option to be "Add a number to the list/array", I want my second option to be "Display the mean", the third to be "Display the median", the fourth "Print the list/array to the screen", the fifth "Print the list/array in reverse order" and the last option "Quit". So far I have gotten:
def main():
myList = [ ]
addOne(myList)
choice = displayMenu()
while choice != '6':
if choice == '1':
addOne(myList)
elif choice == '2':
mean(myList)
elif choice == '3':
median(myList)
elif choice == '4':
print(myList)
elif choice == '5':
print(myList)
choice = displayMenu()
print ("\nThanks for playing!\n\n")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' \
and myChoice != '4' and myChoice != '5':
print("""\n\nPlease choose
1. Add a number to the list/array
2. Display the mean
3. Display the median
4. Print the list/array to the screen
5. Print the list/array in reverse order
6. Quit
""")
myChoice = input("Enter option---> ")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4' and myChoice != '5':
print("Invalid option. Please select again.")
return myChoice
#This should make sure that the user puts in a correct input
def getNum():
num = -1
while num < 0:
num = int(input("\n\nEnter a non-negative integer: "))
if num < 0:
print("Invalid value. Please re-enter.")
return num
#This is to take care of number one on the list: Add number
def addOne(myList):
while True:
try:
num = (int(input("Give me a number:")))
num = int(num)
if num < 0:
raise exception
print("Thank you!")
break
except:
print("Invalid. Try again...")
myList.append(num)
#This should take care of the second on the list: Mean
def mean(myList):
myList = [ ]
listSum = sum(myList)
listLength = len(myList)
listMean = listSum / listLength
print("The mean is", listMean)
#This will take care of number three on the list: Median
def median(myList):
median = 0
sortedlist = sorted(myList)
lengthofthelist = len(sortedlist)
centerofthelist = lengthofthelist / 2
if len(sortedlist) % 2 ==0:
return sum(num[center - 1:center + 1]) / 2.0
else:
return num[center]
print("The mean is", centerofthelist)
#This will take care of the fourth thing on the list: Print the list (In order)
def sort(myList):
theList.sort(mylist)
print(myList)
#This will take care of the fifth thing on the list
def reversesort(myList):
theList.sort(reverse=True)
print(myList)
main()
After I run the program I can't get past creating the list.
Corrected code with minimum changes:
def main():
myList = []
choice = 1
while choice != 6:
if choice == 1:
option1(myList)
elif choice == 2:
option2(myList)
elif choice == 3:
option3(myList)
elif choice == 4:
option4(myList)
elif choice == 5:
option5(myList)
choice = displayMenu()
print ("\nThanks for playing!\n\n")
def displayMenu():
myChoice = 0
while myChoice not in [1, 2, 3, 4, 5]:
print("""\n\nPlease choose
1. Add a number to the list/array
2. Display the mean
3. Display the median
4. Print the list/array
5. Print the list/array in reverse order
6. Quit
""")
myChoice = int(input("Enter option---> "))
if myChoice not in [1, 2, 3, 4, 5]:
print("Invalid option. Please select again.")
return myChoice
# Option 1: Add a number to the list/array
def option1(myList):
num = -1
while num < 0:
num = int(input("\n\nEnter a non-negative integer: "))
if num < 0:
print("Invalid value. Please re-enter.")
myList.append(num)
# Option 2: Display the mean
def option2(myList):
print("The mean is ", sum(myList) / len(myList))
# Option 3: Display the median
def option3(myList):
sortedlist = sorted(myList)
if len(sortedlist) % 2:
median = myList[int(len(sortedlist) / 2)]
else:
center = int(len(sortedlist) / 2)
median = sum(myList[center-1:center+1]) / 2
print("The median is", median)
# Option 4: Print the list/array
def option4(myList):
print(sorted(myList))
# Option 5: Print the list/array in reverse order
def option5(myList):
print(sorted(myList, reverse=True))
main()
How I would do this:
The first part of the following code are a set of constants to customize the style of the menu. Then a set of functions representing each option are defined. The following 3 functions should not be modified, they generate the menu, display it and close the application. Then the main section starts, where you need to pass every option as an argument to setOptions(). The rest should not be modified either as it is the main loop.
# Menu formatting constants
MENU_HEADER = "Please choose an option:"
MENU_FORMAT = " * {:2}. {}"
MENU_QUIT_S = "Quit"
MENU_ASK_IN = "Enter option: "
MENU_INT_ER = "ERROR: Invalid integer. Please select again."
MENU_OPT_ER = "ERROR: Invalid option. Please select again."
END_MESSAGE = "Thanks for playing!"
# OPTIONS FUNCTIONS START HERE
def addElement(l):
""" Add a number to the list/array. """
n = -1
while n < 0:
try:
n = int(input("Enter a non-negative integer: "))
except ValueError:
print("It needs to be an integer.")
n = -1
else:
if n < 0:
print("It needs to be a non-negative integer.")
l.append(n)
def mean(l):
""" Calculate the mean. """
print("Mean: {:7.2}".format(sum(l) / len(l)))
def median(l):
""" Calculate the median. """
l = sorted(l)
p = int(len(l) / 2)
print("Median: {:7.2}".format(l[p] if len(l)%2 else sum(l[p-1:p+1])/2))
def oprint(l):
""" Print the list/array. """
print(sorted(l))
def rprint(l):
""" Print the list/array in reverse order. """
print(sorted(l, reverse=True))
# OPTIONS FUNCTIONS END HERE
def onQuit(l):
""" Function to execute when quitting the application. """
global quit
quit = True
print(END_MESSAGE)
def setOptions(*args):
""" Generates the menu and the options list. """
# Menu header and quit option (option 0)
menu = [MENU_HEADER]
options = [onQuit]
# Passed arguments represent texts and functions of additional options
for i, f in enumerate(args, start=1):
menu.append(MENU_FORMAT.format(i, f.__doc__.strip()))
options.append(f)
# We print the option 0 the last one
menu.append(MENU_FORMAT.format(0, MENU_QUIT_S))
# Returning both the menu and the options lists
return tuple(menu), tuple(options)
def displayMenu(menu):
""" Display the menu and get an option that is an int. """
while True:
for line in menu:
print(line)
try:
choice = int(input(MENU_ASK_IN))
except ValueError:
print(MENU_INT_ER)
else:
return choice
if __name__ == '__main__':
# Pass the option functions to the setOptions function as arguments
menu, options = setOptions(
addElement,
mean,
median,
oprint,
rprint
)
# Initiate the needed variables and start the loop
l = []
quit = False
while not quit:
c = displayMenu(menu)
try:
f = options[c]
except IndexError:
print(MENU_OPT_ER)
else:
f(l)
There is an indentation error inside your function addOne.
myList.append(num) is inside the while loop, and just before that you have a break, so the number is never appended to the list because we have left the loop already.
So I need to create a function in python that asks the user to input numbers and enter end when done. After that I need to compute the sum of the numbers enter excluding the max number. (i.e if the user entered 20, 50, and 100 the sum would be 70)
So for I have this which loops input until user inputs the word end:
def excludeMax():
while True:
result = input('Enter next number or end:')
if (result == 'end'):
break
This looks like what you are looking for.
def excludeMax():
numbers = []
while True:
result = input('Enter next number or end:')
if (result == 'end'):
break
else:
numbers.append(result)
# notice this is after the loop
numbers.remove(max(numbers))
return sum(numbers)
Simply sort it and then add up a slice:
def exclude_max():
return sum(sorted(map(int, iter(lambda: input('Enter next number or end: '), 'end')))[:-1])
Result:
>>> exclude_max()
Enter next number or end: 20
Enter next number or end: 50
Enter next number or end: 100
Enter next number or end: end
70
Place all numerical input into a list. If you see an end, break from the while loop. Once you've exited the while loop, remove the max element from the list (e.g., lst.remove(max(list))). Finally, get the sum via sum(lst).
Approach 1: No temp lists and sort needed in this approach. Excludes just one of the max numbers(doesn't deal with duplicates)
def excludeMax():
biggest_sof_far = None
sum_of_inputs = 0
while True:
result = input('Enter next number or end:')
if result == 'end':
break
if biggest_sof_far == None:
biggest_sof_far = result
elif result > biggest_sof_far:
sum_of_inputs += biggest_sof_far
biggest_sof_far = result
else:
sum_of_inputs += result
return sum_of_inputs
if __name__ == "__main__":
print excludeMax()
Approach 2: Using a temp list (increases space complexity) and sort and sum on list(increases time complexity). This to excludes just one max numbers(doesn't deal with duplicates)
def excludeMax():
input_numbers = []
while True:
result = input('Enter next number or end:')
if result == 'end':
break
input_numbers.append(result)
input_numbers.sort()
return sum(input_numbers[:-1])
if __name__ == "__main__":
print excludeMax()
Both the approaches assume that you want to exclude just one max element. If you want to exclude all max elements(in case of duplicate max numbers):
Approach 1: Excludes even the duplicate max numbers
def excludeMax():
biggest_sof_far = None
sum_of_inputs = 0
while True:
result = input('Enter next number or end:')
if result == 'end':
break
if biggest_sof_far == None:
biggest_sof_far = result
elif result == biggest_sof_far:
pass
elif result > biggest_sof_far:
sum_of_inputs += biggest_sof_far
biggest_sof_far = result
else:
sum_of_inputs += result
return sum_of_inputs
if __name__ == "__main__":
print excludeMax()
Approach 2: Excludes even the duplicate max numbers
def excludeMax():
input_numbers = []
while True:
result = input('Enter next number or end:')
if result == 'end':
break
input_numbers.append(result)
input_numbers.sort()
omit_till_index = -1
input_len = len(input_numbers)
while input_len > -omit_till_index and \
input_numbers[omit_till_index] == input_numbers[omit_till_index-1]:
omit_till_index = omit_till_index-1
return sum(input_numbers[:omit_till_index])
if __name__ == "__main__":
print excludeMax()
In your loop append all input values to a list (if not 'end'). After that sort list in place and compute sum for list[:-1] (gives you the list without the last element).
In code:
numbers = []
def excludeMax():
while True:
result = input('Enter next number or end:')
if (result == 'end'):
break
else:
numbers.append(result)
numbers.sort()
sum_numbers = sum(numbers[:-1])
I am making a code to simulate a dice and do other stuff, but there is a while loop which isn't breaking and I don't know why.
import random
import math
#infinite loop
while True:
while True:
a = 0
#input amount of dice
att_die = raw_input('Attacking dice: ')
def_die = raw_input('Defending dice: ')
#att
#if NaN
if str(att_die).isdigit() == False:
print('NaN')
#if not NaN
else:
a += 1
#def
#if NaN
if str(def_die).isdigit() == False:
print('NaN')
#if not NaN
else:
a +=1
if a == 2:
break
if att_die >= def_die:
no = def_die
else:
no = att_die
print (no)
x = 0
while x <= no:
att_loss = 0
def_loss = 0
roll_att = random.randint(1,6)
roll_def = random.randint(1,6)
if roll_att <= roll_def:
att_loss += 1
elif roll_att == roll_def:
att_loss += 1
else:
def_loss += 1
x += 1
print(x)
print('Att: -' + str(att_loss) + '\nDef: -' + str(def_loss))
everything works up until the last while loop, which just continuously outputs the value of x increasing.
Any help on how to fix this would be appreciated.
Thanks in advance
no is a str, not an int. x is an int. In Python2, ints are always compare less than strs:
In [187]: 9999 < '1'
Out[187]: True
The solution is to convert the str no into an int:
no = int(no)
In [188]: 9999 < int('1')
Out[188]: False
Note that in Python3, comparing an int with a str raises a TypeError, which will save many a programmer from this pitfall.
Here's a refactored version:
import random
import math
DIE_SIDES = 6
WINNING_ATTACK_ODDS = 0.5 * (DIE_SIDES - 1) / DIE_SIDES
def get_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def attack():
"""
Does the attacker win?
"""
return random.random() < WINNING_ATTACK_ODDS
def main():
while True:
att_die = get_int("Attacking dice: ")
def_die = get_int("Defending dice: ")
rolls = min(att_die, def_die)
def_loss = sum(attack() for _ in range(rolls))
att_loss = rolls - def_loss
print("Att: -{}\nDef: -{}".format(att_loss, def_loss))
if __name__=="__main__":
main()