How do I display the max function i created in python - python

I have to get userinputs of ints and store them in a array, and print the max number in the list. But I had to create my own max function. Im not sure what steps to take to implement it into my code.
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)

The below code does exactly what you want.
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()

python support built-in max function
max([1,2,3]) # return 3
and Your code is totally wrong.
if you want to input array of integers, getInt may be like this.
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
and main code will be
array = getInt()
max_value = max(array)
print (max_value)
if you want your own max function, it can be
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val

Here is a fixed version of your maxNum function:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
Let's also fix your getInt function:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
Finally, your "main" function needs the following fix:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum

Related

Multiples of 10 in a list

I am currently doing an assignment in my intro level CS class and just need a smidge of help.
They are asking me to write a program that reads a list of integers and determines if it has;
multiples of 10
no multiples of 10
mixed values.
It currently correctly outputs everything but mixed values. This is what I have:
n = int(input())
my_list =[]
for i in range(n):
num = int(input())
my_list.append(num)
def is_list_mult10(my_list):
mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 0:
mult10 = False
return mult10
def is_list_no_mult10(my_list):
no_mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 1:
no_mult10 = False
return no_mult10
if is_list_no_mult10(my_list) == True:
print("no multiples of 10")
elif is_list_mult10(my_list) == True:
print("all multiples of 10")
else:
print("mixed values")
def check_multiplier(my_list):
is_10_multiplier = []
for i in my_list:
if i % 10 == 0:
is_10_multiplier.append(True)
else:
is_10_multiplier.append(False)
if sum(is_10_multiplier) == len(my_list):
print("all multiples of 10")
elif sum(is_10_multiplier) == 0:
print("no multiples of 10")
else: print("mixed values")
# tests
mixed = [1, 20, 34, -10]
check_multiplier(mixed)
no_10 = [13, 22, 101, -5]
check_multiplier(no_10)
only_10 = [20, 140, 30, -50]
check_multiplier(only_10)
Function check_multiplier indexing all elements from my_list and saves booleans into is_10_multiplier. Then checks the sum of is_10_multiplier, if all items are True then sum is equal length of passed list, if all are False then sum is 0.
As mentioned in the comments, you have a couple of errors in your code (the return statements are inside the for loop).
Also, the logic seems a little too complicated :) No need to have 2 separate functions, you can try:
n = int(input('How many numbers?: '))
my_list =[]
for i in range(n):
num = int(input(f'Insert element {i}: '))
my_list.append(num)
def how_may_mult10(my_list):
# counting how many multiples of 10 you have in your list
number_of_m10 = 0
for num in my_list:
if num % 10 == 0:
number_of_m10 += 1
return number_of_m10
number_of_m10 = how_may_mult10(my_list)
if number_of_m10 == len(my_list):
print('All multiples of 10')
elif number_of_m10 == 0:
print('No multiples of 10')
else:
print('Mixed values')
I see you have done some logical as well as syntactic error, as mentioned in the comments also.
Below is your modified code :
n = int(input())
my_list =[]
for i in range(n):
num = int(input())
my_list.append(num)
def is_list_mult10(my_list):
mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 != 0:
mult10 = False
return mult10 #changed here
def is_list_no_mult10(my_list):
no_mult10 = True
for i in range(len(my_list)):
if my_list[i] % 10 == 0: #changed here
no_mult10 = False
return no_mult10 #changed here
if is_list_no_mult10(my_list) == True:
print("no multiples of 10")
elif is_list_mult10(my_list) == True:
print("all multiples of 10")
else:
print("mixed values")
It successfully prints the correct statement. However I'll suggest you to try to optimise e your program.

I want my prime or not program to return True and and print "True" but it's returning as None

def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break
else:
return "True"
else:
return "False"
x = int(input("Enter number"))
c = acc_p(x)
print(c)
Output:
Enter number33
None -> (I want this to be 'True')
Your code reaches no return statement for the break case. You can return from there though:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
return "False"
else:
return "True"
else:
return "False"
This can be simplified as you are returning from every if-block:
def acc_p(num):
if num <= 1:
return "False"
for i in range (2, int(num/2)+1):
if num % i == 0:
return "False"
return "True"
Ultimately you would probably want to return bool values. And with the short-circuiting pattern in your loop, you can use any:
def acc_p(num):
if num <= 1:
return False
return not any(num % i == 0 for i in range (2, int(num/2)+1))
It returns None when the for loop breaks, meaning the else statement will never be met:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break # If it breaks here...
else:
return "True" # This will never be met
else:
return "False" # And of course this one will never be met
x = int(input("Enter number"))
c = acc_p(x)
print(c)
What you'll want to do is return another value under the inner else statement:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break
else:
return "True"
return "False"
else:
return "False"
x = int(input("Enter number"))
c = acc_p(x)
print(c)
Test run:
Enter number7
True
Again:
Enter number33
False
(Note that 33 is not a prime number.)

Combine the 2 for loops

def getList(num):
result = []
while num>0:
remain=num%10
if remain >0:
result.append(remain)
elif remain ==0:
result.append(float('inf'))
num /= 10
return result
not_ans = []
for i in range(left, right+1):
for num in getList(i):
if i%num != 0:
not_ans.append(i)
ans = []
for i in range(left, right+1):
if i not in not_ans:
ans.append(i)
return ans
I have always been struggling with how I should write the code and append the result, when all the conditions should be met in for loop. I can only do it with a negative list. Can you guys help me with this? Thank you!
why don't you just append the anses in an else block:
def main():
not_ans = []
ans = []
for i in range(left, right+1):
for num in getList(i):
if i%num != 0:
not_ans.append(i)
else:
ans.append(i)
return ans

My program for getting the average doesn't quite work

def opdracht3()
a = True
result = 0
waslijst = []
while a:
n = input("Enter a number: ")
if n == "stop":
a = False
else:
waslijst += n
for nummer in waslijst:
result += int(nummer)
eind = result / len(waslijst)
print(eind)
opdracht3()
I want to get the average of the list that is being created, but when I add numbers like 11, the len(waslijst) gets set to 2 instead of 1. Is there another way to get the average, or am I using the len function wrong?
You need use .append method to store all elements in a list.
def opdracht3():
a = True
result = 0
waslijst = []
while a:
n = input("Enter a number: ")
if n == "stop":
a = False
else:
waslijst.append(n)
for nummer in waslijst:
result += int(nummer)
eind = result / len(waslijst)
print(eind)
opdracht3()

None output when I run my code

I run this code:
def fact(i):
j = 1
while i >= 1:
j = i * j
i -= 1
i = input("input the number: ")
print (fact(i))
and see this output:
input the number: 6
None
Why is my output None? What is wrong?
You are printing the result of a function. In order for a function to return result, you must use the return statement. If you don't return anything, then the the function will automaticaly return None. I suspect you want your function to return j so you need to add return j to the end of the function for it to work.
That should work:
def fact(i):
j = 1
while i >= 1:
j = i * j
i -= 1
return j
i = input("input the number: ")
print (fact(i))

Categories

Resources