When I try to run this code, I get incorrect maximums and minimums. Could anyone tell me how I can fix it? I am not allowed to use 'max' and 'min'.
UPDATE: I have updated the code and it still doesn't work properly.
UPDATE 2: The code works now! Thank you so much guys!
minimum=float('inf')
maximum=None
count=0
total=0
number=input ("Please enter the amount of numbers you wish to categorize: ")
while True:
num = input("Enter a number: ")
count+=1
total+=num
if num is None or num < minimum:
minimum = num
if num is None or num > maximum:
maximum = num
if count == number:
break
print "The average of your numbers is ", round ((total / count),2),"."
print 'The largest number is:', maximum,"."
print 'The smallest number is:', minimum,"."
Your initial values and conditions for minimum and maximum are incorrect.
minimum = None
maximum = None
...
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
...
You could also fix this by checking if count equals 1 instead of identity to None.
In addition to what Ignacio said, you're breaking out of your loop too early. You want to process the last number you enter before breaking, so move the if count == number: break block after the min/max setting blocks.
Note that you can set a number to infinity or negative infinity by
maximum=float('-inf')
minimum=float('inf')
print minimum, maximum
This might be useful for your homework ;)
Ignacio's answer would be preferable if you want to consider the case that the user enters 0 for number (since None would be a more seasonable maximum of no numbers than -inf).
Edit:
Remark to mVChr's correct finding:
Instead of using a while True loop with a break why not writing
while count < number:
or even use a for loop:
for count in xrange(number):
As this is homework you're supposed to learn. Here are some ideas how to solve the problem:
One error is that you're initializing maximum and minimum to 0 on program startup. if you only type in positiv numbers minimum will stay at 0 but won't be the real minimum. To solve this case you should look into lists or initialize both variables to some values that uniquely identifies an invalid initial value that won't leak into your calculation (I suggest None). On the first iteration set both minimum and maximum to the first entered value.
After modfifications: You are comparing strings since raw_input returns strings, not numbers. You have to convert those strings into integer values using int, for example int(raw_input( ... )). Additionally you had a badly indented break of which I fixed the indent.
Other idea: Since you're not allowed to use min and max you might just use
tmp=sorted([int(raw_input('Number: ')) for x in xrange(number)])
minimum, maximum = tmp[0], tmp[-1]
but I guess this defeats your assignment :)
The solution that requires the least treatment of special values, would be to initialize both variables to +/- infinity.
minimum=float("-inf")
maximum=float("inf")
Related
So, I wrote a code to find if a number is PRIME or NOT...
I wrote it in 2 different ways, they are almost same but I just had a doubt. So here it is:
1st code:
num = int(input("Enter the number: "))
lim = num//2 + 1
for i in range(2,lim):
if num % i == 0:
print("Prime!")
break
else:
print("Not Prime!")
2nd Code:
num = int(input("Enter the number: "))
for i in range(2,num):
if num % i == 0:
print("Prime!")
break
else:
print("Not Prime!")
The 1st code takes the input(num) and according to the input sets a limit(which is the half number + 1)
and then checks if the num is divisible by all the numbers in range (2 to lim)
The second one is same but instead of setting a limit it just checks all numbers lower than the input, which means it has to do a little more work...
Now both of these are almost same, the only difference is I saved a line in 2nd one and output efficiency is also better!
Which code would you want me to prefer/
also if this code has any problems, pointing them out would be helpful!
Thanks :)
Explanation
The most important piece of iteration, namely determining whether a number is prime or not, is to keep track of it. Without this process and in the OP's program, a variable is not used to handle this, meaning that he checks whether a number is or isn't prime every single time and concludes at that point. He also uses an else statement which is syntactically incorrect.
To prevent this, we can use a variable to keep track of this. Let's call it isprime. We need to assume that a number will always be a prime unless otherwise said. This can be achieved by setting isprime to default be True, and setting it to be False when we conclude that it is not a prime, because is has a divisor. Finally, we can check this variable at the end and determine whether that number is a prime or not, because it would be set to False if not, or left as True if it is.
Another observation made is that the limit for determining primes can be reduced down to sqrt(n). This is because we do not need to find every factor if it exists, just its lowest corresponding factor. Let's look at an example:
Factors of 24: 2, 3, 4, 6, 8, 12
We can stop checking for the factors right here:
2, 3, 4 | 6, 8, 12, 24
This is because if a number has a factor (such as greater than the square root), it will have a corresponding factor less than the square root. As a result, we can set our limit to be sqrt(n), just for peace of mind + a time complexity of O(sqrt(n)) v. O(n).
As an extra note, sqrt is not inbuilt into Python. You will have to import it from the math library using:
from math import sqrt
Final Code
# Setup
num = int(input("Enter the number: "))
lim = sqrt(num)
isprime = True
# Loop & check
for i in range(2,lim):
if num % i == 0:
isprime = False
break
# Results
if isprime:
print("Prime!")
else:
print("Not prime!")
The logic of the solution is wrong. You gave to switch the "Prime" and "Not Prime" tags. Like follows;
num = int(input("Enter the number: "))
lim = num//2 + 1
for i in range(2,lim):
if num % i == 0:
print("Not Prime!")
break
else:
print("Prime!")
The solution 1 is more efficient because you do not need to do extra
computation to check num//2 + 1. So it is preferable.
Let's assume you want to guess a certain number(x) within a big range in Python.
A simple external validation function, which you can call as many times as needed, will give you hints:
If the number being tested is equal to or higher than the lowest valid number, it will, in both cases, return True (you may not know explicitly if the number being tested is too high).
Else (if the number is too low) it will return False.
What would be the most efficient way to determine the smallest possible valid number? Is there a non-linear approach?
I don't know about most efficient, but here is a quite efficient algorithm. It first searches the order of magnitude by taking successive powers of 2. Then it uses dichotomy to narrow down the actual number:
num = 123
lowest = 0
guess = 1
check = lambda : guess >= num
i=0
# find order of magnitude
while not check():
i+=1
#print(guess)
lowest = guess
guess = guess*2
# find number
highest = guess
while lowest != highest-1:
i+=1
guess = (highest+lowest)//2
#print(lowest, guess, highest)
if check():
highest = guess
else:
lowest = guess
guess = highest
print(f'found {guess} in {i} steps')
Example with 123: found 123 in 13 steps
Example with 123456789: found 123456789 in 53 steps
NB. You can uncomment the print to see the intermediate steps
def validation(number, answer):
if answer > number:
return True
return False
The number parameter is the number you are trying to guess.
First baby steps into Python and I'm stuck. I want to print the absolute value of an integer that is input by the user. If the integer that is input is a negative value, I want it to return a positive value. I'm converting the string to an integer fine, I'm storing the input 'number' fine, but if I input a negative number it's not doing the eval of the if statement and converting to a positive number by * -1 as you see below. I'm at a loss, should I be defining another variable somewhere here?
number = int(input('Please enter a number: '))
if number <= 0:
number = number * -1
I performed the tests on my machine and the operation went correctly. Is it returning an error for you?
As a suggestion, you can also use the abs() function instead of multiplying by -1 to return the absolute value of a number.
Example :
abs(-5) ---> 5
abs(5) ---> 5
try this:
num = int(input("Please enter a number:"))
if num <= 0:
num = abs(num)
Python has a lot of built-in functions that help do simple tasks like this.
The abs() function returns the absolute value of any float/int/etc. you put into it.
You can also do this all in one line if you wish, you would use the same abs() function. This time around it can be in a try-except block which will handle any bad input like "18asdfnsjkdf" for example.
try:
num = abs(int(input("Enter a number:")))
except ValueError:
pass
Your code works, add a print statement and be careful of indentation issues:
number = int(input('Please enter a number: '))
if number <= 0:
number = number * -1
print(number)
Output is:
Please enter a number: -5
5
I tackled a beginners' exercise:
"asks the user for a number and then prints out a list of all the divisors of that number."
NB - I reviewed similar questions in this forum but decided to post the following as they didn't address
my needs.
The workflow I established is:
input an integer number, say x
add a variable which value is x/2, say y
declare a divisors list
if the x is greater than 4
iterate between 2 and y+1
if the remainder is zero
append it the the divisors list
if divisors list is empty or if the input number is smaller than 4
return: this is a primary number.
else, return divisors list
I ended up with the following solution. It does the job, but isn't good enough, as it has the following issues:
What is the python's input number limit? Currently, I have no limit which is wrong as it beyond the computational capacities of any computer.
I suspect my else statement isn't tidy enough. It can be shorter... but how?
If the number is lower than 4, the script returns twice the message "the number you entered is a primary number". I could fix it with an ad-hoc solution - but it should be solved through an algorithm not in a manual manner (...at least if I try to learn coding).
I ended up iterating in range of 2 and y+2 rather y+1 as I thought. I solved it manually but I don't understand why it isn't y+1.
num = int(input("Please select a number between: "))
y = num/2
if not y==0:
y=int(y-0.5)
list_range = list(range(2,y+2))
divisors_list = []
if num < 4:
print("The number you entered is a primary number")
else:
for i in list_range:
if num%i ==0:
divisors_list.append(i)
if not divisors_list:
print("The number you entered is a primary number")
else:
print(divisors_list)
Thanks for your consideration.
My task:
Write a program that prompts for a list of numbers and at the end prints out both the maximum and minimum of the numbers. (and not suppose to use the min and max function)
eg. if i enter 4, 5, 7, done, it should print maximum as 7 and mininum as 4.
Max = None
Min = None
while True:
num = raw_input("Enter a number: ")
if num == "done":
break
try:
int(num)
except:
print "Invalid input"
continue
int(num)
if Max is None or num > Max :
maximum = num
if Min is None or num < Min :
minimum = num
print maximum, minimum
Number used: 4, 5, 7, done
Results: It prints 7 and 7 for both maximum and minimum
You are never setting Min and Max after their initialisation. At each pass through the loop, both are None, so you set maximum and minimum to the newly entered number.
To fix this, either change Max to maximum and Min to minimum, or the opposite: maximum to Max and minimum to Min.
You're also throwing away the result of int(num), so your num variable is always a string. This means the algorithm is comparing strings and not the numbers. It won't break, per se, but it might not give you the results you expect (e.g. given 3 and 20 as inputs, your code will say that 20 is smaller than 3)
You test Min and Max, but set and print minimum and maximum.
Also, as TigerhawkT3 notes, while it's legal to work with strings, you probably meant to test with integers; int(num) throws away the result (it doesn't change num in place), you probably want num = int(num).
int(num) casts num to an integer, then throws it away. You need to save a reference to it.
num = int(num)