Get numbers from user, put them in a list, and find the biggest odd number - python-3.x

I'm a beginner in Python 3. I want to:
Ask for 10 numbers from the user and put them in a list
Check for the biggest odd number
The following code just put the last number in the value (number)
and I have no idea how to check for the biggest odd number:
for i in range(1,11):
number = list((input(f"please enter the {i}th number: ")))
print(number)

To create a list of numbers given by user we use a for-loop with input to ask for numbers as you almost did correctly (do not forget to cast to int):
numbers = []
for i in range(1, 11):
number = int(input(f"Enter number {i}: "))
numbers.append(number)
You can also do this with list comprehension, which will make it shorter but maybe a little harder to understand at the begining (this has exactly the same result as the previous code):
numbers = [int(input(f"Enter number {i}: ")) for i in range(1, 11)]
Now, to get the largest odd number from a list of numbers you can:
Set a variable with the minimum possible value or to None
Iterate over your list
Update the value of the variable, if a number is an odd number and larger than the one saved in your variable
Let's see this in action considering you have your list of numbers numbers.
odd_largest = 0
for number in numbers:
if number % 2 != 0 and number > odd_largest: # If number is odd and larger
odd_largest = number # update value
print(odd_largest)
What is the difference of setting odd_largest to 0 vs None? If you set it to 0 and the final value of odd_largest is 0, you wouldn't know if it was updated at all, is it a number in the list or just the original value? Imagine the case there is no odd number in the list, for example.
When using None as initial value you will be sure if it was updated. You also need to add an additional condition:
odd_largest = None
for number in numbers:
if number % 2 != 0 and (odd_largest is None or number > odd_largest): # If number is odd and larger or None
odd_largest = number
print(odd_largest)
When you put everything together you get what is needed.
numbers = [int(input(f"Enter number {i}: ")) for i in range(1, 11)]
odd_largest = None
for number in numbers:
if number % 2 != 0 and (odd_largest is None or number > odd_largest): # If number is odd and larger or None
odd_largest = number
print(odd_largest)
Here some questions arise. First: are we using the list numbers for any other actions? If the answer is yes, then our code is enough. But if this is all that is needed we can actually do better.
Find the largest odd number by comparing the numbers right after input by the user, without even creating a list. Let's check it out!
odd_largest = None
for i in range(1, 11):
number = int(input(f"Enter number {i}: "))
if number % 2 != 0 and (odd_largest is None or number > odd_largest):
odd_largest = number
print(odd_largest)
What do we gain with this? Iterating just once over the numbers instead of twice, saving memory since we are not saving all numbers input just one. Cool uh?
If you have any more questions do not hesitate. Happy coding!

my_list = []
for i in range(1, 11):
my_list.append(int(input(f"please enter the {i}th number: ")
my_list_only_odd_numbers = [n for n in my_list if n % 2]
largest_odd_number = max(my_list_only_odd_numbers)
Get a list of integers from the user, remove all numbers from the list that aren't odd and then get the largest number in that list using max()

Related

I need the code to stop after break and it should not print max(b)

Rahul was learning about numbers in list. He came across one word ground of a number.
A ground of a number is defined as the number which is just smaller or equal to the number given to you.Hence he started solving some assignments related to it. He got struck in some questions. Your task is to help him.
O(n) time complexity
O(n) Auxilary space
Input Description:
First line contains two numbers ‘n’ denoting number of integers and ‘k’ whose ground is to be check. Next line contains n space separated numbers.
Output Description:
Print the index of val.Print -1 if equal or near exqual number
Sample Input :
7 3
1 2 3 4 5 6 7
Sample Output :
2
`
n,k = 7,3
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
print(max(b))
`
I've found a solution, you can pour in if you've any different views
n,k = 7,12
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
else:
print(max(b))
From what I understand, these are the conditions to your question,
If can find number, print the number and break
If cannot find number, get the last index IF it's less than value k
Firstly, it's unsafe to manually input the length of iteration for your list, do it like this:
k = 3
a= [1,7,2,2,5,1,7]
finalindex = 0
for i, val in enumerate(a):
if val==k:
finalindex = i #+1 to index because loop will end prematurely
break
elif val>=k:
continue
finalindex = i #skip this if value not more or equal to k
print(finalindex) #this will either be the index of value found OR if not found,
#it will be the latest index which value lesser than k
Basically, you don't need to print twice. because it's mutually exclusive. Either you find the value, print the index or if you don't find it you print the latest index that is lesser than K. You don't need max() because the index only increases, and the latest index would already be your max value.
Another thing that I notice, if you use your else statement like in your answer, if you have two elements in your list that are larger than value K, you will be printing max() twice. It's redundant
else:
print(max(b))

Want to get to know how many times double 6 appeared while rolling the dice to randomly generated number of time?

I just saved the results as string and now performing the check using the loop but its not working
counter is still 0 if 66 appeared in the result.
from random import *
trial = int(randint(1, 10))
print(trial)
result = ''
for i in range(trial):
init_num = str(randint(1, 6))
result += init_num
print(result)
last_dice = 0
counter = 0
for i in range(trial):
if result[i] == 6 and last_dice == 6:
counter += 1
last_dice = 0
else:
last_dice = result[i]
print(counter)
if result[i] == 6
This condition will never be true because the value in 'result' is a string. If you change the 6 to '6' it should work.
EDIT
"how many time double 6 appeared while rolling the dice" implies the dice are being rolled in pairs. As it is, your script will count any two consecutive sixes as having been rolled together. For example if the rolls are 4,6,6,5 your script counts this as an instance of double sixes, which is not accurate if the rolls are occurring in pairs. For this reason you should generate the random 1-6 values in pairs so it is clear when sixes are actually rolled together.
You could create 'results' as a list where each item is a pair of numbers representing a roll of two dice:
results = [str(randint(1,6))+str(randint(1,6)) for i in range(randint(1, 10))]
Your 'trials' variable is only used to print the number of rolls. If each roll is for a pair of dice, the number of rolls is equal to the number of items in the above 'results' list. Printing this value doesn't require a variable, but merely the length of the list:
print(len(results))
One way to print all the roll results is as an easily readable string of comma-separated roll pair values, which can be done printing this list joined together with each item separated by a comma:
print(','.join(results))
Counting the number of double sixes rolled can be done by summing the number of times the value '66' appears in the 'results' list:
print(sum(i == '66' for i in results))
All together the script could be written as:
from random import randint
results = [str(randint(1,6))+str(randint(1,6)) for i in range(randint(1, 10))]
print(len(results))
print(','.join(results))
print(sum(i == '66' for i in results))

This is a simple Python question for list

Im trying to take in user input to get a list of numbers and then use a for loop to grab the largest value. For what I have now I can use 8237483294 but It will list each integer as its own independent value and will have its own place in the list so it would be [8,2,3,7,4,8,3,2,9,4] Which was an A+ for what I wanted. But now I want to take it to another place and take multi digit values such as [23,44332,32523,243,22,]
my code is
users_number = input("list number")
numbers = users_number
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
Use string.split().
#Get user input
# (no need for the two variables you used in your example)
numbers = input("List numbers separated by spaces").split()
#Convert to list of ints
numbers = [int(num) for num in numbers]
#Solution 1: use max()
print("Max value:", max(numbers))
#Solution 2: Iterate through list
max_val = numbers[0]
for num in numbers:
if num > max_val:
max_val = num
print(max_val)
On an additional note, I presented 2 possible methods for finding the max value. max() is a built-in that finds the maximum value in the list. There is also the iterating method, which is what you do in your code.
Here is a more user-friendly approach that asks for the numbers one by one from the user. The advantage is that you don't have to rely on your users to enter the correct syntax for a list.
numbers = []
while True:
number = input("Enter a number from your list. When finished with list, enter 'done': ")
if number == "done":
break
else:
numbers.append(int(number))
max_num = max(numbers)
print(max_num)
Simple and elegant one liner:
max(map(int, input("Enter a list: ").split()))

choose one list. choose the one whose nth element is the smallest. Python 3

I have two lists. I have to choose one. I have to choose the one with the smallest nth element. So I can choose the smallest element easy with min, but how do I back track it to the list itself. Have literally no idea how to solve this presumably easy problem.
a = [2,45,1,56]
b= [0,23,3,87]
Which list has the smallest element at position 2? The answer here is list a.
In case I wasnt clear, the program sould be able to solve this task for any pair of lists.
Here is a very simple snippet that does what you want, but you might want to check for the size of the arrays, in case the index is out of range.
def choose_smallest(a, b, i):
if len(a) >= i or len(b) >= i:
return 0 # do whatever you want here
if a[i] < b[i]:
return a
else:
return b
Also notice that both nth elements in your array can have the exact same value... In this example array b will be returned, but you can change that behaviour if needed.
EDIT
Added array length check
According to your example, here is a sample code you can try. You can change the code as per your requirement.
a = [2,45,1,56]
b = [0,23,3,87]
n= int(input('Enter element number: ')) # n starts from zero to length of list - 1
if a[n] > b[n]:
print('List b has smaller nth element')
elif a[n] < b[n]:
print('List a has smaller nth element')
else:
print('Both lists have equal nth element')

Would like to know how to find the min and max of a list Python

I have this program that calulates the avergae of grades. A teacher puts how many classes they want then how many students they want the program to run through. The program then asks them to import grades and calulates the average for them . I also want to add at the end the higest and lowest averages. Please help, thanks.
classes = int(input("Enter the number of classes:"))
for num in range(classes):
students =int(input("Enter the amount of students:"))
max1 = students
total = 0
for counter in range(max1):
number = int(input('Enter a grade:'))
total += number
while number > 100:
print('Error: Grades must be less than 100')
number = int(input('Enter a grade:'))
print('The total', total/ students)
else:
print('end')
If you want to use lists: at start, averages = [] to make an empty list, averages.append(average) to add one in each loop pass, max(averages) and min(averages) at the end.
If you don't want to use lists: max_average = float("-inf"); min_average = float("inf"), at each iteration if average > max_average: max_average = average (and equivalently for min_average).

Resources