I have a question: I don't understand why my last function isn't going through and printing anything. I tried fixing where I think I might've messed up, but I can't find it. My task is to create function 1 that checks if all the values in a list are unique or not and return true or false, and the second function is the one that generates the random integer list based on user input (function 1 helps with this). After this, I need to find the nth maximum in the list that is requested by the user, which is the part that doesn't seem to be working.
For Example:
If the list has the values 1 3 7 2 15 20 5 18 11 and the user wanted the:
1st Maximum (n = 1) -> It would return 20 (the highest number)
2nd Maximum (n = 2) -> It would return 18 (the second highest number)
3rd Maximum (n = 3) -> It would return 15 (the third highest number)
import random
#check for all unique values in list
def allunique(x):
unique_or_not= []
for item in x:
if item in unique_or_not:
return False
unique_or_not.append(item)
return True
#generate list of random numbers
def list_of_nums(start,end,number_of_values):
nums= []
#how can I let integer also be a negative value with range??
for i in range(0,number_of_values):
nums.append(random.randint(start,end))
return nums
#main function of inputs and calls list
def main():
number_of_values= int(input("Please enter the number of values you wish to generate:"))
start= int(input("Please enter the starting # of the values you wish to generate:"))
end= int(input("Please enter the ending # of the values you wish to generate:"))
myList= list_of_nums(start,end, number_of_values)
print(myList)
#find nth max
def finding_nth_max(nums):
sorted_list= nums.sorted()
nthmax= int(input("Please enter the nth maximum you would like to find: "))
print("The nth maximum is", sorted_list[-nthmax])
main()
CodePudding user response:
you must add finding_nth_max(your_list_here) function within your main function, for the output of that function to be printed. This must be added after you have called list_of_nums in your main function
CodePudding user response:
you need to call method and nums.sort()
does not return anything, it updates the list automatically
def find_nth_max(nums: list):
nums.sort()
print(f'provided list: {nums}')
nthmax= int(input("Please enter the nth maximum you would like to find: "))
print("The nth maximum is", nums[-nthmax])
find_nth_max([2, 5, 1, 8])