Can anyone help me make a Polygon Generator in Python? - python

It should ask for a number between 4 and 8 and then turtle will draw those sides.
The interior angle equation:
where N is the # of sides (N -2)180= x, then x divided by N = draw
sides
>>> import turtle
>>> t=turtle.Pen()
>>> usernum = int(input('Give me a number between 4 and 8: '))
Give me a number between 4 and 8: 5
>>> if usernum < 4 or usernum > 8:
print ("invalid number!")
else:
draw
myangle = (((numSides-2) * 180)/ numSides)
turtle.right(180 - myangle)

Since you showed what you actually tried I'll toss you a bone, but you almost certainly could have figured out how to do this from a couple of quick Google searches.
For whatever reason I have some issues running turtle graphic scripts from IDLE, I don't know if you have better luck.
import turtle
t = turtle.Pen()
num_sides= int(input("Give me a number between 4 and 8: "))
side_length = 30
while True:
if (num_sides < 4) or (num_sides > 8):
num_sides = int(input("Invalid Number! Please enter a new one from 4-8: "))
else:
myangle = 360 / side_length
break
for i in range(num_sides):
t.forward(side_length)
t.right(myangle)
If like me you have issues running that from IDLE try running it from the python interpreter in the command line. Using a slightly modified version of this I made all of the polygons where num_sides = range(3, 15). As a note, the reason that we don't get exactly back to the start each time is due to the use of integers instead of floating point numbers. Changing this to use floating point should resolve that issue.

Related

WAP in python script to input a multidigit number and find each of the number's factorial

The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')

How to find out if a number is a perfect square without using sqrt function or ** in Python? [duplicate]

This question already has answers here:
Check if a number is a perfect square
(25 answers)
Closed 4 days ago.
I have to write a program that finds out whether or not a number is a perfect square. The terms are I don't use a sqrt function or an exponent (**)
I previously showed my teacher my solution using exponent (**) and she told me not to include that there.
num=int(input("Enter a positive integer: "))
base=1
while num/base!=base:
base=base+1
if (num/base)%1==0:
print(num,"is a square")
else:
print(num,"is not a square")
It works fine with perfect squares but when they're not, it won't work because I can't find a way to get it out of the while loop even though it's not a perfect square.
You have to change
while num/base!=base:
to
while num/base>base:
and it will work.
You can iterate till finding a value bigger than you number:
You are sure the while will finish since you have a strictly increasing sequence.
def is_perfect_square(x):
i = 1
while i*i < x:
i += 1
return i*i == x
print(is_perfect_square(15))
# False
print(is_perfect_square(16))
# True
The sum of the first odd integers, beginning with one, is a perfect square.
See proof
1 = 1
1 + 3 = 4
1 + 3 + 5 = 9
1 + 3 + 5 + 7 = 16
and so on .....
So here, we can make use of this important fact to find a solution without using pow() or sqrt() in-built functions.
num = int(input("Enter a positive integer: "))
odd = 1
while num > 0:
num -= odd
odd += 2
if num == 0:
print('It is a pefect square')
else:
print('It is not a pefect square')
I guess it is not a place to answer such questions, but here is a super straightforward solution without using any tricks.
num=int(input("Enter a positive integer: "))
for i in range(num + 1): # in case you enter 1, we need to make sure 1 is also checked
pow = i * i
if pow == num:
print('%d is a pefect square' % num)
break
elif pow > num:
print('%d is not a pefect square' % num)
break
Instead of dividing and taking the remainder, multiply the base and see if it matches the number you are testing. For instance.
for i in range(1, num + 1):
sq = i * i
if sq == num:
print(f"{i} squared is exactly {num}")
break
if sq > num:
print(f"{num} is not a perfect square")
break
You might get a better mark if you do something more clever than increment from 1. A binary search would speed things up a lot for large numbers.
Hey Buddy Try This Code,
num=int(input("Enter a positive integer: "
base=1
while num/base>base:
base=base+1
if (num/base)%1==0:
print(num,"is a square")
else:
print(num,"is not a square")
It should work I tried it
Jai hind jai bharat
Here is something that I came up with:
from math import *
num = eval(input('Enter a number: '))
sq = sqrt(num)
sq1 = sq%1 #here we find the decimal value and then..
if sq1 == 0.0: #if the value = 0 it is a perfect square else it is not, only perfect
squares will be whole numbers.
print(f'{num} is a perfect square')
else:
print(f'{num} is not a perfect square')

Python and random.randint()

I have the following problem from school: the teacher has asked us to divide to sides with 2/3 and 1/3 probabilities using the randint function.
I really don't understand how this randint function on probabilities works.
import random
rand = (random.randint(1,100))
if rand >= 67 :
print ("obj A 1/3")
else:
print ("obj B 2/3")
This does not work.
One key skill you must learn is using documentation. A quick search brought me to the Python manual page on random.randint():
Return a random integer N such that a <= N <= b.
Your creating a variable rand which is equal to a random number >= 1 and <= 100. The next line is a conditional that checks if your number is >= 67...this will only be true ~1/3 of the time.
Side note: there's no benefit to using a random number between 1-100. Your code would be much more straightforward (and therefore Pythonic) if you looked for exactly what you wanted (i.e. 1/3).
import random
rand = random.randint(1, 3)
if rand is 1:
print '1/3'
else:
print '2/3'
Why so complicated? Simplify to the level of your denominator: 3. Generate one of three integers, with equal probability. You'll get 1, 2, and 3; each appears 1/3 of the time.
rand = random.randint(1,3)
if rand == 1:
print ("obj A 1/3")
else:
print ("obj B 2/3")
Is this simple enough for you to understand? In your original code, you were generating 100 different integers. You did the "A" part in 34 of those cases. That's 34%, a little more than the requested 1/3.
random.randint(1,100)
This returns a number from 1 to 100. So, 1/3 is about 33 and 2/3 is about 66. So the first if statement is seeing that if the number is equal or greater than than 67, print "obj A 1/3", which is this part:
if rand >= 67:
print ("obj A 1/3")
Anything else, then print "obj A 2/3", which is the last part:
else:
print ("obj B 2/3")
Of course, you need to use print() like that and not like this, print () unless you want a Syntax error. Also, the math is wrong. The program should look more like this:
import random
rand = (random.randint(1, 3))
if rand == 1:
print("obj C 3/3")
elif rand == 2:
print("obj A 2/3")
elif rand == 1:
print("obj B 1/3")
The above math is the most accurate as you have a 1/3 chance of getting one of the numbers, which corresponds to the numerator in the fraction, x over 3, where rand is equal to x.
I think I see what you're trying to do but you need to start here by reading up on random. Check out this question/answer, I think it will explain things better. Your current code will get a syntax error, I think what you're looking to do is this:
import random
rand = (random.randint(1,100))
if rand >= 67:
print("1/3rd") # Do the 1/3rd things...
else:
print("2/3rd") # Do the 2/rd things...
I implore you to go read up on python though. PS. A more accurate solution would be to generate a random int from 1 to 3 instead of thinking of the problem in terms of 1-100. Then your probability becomes more accurate since 1/3rd = 33.3333... of the time, its hard to represent it using 1-100.

Python number guessing game

I have found some practice problems online and I got most of them to work, but this one has stumped me. Its not homework so I'm not getting a grade. However, there isn't a solution provided so the only way to get the answer is by doing it.
The task asks for you to write a problem that plays a number guessing game for numbers 1-100. However, this one tries to guess the users number by interval guessing, such as [1, 100] and generates the next question by using first+last/2.
I have a sample run from the site.
Think of a number between 1 and 100 (inclusive).
Answer the following questions with letters y or Y for yes and n or N for no.
interval: [1,100]. Is your number <= 50? y
interval: [1,50]. Is your number <= 25? y
interval: [1,25]. Is your number <= 13? y
interval: [1,13]. Is your number <= 7? n
interval: [8,13]. Is your number <= 10? n
interval: [11,13]. Is your number <= 12? y
interval: [11,12]. Is your number <= 11? y
Your number is: 11
Here is my code so far, but I don't even quite know where to start because a while-loop constantly gives me an infinite loop. I know the "middle" number needs to be an integer or else it'll be an infinite loop, but I can't seem to figure out how to do that.
x = input("Is your numbr <=50?")
count = 100
while x=="y" or "Y":
count = count/2
x = input("Is your number <=",count,"?")
print(count)
If anyone has any tips it would be greatly appreciated.
The issue is here:
while x=="y" or "Y":
the expression "Y" will always evaluate to true.
You want
while x == "y" or x == "Y":
Even then, this will end the loop when the user types an "N". A working loop would be something like:
finished = False
while not finished:
if x == "y":
upper -= (upper-lower)/2
# prompt for input
elif x == "n":
lower += (upper-lower)/2
# prompt for input
if upper == lower or (upper - 1) == lower:
finished = True
# final output
You should be able to fill in the blanks from there.
The entire idea of the problem is to keep both "bounds" starting at 1 and 100, and each time you make a question "is you number <= X" you discard half of the range according to the answer, you are not doing this in your current solution.
like this.
lower = 1
high = 100
mid = (high + lower)/2 -> at start it will be 50
If the user answers Yes then you take the range from the current lower bound to the mid of the range, otherwise you continue with the range starting on mid+1 to the end, like this:
If user answers Yes:
high = mid
If user answers No:
lower = mid +1
The last part of the idea is to detect when the range lower-high contains only 2 numbers, or are the same number like this [11,12], you use the final answer of the user to choose the correct answer and the program terminates, the full code is here so you can test it:
found = False
range_lower_bound = 1
range_high_bound = 100
print "Think of a number between 1 and 100 (inclusive)."
print "Answer the following questions with letters y or Y for yes and n or N for no."
while not found:
range_mid = (range_high_bound + range_lower_bound) / 2
x = raw_input('interval: [%s,%s]. Is your number <= %s? ' % (range_lower_bound, range_high_bound, range_mid))
if x.lower() == 'y':
# Check if this is the last question we need to guess the number
if range_mid == range_lower_bound:
print "Your number is %s" % (range_lower_bound)
found = True
range_high_bound = range_mid
# here i'm defaulting "anything" no N for simplicity
else:
# Check if this is the last question we need to guess the number
if range_mid == range_lower_bound:
print "Your number is %s" % (range_high_bound)
found = True
range_lower_bound = range_mid + 1
Hope it helps!
One good idea would be to have a simple while True: loop, inside which you maintain a maximum guess and a minimum guess. You then ask the user whether their number is greater than the average of the two. If it is, update your minimum guess to the average. If not, you lower your maximum guess to the average. Repeat until the two guesses are equal, at which point you have found the number, and can break out of the infinite loop.
You'll have to do some simple parity checking of course, to make sure you actually change your guesses in each round. You should really use raw_input() for strings, input() is for python-formatted data.

python input error checking

Hello, I am trying to get my input to only allow integers, and once it gets past 10, it displays error, any assistance would be appreciated.
square_ct = input("Enter an integer from 1-5 the number of squares to draw: ")
triangle_ct = input("Enter an integer from 1-5 the number of triangles to draw: ")
while square_count(input) > 10:
print ("Error!")
square_count=input() #the statement reappears
while triangle_count(input) > 10:
print ("Error!")
triangle_count=input() #the statement reappears
My preferred technique is to use a while True loop with a break:
while True:
square_ct = input("Enter an integer from 1-5 the number of squares to draw: ")
if square_ct <= 10: break
print "Error"
# use square_ct as normal
Or, on Python 3:
while True:
square_ct = int(input("Enter an integer from 1-5 the number of squares to draw: "))
if square_ct <= 10: break
print("Error")
# use square_ct as normal
I took the path nneonneo offered and got pretty close to what I wanted. The final result is below.
I thank all of you for your comments. The last time I did anything even slightly like programming was in Fortran on punch cards on an IBM 360.
I apologize for asking such basic questions but really am trying.
The code that works but really doesn't point out exactly which fault happened. I will try to figure out how to convert the string in the input statement to a float and see if there is a remainder (modulo maybe?) so the user gets a better hint what was wrong.
import math
from datetime import datetime
import time
num = 0
start = 0
end = 0
try:
num = int(input('Enter a positive whole number: '))
if (num >= 0 and num <= 2147483647):
start = datetime.now()
print("The factorial of ", num, " is : ")
print(math.factorial(int(num)))
end = datetime.now()
else:
print('Number must be between 0 and 2147483647 are allowed.')
print(f"Time taken in (hh:mm:ss.ms) is {end - start}")
except ValueError:
print('Text or decimal numbers are not allowed. Please enter a whole number between 0 and 2147483647')
I have a lot to learn because I'm bored...
Norman

Categories

Resources