Maximum, minimum and total numbers - python

Maximum, minimum and total numbers using python. For example:
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
Here is my code. I need some help with this.
def maxmin():
minimum = None
maximum = None
while (num != -10):
num = input('Please enter a number, or -10 to stop: ' )
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)

def maxmintotal():
num = 0
numbers = []
while True:
num = int(input('Please enter a number, or -10 to stop: ' ))
if num == -10:
break
numbers.append(num)
print('Numbers:', len(numbers))
print('Maximum:', max(numbers))
print('Minumum:', min(numbers))

I would do this:
def maxmin():
minimum = None
maximum = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()
See, you're not really conditioning your while loop aroud num != -10 since you check for that within the loop and break out of it. So, there will never be a time when num=-10 at the beginning of the loop, make sense?
So, you just loop forever (The while True) until someone inputs a -10

You have to define num before you use it in the while, also your nested if should be out of the other if:
def maxmin():
minimum = None
maximum = None
num = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maximum: ", maximum)
print ("Minimum: ", minimum)
maxmin()

This function should give you the output that you want:
def maxmin():
minimum, maximum, total = None, None, 0
while(True):
number = input('Please enter a number, or -10 to stop: ')
num = int(number)
if num == -10:
break
if total == 0:
minimum, maximum, total = num, num, 1
continue
total += 1
if num < minimum:
minimum = num
elif num > maximum:
maximum = num
print("Output : total ={}, minimum={}, maximum ={}".format(total, minimum, maximum))

Related

How can I display the first 25 prime numbers?

How can I display the first 25 integer prime numbers in the given interval? I can't find a way to limit it to 25 integer prime numbers.
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
for num in range (minimum, maximum + 1):
if num > 1:
for i in range (2, num):
if (num % i) == 0:
break
else:
print(num)
you have to use a counter to store how many prime numbers you've found.
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
counter = 0
for num in range (minimum, maximum + 1):
if counter == 25: break
if num > 3:
for i in range (2, int(num/2)): # for optimization
if (num % i) == 0:
break
else:
counter += 1
print(counter,num)
else:
counter += 1
print(counter,num)
here is the more optimized code with the hints in the comments:
import math
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
counter = 0
for num in range (minimum, maximum + 1):
if counter == 25: break
if num > 3:
if (num % 2) != 0:
for i in range (3, math.ceil(math.sqrt(num)), 2):
if (num % i) == 0:
break
else:
counter += 1
print(counter,num)
else:
counter += 1
print(counter,num)
If nothing else, you could use a variable to keep track of how many you've printed and break from the outer loop when that hits 25.
Here's an example, added to your code.
minimum = 1000000000
maximum = 9999999999
printed = 0
print ("The first 25 10-digit prime numbers are:")
for num in range (minimum, maximum + 1):
if num > 1:
for i in range (2, num):
if (num % i) == 0:
break
else:
print(num)
printed+= 1
if printed >= 25:
break
You can try this.
from sympy import isprime
i=1
count = 0
while count < 25:
if isprime(i):
print(i)
count += 1
i += 1

python how many moves to get to zero

I have tried to do this task in a lot of ways but none of it works.
The user enters a natural number n. In one move, its largest digit is subtracted from the number. In the next move, its highest digit is subtracted from the result, etc. The program needs to determine and print how many moves it takes to get to zero. For example, number 24 requires five moves (24 → 20 → 18 → 10 → 9 → 0).
Here is what I've done so far. I know how to find the largest digit but how can I put this into a loop to substract largest digit from result ?
num = int(input("Enter natural number "))
if num <= 0:
print("That is not a natural number")
else:
max = 0
while num > 0:
digit = num % 10
if max < digit:
max = digit
num = num // 10
print("Largest Digit is : ", max)
You could try with a string and max:
num = int(input("Enter natural number "))
if num <= 0:
print("That is not a natural number")
else:
ntimes = 0
while num > 0:
num -= int(max(str(num)))
ntimes += 1
print(ntimes)
Output:
5
In case you have the requirement of not casting the number into a string to obtain its digits you can use divmod:
def get_natural_num_input(prompt: str) -> int:
num = -1
while True:
try:
num = int(input(prompt))
if num <= 0:
print("Error: Not a natural number, try again...")
else:
break
except ValueError:
print("Error: Enter a integer, try again...")
return num
def get_digits(num: int) -> list[int]:
digits = []
while num > 0:
num, digit = divmod(num, 10)
digits.append(digit)
return digits
def moves_to_get_zero(num: int) -> int:
moves = 0
while num != 0:
num -= max(get_digits(num))
moves += 1
return moves
num = get_natural_num_input("Enter a natural number: ")
print(f'moves_to_get_zero({num}) = {moves_to_get_zero(num)}')
Example Usage:
Enter a natural number: 24
moves_to_get_zero(24) = 5

Counter in for loop always prints 0

I need to check if a number is Lychrel number and if not to print the number of times the loop did until it got to the palindrome, for some reason it always print 0
num = input('please enter your number ')
num = int(num)
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
update: thanks to Vova the code is now working.
fixed code:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
It will print 0 each time when you type 1 numeric number(0..9)
When you type more than 1 numeric not mirror number for example 2,3,4 etc(10,234 etc), it will print 1
Moreover it will never print True, coz you exit() it in if statement
Try to input 23, it will print 1:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')

Python3 ParseError

I was trying to do a simple task, a script that figures out which of numbers inputed were largest of smallest. Here is the code:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try :
num = int(num)
except :
print('Invalid input')
continue
if smallest is None :
smallest = num
elif:
smallest > num
smallest = num
if largest is None :
largest = num
elif :
largest < num
largest = num
print("Maximum", largest)
When I am trying to run the code, it tells me 'ParseError: bad input on line 15'
Could anybody help me?
The correct syntax for elif is the same as for normal if statements:
Instead of:
elif:
smallest > num
smallest = num
Do:
elif smallest > num:
smallest = num
Same for your other elif further down.

How do i print smaller value?

I am very new to python, I write below few lines of code but not able to print smallest number from the input.
largest = 0
smallest = 0
while True:
num = raw_input("Enter a number:")
if num == "done" : break
try:
num = int(num)
except:
print "invalid"
continue
if num is smallest:
smallest = num
if num > largest:
largest = num
print "Minimum", smallest, "Maximum", largest
below is my output, it does print correct largest value (whatever i input) but smallest is always zero.
Enter a number:34
Enter a number:12000
Enter a number:dds
invalid
Enter a number:done
Minimum 0 Maximum 12000=====> see minimum is "0" should be 34?
That's the expected behaviour. In fact, your second statement reads:
smallest = 0
0 is less than 34, so smallest won't be updated.
A possible solution is initializing smallest and largest from the first element read:
largest = None
smallest = None
while True:
num = raw_input("Enter a number:")
if num == "done" : break
try:
num = int(num)
except:
print "invalid"
continue
if smallest is None: # or largest is None, it's the same
smallest = num
largest = num
if num < smallest:
smallest = num
if num > largest:
largest = num
print "Minimum", smallest, "Maximum", largest
Besides, you have what appears to be a typo or a misconception about the operator is. This:
if num is smallest:
smallest = num
Should be:
if num < smallest:
smallest = num

Categories