Function to find the max of 3 numbers in Python - python

I'm trying to write a function that takes the inputs and puts them into a list, then sorts the list, and finds the greatest number. I keep getting errors and I'm not really sure what's wrong. I'll post the current code that I have typed up already. Any help or advice would be greatly appreciated, thank you.
Code:
def findMax3():
y = list(lst)
y.sort(lst)
y[0] == y[-1]
lst = int(input())
print(findMax3())

You need to pass in a variable - lst maybe?
You need to return value if you want your main to print something.
You need a constant input format for integer arrays, I will suggest 1 2 3 4 5 (space separated), that can be reversed to list using map(int, input().split())
Use the built-in max.
Do you want to limit yourself to 3 number arrays? if yes, use assertion.
That should be enough:
def findMax3(lst):
assert len(lst) == 3
lst.sort()
return max(lst)
lst = map(int, input().split())
print(findMax3(lst))

This is the corrected code:
def findMax3(lst):
y = lst[:]
y.sort()
return y[-1]
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I'd say findMax() would be a better name as this could find the maximum of lists of any length.
Bear in mind the following does the same thing:
lst = [int(x) for x in input().split()]
print(max(lst))

Put the numbers in a list, then use max() function to get the maximum value in a list, like this:
#create an empty numbers list
lst=[]
#loop for getting input numbers
for i in range(1,4):
try:
#here we get the input number
my_new_number=int(raw_input("Please input the number "+str(i)+"/3 :\n"))
except:
#in case of it is not a number raise an alert
print "not regular integer number"
#here we check that number not exist
if my_new_number not in lst:
#add the current input number to the list
lst.append(my_new_number)
else:
print "the number",my_new_number,"already exist in this list"
#show the maximum number of the list
print "The maximum number is",max(lst)

You might be interested in typing your list items one by one instead of using split() function to split your input. Also, to retrieve your list max, you have already a built-in max() function that you can use:
>>> num_list = []
>>>
>>> for i in range(3):
... num = input("Enter number {}: ".format(i + 1))
... num_list.append(int(num))
...
Enter number 1: 3
Enter number 2: 6
Enter number 3: 2
>>>
>>> max_num = max(num_list)
>>> print(max_num)
6

First off, Ebe Isaac gave a good explanation and you should look at his solution and understand why it works.
There's a few issues with your code.
lst = int(input())
print(findMax3())
You're inputting a list of numbers that need to be separated by some non-numeric character, so you cannot use int() on your input value.
lst = [int(x) for x in input().split()]
should give you what you want (with default separator being blank space). To learn more about this format, see list comprehensions.
Next, you call findMax3() but this function does not return a value so it will not have anything to print (see below). Additionally, it would be better to send it your list as an argument, this will save you from another line copying it later (see below).
lst = input().split()
print(findMax3(lst))
Now for your function:
def findMax3():
y = list(lst)
You should probably send an argument (the inputted list) to the function. This argument can be renamed whatever you put in the parentheses after the name of the function. You are using y here so we can rewrite it as:
def findMax3(y):
and delete the y = list(lst) line.
y.sort(lst)
When using a method or function, it's a good idea to look up the documentation to identify what arguments it takes. You'll see that sort can take two arguments (key and reverse) neither are needed here so we can fix this line by changing it to:
y.sort()
The next line:
y[0] == y[-1]
is a Boolean expression and returns either True or False if the first element of the sorted list (y[0]) is equal to the last element of the sorted list (y[-1]). To be honest, I'm not really sure what you were trying to do here. Since the function is designed to find the max value of the list, it needs to return that value so we need to use return(). The max value will be the last of the list so you can do:
return(y[-1])
So if you want to keep the flow of your original code, it can work by changing it to:
def findMax3(y):
y.sort()
return(y[-1])
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I hope this helps. Best of luck.

As many have mentioned, you need to let your function know what list to find the max of. To do that, you need to put the name of the list in the parameter list of the function i.e. findMax3(lst).
Your function will still not work because you are not returning anything from it. You need to use the return keyword followed by what to return in order to have the function give you a response. For example, return 1 will return the value of 1 to anyone who called this function. Using that example, you need to decide what to return to the caller.
My version of findMax3 without any other function calls:
def findMax3(*args):
max3 = args[0]
for n in args[1:3]:
if n > max3:
max3 = n
return max3
This is pretty close to what the built in max function will do given those same 3 inputs

If you already have a list then you can simply use the max function to get the highest number among 3 numbers in the list.
lst = [5, 2, 9]
print(max(lst))
# output
9
Or I assume you have three different numbers as input and then you can pass them to your desired method to get the highest number.
# function to get max among 3 integers
find_max(x, y, z):
return max([x, y, z])
# take input
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
num3 = int(input("enter num3: "))
# call your function
print(find_max(num1, num2, num3))

If we do not want to use the built in function for solving the problem we could always follow the below simple approach.
Using max() to find maximum of numbers is already shown in above few solutions.
Posting a sample solution without use of max()
num1=51
num2=6
num3=72
def find_max(num1,num2,num3):
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
return largest
print(find_max(num1,num2,num3))

Related

Longest sequence of equal numbers in python

I tried to generate the longest sequence of equal numbers in python, but it doesn't work
def lista_egale(lst1 = input("numbers go here ")):
l = 0
lst1 = []
maxi = -9999
prev_one = None
lmax = -9999
for current in lst1:
if prev_one == current:
l += 1
else:
l = 1
if l > lmax:
lmax = l
maxi = current
prev_one = current
print("longest sequence is ", lmax, " and ", maxi)
lista_egale()
Input:
1 2 2 2 2 3 4 5 6 2 2 2
Expected Output:
longest sequence is 4 and 2
I was going to write up the same concern about your default argument, but that would at least work correctly the first time it is called. This function does not. Everyone jumped on that common problem, and failed to notice the next line. Let's look another look at this abridged version of your code:
irrelevant = input("numbers go here ")
def lista_egale(lst1 = irrelevant):
# while it is true that your default argument is bad,
# that doesn't matter because of this next line:
lst1 = []
for current in lst1:
# unreachable code
pass
To clarify, since your reply indicates this is not clear enough, it doesn't matter what value was passed in to lst1 if you immediately overwrite it with an empty list.
(for others reading this:) Separating out what I labeled "irrelevant" is not quite identical, but I'm trying to point out that the input was overwritten.
I don't think this function should take user input or have a default argument at all. Let it be a function with one job, and just pass it the data to work on. User input can be collected elsewhere.
Based on Barmar's note, and the principle of using only unmutable default values, your code should look something more like this:
def lista_egale(inp1 = None):
if not inp1:
inp1 = input("numbers go here ")
# optionally do some error checking for nonnumerical characters here
lst1 = [int(i) for i in inp1.split(" ")]
# rest of your code here
lista_egale()
Basically, input returns a string value, and you need to convert it into a list of integers first before you start working on it.
You can swap out the list comprehension for map(int, inp1.split(" ")) as it will do the same (but you can't iterate through a map more than once unless you wrap it in a list() function first).
Secondly, avoid setting mutable default arguments as (in short) can lead to weird results when rerunning the same function multiple times.

How To Modify This Code In python to return/print all positive numbers not just one

The positive_numbers function should return a list containing numbers that are non-negative (>=0).
However, currently, it returns only the [3] instead of a list of values.
I tried different ways to make this work I'm currently a beginner in python and I don't have anyone to ask that's why I'm sorry if this is too basic for you just want to learn and see my mistake
def positive_numbers(numbers):
for number in numbers:
result = []
result = result + [number]
if number < 0:
continue
return result
Expected: The function should return a list of numbers
Actual: returns list with the only value being 3
Error: The call positive_numbers([1, 2, 3]) should return [1, 2, 3], but it returned [3]
You reset the list each iteration of the loop because of result = [].
Try this:
def positive_numbers(numbers):
result = []
for number in numbers:
if number > 0:
result = result + [number]
return result
Also, debugging would make this very clear. Try to debug your code to get a better understanding of it.
You have to declare result outside of your for loop.
def positive_numbers(numbers):
result = []
for number in numbers:
if number < 0:
continue
result.append(number)
return result
As already stated, you are setting results no a new empty string at every iteration of your for loop. Also, the if statement does not make any change, since by the time is evaluated, the new number is appended to the result.
So the minimal working change is:
def positive_numbers(numbers):
result = []
for number in numbers:
if number 0:
continue
result = result + [number]
return result
Besides, note that you could use a list comprehension for that:
positive_numbers = [number for number in numbers if number >= 0]
Or using filter:
positive_numbers = list(filter(lambda num: num>=0, numbers))
Note that in the latter case, if you don't need your output to be a list but an iterable, you can remove the list(...) part
You have all of the pieces, just not necessarily in the right order. Here is an amended version:
def positive_numbers(numbers):
result = []
for number in numbers:
if number < 0:
continue
result = result + [number]
return result
With result = [] inside the for loop as you had it, you were emptying the result on each iteration. Then you were unconditionally adding the number to the list instead of checking if it is negative first. In this amended first, the loop skips to the next number if the current number is not non-negative.

Test the length of elements in a list

def lengthgood(x):
for i in x:
if len(i)<13
return i
else:
pass
def makeproperlist(x):
return x.split(',')
attendancelist=makeproperlist(input("attendee list:"))
final_list=list(filter(lengthgood,attendancelist))
for i in finallist:
print (i)
I want to write a programme of which I create a list in which only elements shorter than 14 can be a part of.
This is my code, but it keeps returning all the elements I put in, even if some of them are longer than 14?
I tried to print the len(i) and it says that it is 1 for every element in the list?
How do I solve this?
You shouldn't put a return within a loop; it'll only return the first element that matches your condition.
You also shouldn't be looping within your filter function, because you're actually looping over characters of strings, which are all length 1.
Therefore, the first character is always returning a truthy value, giving you back the initial input after filtering
You only need to check the input length, and filter functions should ideally return appropriate boolean conditions rather than truthy values (in your case return i is returning a non-empty string)
def lengthgood(x):
return len(x)<13
If you don't need to use filter(), you can write a list comprehension
final_list=[a if len(a) < 13 for a in attendancelist]
may be like that
flst = []
def croper(lst):
for i in lst:
flst.append(i) if len(i) < 13 else 0
lst = input("attendee list:").split(',')
croper(lst)
print(flst)
or shorter
def croper(lst):
return [i for i in lst if len(i) < 13]
lst = input("attendee list:").split(',')
print(croper(lst))
You want to create a list but you not define it anywhere in program simply done it with simply one function makeproperlist(x).
Try this code bro this will help you.
attendancelist=[]
while (True):
ch=input("Enter c for continue and e for exit : ")
if (ch=='c'):
def makeproperlist(x):
if x<=13:
attendancelist.append(x)
else:
print("Enter number which is <= to 13.")
makeproperlist(int(input("attendee list:")))
elif (ch=='e'):
break;
print("Your attendece list : ",attendancelist)

Iterate through a newly generated list: Python

I am trying to reuse the newly created list from the Fibonacci sequence, I want to be able to use the answer to iterate through and call just the even numbers.
I can do this on it's own but have no idea how to use the results of my current code.
Any help greatly appreciated. Thank You.
FibStart = int(raw_input('Enter a start number : '))
FibStop = int(raw_input('Enter a stop number : '))
def fib(n):
if n < 2:
return n
else:
return fib(n-2) + fib(n-1)
print map(fib, range(FibStart, FibStop))
# when called will return [0,1,1,2,3,5,8,13,21,34]
Just translate your English text into code:
I want to be able to use the answer
So store it in a variable:
answer = map(fib, range(FibStart, FibStop))
… to iterate through
So iterate through it:
for value in answer:
… and call just the even numbers.
So check if they're even:
if value % 2 == 0:
Or, if you want to make a new list of just the even values to use repeatedly, you can use a list comprehension:
evens = [value for value in answer if value % 2 == 0]
for even in evens:

Writing a custom sum function that sums a list of numbers

I am new to Python and need some help writing a function that takes a list as an argument.
I want a user to be able to enter a list of numbers (e.g., [1,2,3,4,5]), and then have my program sum the elements of the list. However, I want to sum the elements using a for loop, not just by using the built in sum function.
My problem is that I don't know how to tell the interpreter that the user is entering a list. When I use this code:
def sum(list):
It doesn't work because the interpreter wants just ONE element that is taken from sum, but I want to enter a list, not just one element. I tried using list.append(..), but couldn't get that to work the way I want.
Thanks in anticipation!
EDIT: I am looking for something like this (thanks, "irrenhaus"):
def listsum(list):
ret=0
for i in list:
ret += i
return ret
# The test case:
print listsum([2,3,4]) # Should output 9.
I'm not sure how you're building your "user entered list." Are you using a loop? Is it a pure input? Are you reading from JSON or pickle? That's the big unknown.
Let's say you're trying to get them to enter comma-separated values, just for the sake of having an answer.
# ASSUMING PYTHON3
user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number
def sum(lst):
accumulator = 0
for element in lst:
accumulator += element
return accumulator
The top three lines are kind of ugly. You can combine them:
user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))
But that's kind of ugly too. How about:
raw_in = input("Enter a list of numbers, comma-separated\n>> ").split(',')
try:
processed_in = map(float, raw_in)
# if you specifically need this as a list, you'll have to do `list(map(...))`
# but map objects are iterable so...
except ValueError:
# not all values were numbers, so handle it
The for loop in Python is exceptionally easy to use. For your application, something like this works:
def listsum(list):
ret=0
for i in list:
ret+=i
return ret
# the test case:
print listsum([2,3,4])
# will then output 9
Edit: Aye, I am slow. The other answer is probably way more helpful. ;)
This will work for python 3.x, It is similar to the Adam Smith solution
list_user = str(input("Please add the list you want to sum of format [1,2,3,4,5]:\t"))
total = 0
list_user = list_user.split() #Get each element of the input
for value in list_user:
try:
value = int(value) #Check if it is number
except:
continue
total += value
print(total)
You can even write a function that can sum elements in nested list within a list. For example it can sum [1, 2, [1, 2, [1, 2]]]
def my_sum(args):
sum = 0
for arg in args:
if isinstance(arg, (list, tuple)):
sum += my_sum(arg)
elif isinstance(arg, int):
sum += arg
else:
raise TypeError("unsupported object of type: {}".format(type(arg)))
return sum
for my_sum([1, 2, [1, 2, [1, 2]]])
the output will be 9.
If you used standard buildin function sum for this task it would raise an TypeError.
This is a somewhat slow version but it works wonders
# option 1
def sumP(x):
total = 0
for i in range(0,len(x)):
total = total + x[i]
return(total)
# option 2
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
sumP([2,3,4]),listsum([2,3,4])
This should work nicely
user_input = input("Enter a list of numbers separated by a comma")
user_list = user_input.split(",")
print ("The list of numbers entered by user:" user_list)
ds = 0
for i in user_list:
ds += int(i)
print("sum = ", ds)
}
Using accumulator function which initializes accumulator variable(runTotal) with a value of 0:
def sumTo(n):
runTotal=0
for i in range(n+1):
runTotal=runTotal+i
return runTotal
print sumTo(15)
#outputs 120
If you are using Python 3.0.1 or above version then use below code for Summing list of numbers / integer using reduce
from functools import reduce
from operator import add
def sumList(list):
return reduce(add, list)
def oper_all(arr, oper):
sumlist=0
for x in arr:
sumlist+=x
return sumlist
Here the function addelements accept list and return sum of all elements in that list only if the parameter passed to function addelements is list and all the elements in that list are integers. Otherwise function will return message "Not a list or list does not have all the integer elements"
def addelements(l):
if all(isinstance(item,int) for item in l) and isinstance(l,list):
add=0
for j in l:
add+=j
return add
return 'Not a list or list does not have all the integer elements'
if __name__=="__main__":
l=[i for i in range(1,10)]
# l.append("A") This line will print msg "Not a list or list does not have all the integer elements"
print addelements(l)
Output:
45
import math
#get your imput and evalute for non numbers
test = (1,2,3,4)
print sum([test[i-1] for i in range(len(test))])
#prints 1 + 2 +3 + 4 -> 10
#another sum with custom function
print math.fsum([math.pow(test[i-1],i) for i in range(len(test))])
#this it will give result 33 but why?
print [(test[i-1],i) for i in range(len(test))]
#output -> [(4,0), (1, 1) , (2, 2), (3,3)]
# 4 ^ 0 + 1 ^ 1 + 2 ^ 2 + 3 ^ 3 -> 33

Categories