I am coding a program that lets you type in the three angles or sides of a triangle, and it tells if it's equilateral, isosceles etc. I am not worrying about the rest for now, but I'm stuck on the equilateral part of it. Here is my code:
def idtri():
print("\nDo you have all three sides, or al three angles?")
print("(1) Sides")
print("(2) Angles")
choice = input()
if choice == 1:
print("\nType in the lengths of all of the sides.")
t1 = input("1: ")
t2 = input("2: ")
t3 = input("3: ")
print("Your triangle is an equalateral triangle.")
menu()
elif choice == 2:
pass
idtri()
The first thing to note is that, for identifying the triangle as scalene, isoceles, or equilateral, it doesn't matter whether the three values you have are the angles or the side lengths, the process is:
If all three values are the same, the triangle is equilateral;
otherwise, if any two values are the same, the triangle is isoceles;
otherwise, the triangle is scalene.
So you can write a simple function to return the type based on the number of equal values provided:
id_triangle = lambda a, b, c: {0: 'scalene', 1: 'isoceles', 3: 'equilateral'}\
[(a == b) + (a == c) + (b == c)]
and then call that from your interactive script, like:
print('Your triangle is %s.' % id_triangle(t1, t2, t3))
You can also use the counter from the Python collections:
from collections import Counter
def idtri():
cnt = Counter()
side1 = input('Enter length of first side: ')
cnt[side1] += 1
side2 = input('Enter length of second side: ')
cnt[side2] += 1
side3 = input('Enter length of third side: ')
cnt[side3] += 1
if 3 in cnt.values():
print('Equilateral Triangle')
elif 2 in cnt.values():
print('Isosceles Triangle')
else:
print('Scalene Triangle')
if __name__ == "__main__":
idtri()
Related
Trying to have the while loop read the selection but the program only reads the first one for square and 5 to close the program, what do I need to change in order for it to actually read it the values 2,3 and 4 so I can add the other functions for the areas? I've tried
it with elif and else but when I add that it won't even read the selection
def square(l):
area = l*l
return area
def rectangle(l,w):
area = l*w
return area
def triangle(b,h):
#b: base , h: height
b = int(input('Enter the Base of your Triangle: '))
h = int(input('Enter the Height of your Triangle'))
area = (b * h)/2
print('Area of the Triangle= ' +str(area))
print ("Choose which shape whos area you would like to find:")
print ("1 = Square")
print ("2 = Rectangle")
print ("3 = Triangle")
print ("4 = circle")
print ("Enter Option: ")
user_input = 0
while user_input not in (1,5) :
user_input = int(input("Enter your Choice: "))
#--------------------------------------------------------------
if (user_input == 1):
print ("You've selected area of a Square")
length = int(input("Enter the length of a side from your square: "))
area = square(length)
print("Area of your Square is: ", area)
#--------------------------------------------------------------
if (user_input == 2):
print ("You've selected area of a Rectangle")
length = int(input("Enter the length of your rectangle: "))
width = int(input("Enter the width of your rectangle: "))
area = rectangle(length,width)
print("Area of your rectangle is: ", area)
Your problem is with this line of code:
while user_input not in (1, 5):
This is checking for exactly what you say the code seems to be checking for, just either 1 or 5. This is the case because (1, 5) creates a tuple containing the numbers 1 and 5. This line therefore is testing if user_input is one of those two values.
I think what you meant to do is this instead:
while user_input not in range(1, 6):
You have to use 6 rather than 5 because the second argument to range() is not included in the resulting range. So range(1, 5) would produce the equivalent of the tuple (1, 2, 3, 4).
I'm trying to use a timer to see how fast each function is. My codes work but after running it many times I get slightly different results and wonder if I'm implementing function correctly. I am only going to the 10th Fibonacci number which is 55 for testing. Each time I run the "A" option the clockTime() function returns a slightly larger number than before. Any thoughts would be appreciated.
import math
import time
#create a time variable
start_time = time.time()
#create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2
#the runtime function
def clockTime():
print("\nrun time: " + str(time.time()-start_time))
#the golden ration function
def fibGen(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{i:3}: {v:3}'.format(i=number, v=round(val)))
#the find element < Max number function
def elemFib(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
if val < num:
print('Fib({}): {}'.format(number, round(val)))
#Pythonic way
def pythonic():
a, b = 0,1
while a < 57:
print(a, sep=" ", end="\n")
a, b = b, a+b
#display the Main Menu
def dispMenu():
print('---------------------Fibonacci Series ------------------\n')
print('(A) Print Fibonacci numbers to the nth term')
print('(B) Print Fibonacci numbers until element is less than Max number')
print('(C) pythonic print')
print('(Q) Quit the program\n')
def main():
# set boolean control variable for loop
loop = True
#Create while loop for menu
while loop:
#Display the menu
dispMenu()
#Get user's input
choice = (input('Please make a selection: '))
#Perform the selected action
if choice.upper() == 'A':
num = int(input("How many Fibonacci numbers should I print? "))
fibGen(num)
clockTime()
elif choice.upper() == 'B':
num = int(input("the element should be less than? "))
elemFib(num)
clockTime()
elif choice.upper() =='C':
pythonic()
clockTime()
elif choice.upper() == 'Q':
print('\nExiting program, Thank you and Goodbye')
loop = False
else:
print('\nInvalid selection, try again\n')
main()
The problem is you initialized start_time at the start of the program rather than right before you ran the function to be timed. You were adding in the times of previous runs as well as the time the user took to read the instructions and make a decision, etc. Here's a rework of your code that should do what you want:
import math
import time
# create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2
# the runtime function
def clockTime(start_time):
print("\nrun time:", time.time() - start_time)
# the golden ration function
def fibGen(num):
for number in range(num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{i:3}: {v:3}'.format(i=number, v=round(val)))
# the find element < Max number function
def elemFib(num):
for number in range(num + 1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
if val < num:
print('Fib({}): {}'.format(number, round(val)))
# Pythonic way
def pythonic():
a, b = 0, 1
while a < 57:
print(a, sep=" ", end="\n")
a, b = b, a + b
# display the Main Menu
def dispMenu():
print('---------------------Fibonacci Series ------------------\n')
print('(A) Print Fibonacci numbers to the nth term')
print('(B) Print Fibonacci numbers until element is less than Max number')
print('(C) pythonic print')
print('(Q) Quit the program\n')
def main():
# set boolean control variable for loop
loop = True
# Create while loop for menu
while loop:
# Display the menu
dispMenu()
# Get user's input
choice = input('Please make a selection: ').upper()
# Perform the selected action
if choice == 'A':
num = int(input("How many Fibonacci numbers should I print? "))
start_time = time.time()
fibGen(num)
clockTime(start_time)
elif choice == 'B':
num = int(input("the element should be less than? "))
start_time = time.time()
elemFib(num)
clockTime(start_time)
elif choice == 'C':
start_time = time.time()
pythonic()
clockTime(start_time)
elif choice == 'Q':
print('\nExiting program, Thank you and Goodbye')
loop = False
else:
print('\nInvalid selection, try again\n')
main()
My assingment
At each level the complete triangle for the previous level is placed into an extra outer triangle. The user should be asked to input the two characters to be used and the width of the innermost triangle, which must be odd. In addition to the test for negative input the function should test whether the supplied number is odd and display an appropriate message if it is not.
I need to print 3 triangles but every one of them includes other. It needs to get printed with two different character(like *-) and the user have to specify the length of innermost triangle and which has to be an odd number. Example,
Example output for 5 value
Ok, let me explain my way,
Every triangle should be in dictionary.
tri1 = {1:"*****", 2:"***", 3:"*"}
tri2 = {1:"..........", ...}
And couldn't find how I can deal with user input?
If enter 5,
length - 5 unit, height 3 unit
length - 11 unit, height 6 unit
length - 23 unit, height 12 unit.
How can i know? What is the logic?
Ok lets say if I did. I understand I should put a tringle in another triangle with nested loop, can simply iterate it another dictionary but, I need to check second character's position.
Thanks in advance.
My code,
ch1, ch2 = input("Please enter the characters you want to use: ")
num = int(input("Please specify the length of innermost triangle(only odd number): "))
if (num % 2 == 0) or (num < 3):
print("Number can not be even, less then 3 and negative")
num2 = (2 * num) + 1
num3 = (2 * num2) +1
tri1 = {}
tri2 = {}
tri3 = {}
for i in range(3):
tri1[i] = ch1*num
num -= 2
check = 1
cont = 0
var = 1
for ii in range(6):
tri2[ii] = ch2*check
check += 2
if (ii >= 3):
tri2[ii] = ch2*var + tri1[cont] + ch2*var
cont += 1
var += 2
for i in tri1:
print('{:^5}'.format(tri1[i]))
for i in tri2:
print('{:^11}'.format(tri2[i]))
The dictionary can be created using a simple function:
def create_tri_dict(tri_chars, tri_height):
level_str = {0:tri_chars[0]}
for i in range(1,tri_height):
level_length = i *2 +1
tri_char = tri_chars[i%2]
level_str[i] = level_str[i-1] + '\n' + tri_char * level_length
return level_str
Then the main logic of your program could be:
tri_chars = input('Input triangle characters: ')
tri_length = int(input('Input triangle base length: '))
tri_height = (tri_length + 1)//2
if tri_length %2 == 0:
raise Exception('Triangle base length not odd')
tri_dict = create_tri_dict(tri_chars, tri_length)
Then to print the final 3(?) triangles:
print(tri_dict[tri_height-2])
print(tri_dict[tri_height-1])
print(tri_dict[tri_height])
This is my code for a game in which the computer must guess a user defined number within a given range. This is a challenge from a beginners course/ book.
I'd like to draw your attention to the 'computerGuess()' function. I think there must be a more eloquent way to achieve the same result? What I have looks to me like a botch job!
The purpose of the function is to return the middle item in the list (hence middle number in the range of numbers which the computer chooses from). The 0.5 in the 'index' variable equation I added because otherwise the conversion from float-int occurs, the number would round down.
Thanks.
Code:
# Computer Number Guesser
# By Dave
# The user must pick a number (1-100) and the computer attempts to guess
# it in as few attempts as possible
print("Welcome to the guessing game, where I, the computer, must guess your\
number!\n")
print("You must select a number between 1 and 100.")
number = 0
while number not in range(1, 101):
number = int(input("\nChoose your number: "))
computerNumber = 0
computerGuesses = 0
higherOrLower = ""
lowerNumber = 1
higherNumber = 101
def computerGuess(lowerNumber, higherNumber):
numberList = []
for i in range(lowerNumber, higherNumber):
numberList.append(i)
index = int((len(numberList)/2 + 0.5) -1)
middleValue = numberList[index]
return middleValue
while higherOrLower != "c":
if computerGuesses == 0:
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "l":
higherNumber = computerNumber
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "h":
lowerNumber = computerNumber + 1
computerNumber = computerGuess(lowerNumber, higherNumber)
print("\nThankyou. My guess is {}.".format(computerNumber))
computerGuesses += 1
higherOrLower = input("\nHow did I do? If this is correct, enter\
'c'. If your number is higher, enter 'h'. If it is lower, enter 'l': ")
print("\nHaha! I got it in {} attempt(s)! How great am I?".format\
(computerGuesses))
input("\n\nPress the enter key to exit.")
Like this ?
import math
def computerGuess(lowerNumber, higherNumber):
return int((lowerNumber+higherNumber)/2)
def pickOne():
print 'PROPERTIES OF SOLIDS OF REVOLUTION'
print 'Pick a solid to analyze'
print ' 1: ball\n' \
' 2: bwolingPin\n' \
' 3: ellipse\n ' \
' 4: tableLeg\n' \
' 5: quit\n\n '
menu = []
silhouette = ()
flag = 1
while flag:
pickS = raw_input('What is the Number of your choice?')
pickS = int(pickS)
if pickS == 1:
silhouette = str(ball)
flag = 1
if pickS == 2:
silhouette = bowlingPin
flag = 1
if pickS == 3:
silhouette = ellipse
flag = 1
if pickS == 4:
silhouette = tableLeg
flag = 1
if pickS == 5:
flag = 1
main()
else:
flag = 0
print 'Choice %s is not a valid choice' %(pickS)
return
tempinput = raw_input('enter min and max number of points to use (e.g., 2 1000)').split(' ')
minNum = tempinput[0]; maxNum = tempinput[1]
return silhouette , minNum, maxNum
i am new to programming,
i was been told to do a menu for a program, the body code i am done, just this menu really gives me hard time, hope you guys can help me.
I want this fnc work as, if user choose 1-4 for the 1st option, it continues and goes to second Determination that will return two int within 2 to 1000.
the whole function will return the name of the silhouette so that other fnc can call it. and two int.
From my understanding of your question, your logic is flawed. First, you use if statements where you probably want to use elif which is short for else if. Second, your function will always end on printing out 'invalid choice', due to your flag setting. There's also an unused variable and a bunch of unnecessary flag setting, and your minnum and maxnum variables are strings instead of integers (a list comprehension can fix this). You can also do a thing called sequence unpacking to get the values from tempinput. Variable and function names are usually written like lower_case_with_underscores instead of mixedCase.
List comprehensions: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
Sequence unpacking: https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences
def pick_one():
print '''PROPERTIES OF SOLIDS OF REVOLUTION
Pick a solid to analyse:
1: Ball
2: Bowling Pin
3: Ellipse
4: Table Leg'''
silhouette = None
choice = int(raw_input('Enter the number for your choice: '))
while choice not in [1, 2, 3, 4]:
choice = int(raw_input('Enter the number for your choice: '))
if choice == 1:
silhouette = ball
elif choice == 2:
silhouette = bowling_pin
elif choice == 3:
silhouette = ellipse
elif choice == 4:
silhouette = table_leg
tempinput = raw_input('Enter the minimum and maximum number of points to use (e.g. 2 1000) ').split()
min_num, max_num = [int(n) for n in tempinput]
return silhouette, min_num, max_num
If i understand the question correctly i see a few issues with your code. You are using if when you want to use elif which is short for else if. The way you have it written the "Choice is not valid" option will run everytime unless you set pickS == 5 Here is an updated code.
def pickOne():
print 'PROPERTIES OF SOLIDS OF REVOLUTION'
print 'Pick a solid to analyze'
print ' 1: ball\n' \
' 2: bwolingPin\n' \
' 3: ellipse\n' \
' 4: tableLeg\n' \
' 5: quit\n\n '
menu = []
silhouette = ()
flag = 1
while flag:
pickS = raw_input('What is the Number of your choice? ')
pickS = int(pickS)
if pickS == 1:
silhouette = ball
flag = 1
elif pickS == 2:
silhouette = bowlingPin
flag = 1
elif pickS == 3:
silhouette = ellipse
flag = 1
elif pickS == 4:
silhouette = tableLeg
flag = 1
elif pickS == 5:
flag = 1
main()
else:
flag = 0
print 'Choice %s is not a valid choice' %(pickS)
return
tempinput = raw_input('enter min and max number of points to use (e.g., 2 1000) ').split(' ')
minNum = tempinput[0];
maxNum = tempinput[1]
return silhouette , minNum, maxNum