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()))
Related
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))
I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.
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()
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')
I want to return False if the same input is given:
first_answer = input("select square number 1: ")
second_answer = input("select square number 2: ")
third_answer = input("select square number 3: ")
if first_answer == second_answer or first_answer == third_answer or
second_answer == first_answer or second_answer == third_answer or
third_answer == first_answer or third_answer == second_answer:
print("don\'t repeat squares")
Is there an easier way?
Do you like this:
set_answers = set()
set_answers.add(input("select square number 1: "))
set_answers.add(input("select square number 2: "))
set_answers.add(input("select square number 3: "))
if len(set_answers) < 3:
print("don\'t repeat squares")
?
The TRICK: set() stores only unique elements, so adding same value again to a set doesn't change the number of its elements.
Try this.
count = 3
answers = []
for i in range(0, count):
answers[i] = input("select square number " + str(i+1) + ": "
for i in range(0, count-1):
for j in range(i+1, count):
if answers[i] == answers[j]:
print("don\'t repeat squares")
It is (almost) always easier to abstract this kind of thing by using loops and arrays (or sets, or tuples) than to program each variable by hand.
answers is a list here, and the first loop inputs the data into the array. Note that you can easily change the amount of data you want simply by modifying the initial value of count -- this will change everything else as well (including the input messages!).
The second loop is actually a nested pair of for loops in order to generate all of the (relevant) pairs of data items to compare. Note that the first loop stops one short of the last element and that the second loop starts one after whatever the value of the first loop is. This is in order to avoid incorrectly comparing an element with itself.
CLARIFICATION:
[] is an empty list. A list in Python is just an ordered list of elements that can be accessed by their position (index) in the list. Indexes start from 0. (there are good reasons for this)
In general, the range function returns all the integers in the given range that includes the lower bound (the left argument) and does not include the upper bound (the right argument). (there are good reasons for this too)