0

I am trying to find max and min number without using lists I know some information exist about this subject in here but mine is some different.I want numbers from the users.I am gonna continue to get the numbers until they enter -1.I could not find the solution. Here is the code:

count=1 while count != -2: number=int(input("number:")) max=number min=number if number != -1: count+=1 elif number == -1: if number > max: max = number print("max{}".format(max)) if number < min: min = number print("min{}".format(min)) break: 
4
  • Why don't you want to use a list? Commented Oct 25, 2021 at 13:48
  • Because this is the homework required of me.I need to do that with this way. Commented Oct 25, 2021 at 13:50
  • 1
    Start by not using max and min directly as they are native Python functions. Use something like cur_max and cur_min Commented Oct 25, 2021 at 13:52
  • @AdamJaamour is right. You should never uses builtin names as name. Commented Oct 25, 2021 at 13:53

1 Answer 1

2

You can try something like this. The idea is to remember only the max (or the min) value at each iteration to not use any list.

max_ = float('-inf') min_ = float('inf') while True: number=int(input("number:")) if number == -1: break else: # Without min and max function max_ = max_ if max_ > number else number min_ = min_ if min_ < number else number # max_ = max(max_, number) # min_ = min(min_, number) print(f'Max: {max_}') print(f'Min: {min_}') 

Test:

number:10 number:5 number:8 number:3 number:-1 Max: 10 Min: 3 
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your answer I know about max and min function but I can not use this functions.I should write this manually.
I updated my answer but I'm pretty sure you could have found it by yourself :)
@stck_n. Does it solve your problem? You can check this link or search for 'ternary operator' in python.
It is working.I appreciate for your answer:)
Glad to read that.