List population - python

i = int(input('enter number of input: '))
for a in range (0, i):
listInput = int (input("enter your list numbers: "))
List1 = []
List1.append(listInput)
print(List1)
the list only populates the second iteration number not the first input.

include the List1 outside the for loop cuz its getting reinitialized everytime.
Do You want to let user add numbers in a list?
If so, I got a different code snippet
n = int(input("enter number of input: "))
a = list(map(int,input("Enter your list numbers : ").split()))[:n]

Related

How to make Python choose the greatest number from 5 inputs(simple)way?

The problem is:
we write down a code
x = int(input("enter the number here"))
then we loop that 5 times with range and we want python to tell us which number is the greatest of all for example
1,10,100,1000
the greatest number is 1000
how can we do that?
I just do not know how to do it
Here is an easy approach:
nums = (input().split(','))
print(max(list(map(int, nums))))
As the input is taken as a string, when converting it to a list, the elements will be strings. The function map will convert each string in the list to an integer.
I don't know if it's exactly what you want but here is an input combined with a for loop in a range :
answers = []
for i in range(5):
x = int(input("enter the number here : "))
answers.append(x)
greatest_number = max(answers)
print("The greatest number is {}".format(greatest_number))
You can do it by splitting the input with respect to ",". After splitting the str should be turn into int using for loop. Now use max function with the new integer list to get the maximum number.
so your final code should be:
x = input("enter the number here: ")
list = x.split(",")
int_list = []
for s in list:
int_list.append(int(s))
max_num = max(int_list)

How can we add inputs when total number of inputs are not known using strings in Python?

I could get the inputs but don't know how to add them.
This is what I tried:
n = int(input("enter the total number to find average"))
for i in range (0, n):
i = int(input("enter the number {i} here"))
if you want to be able to have an arbitrary number of inputs you can use a while loop and a break condition
numbers = []
i = 1
while True:
try:
numbers.append(int(input(f"enter number {i} (enter blank to end):")), inplace=True)
except ValueError:
break
in this way you can store as many or few inputs as the user wishes to provide in a list and then perform the rest of the script on that list
Please try this:
n = int(input("enter the total number to find average"))
s=0 #a varaiable to store sum
for i in range (1, n+1):
i = int(input("enter the number {} here ".format(i)))
s+=i
print('The sum of all the numbers entered by you is :', s)

Determining the two largest numbers from user input

I've been working on a small program to learn more about Python, but I'm stuck on something.
Basically, the user has to input a sequence of positive integers. When a negative number is entered, the program stops and tells the user the two largest integers the user previously inputted. Here is my code:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while (number > 0):
number = int(input())
if number < 0:
break
largestInteger = max(numbers)
print(largestInteger)
integers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
There are two issues with your code:
You need to update the list with the user input for every iteration of the while loop using .append().
integers isn't defined, so you can't call .remove() on it. You should refer to numbers instead.
Here is a code snippet that resolves these issues:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while number > 0:
number = int(input())
if number > 0:
numbers.append(number)
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
I would build a function that would call itself again if the user enters a number larger or equal to 0, but will break itself and return a list once a user inputs a number smaller than 0. Additionally I would then sort in reverse (largest to smallest) and call only the first 2 items in the list
def user_input():
user_int = int(input('Please enter your desired integers'))
if user_int >= 0:
user_lst.append(user_int)
user_input()
else:
return user_lst
#Create an empty list
user_lst = []
user_input()
user_lst.sort(reverse=True)
user_lst[0:2]
You forgot to append the input number to the numbers list
numbers = []
while (True):
number = int(input())
if number < 0:
break
numbers.append(number)
print("First largest integer: ", end="")
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
print("Second largest integer: ", end="")
largestInteger2 = max(numbers)
print(largestInteger2)```
The above code will work, according to your **desire**

How can I find the amount of duplicates an element has within a list?

In this code, I have a user-generated list of numbers and have to find the amount of duplicates a specific element has within that list. I am getting an error in the function. How do I fix this?
def count(list,y):
new_list = []
for j in range(0,x):
if(list[j]==y):
new_list.append(list[j])
else:
pass
print(new_list)
length = len(new_list)
print("The number {} appears {} times in the list".format(y,length))
list = []
x = int(input("Please enter the size of the list you want to create: "))
for i in range(0,x):
value = input("Please enter value of list : ")
list.append(value)
print("The list of the values you entered : {}".format(list))
y = int(input("Which element do you want to find the number? : "))
count(list,y)
There were multiple issues in your code.
In the loop in function count instead j you are using i as index.
initiation of loop index till range(0,x) => x is not defined as the variable is not assigned in this scope, instead use len of the list.
All the inputs added to the list were strings and the one that was searched was an integer.
Other suggestions:
do not use list as a variable name as it is a keyword.
Below this code I am also providing a shorter version of the function count.
def count(mylist,y):
new_mylist = []
for j in range(0,len(mylist)):
print(mylist[j])
if(mylist[j]==y):
new_mylist.append(mylist[i])
else:
pass
length = len(new_mylist)
print("The number {} appears {} times in the mylist".format(y,length))
mylist = []
x = int(input("Please enter the size of the mylist you want to create: "))
for i in range(0,x):
value = int(input("Please enter value of mylist : "))
mylist.append(value)
print("The mylist of the values you entered : {}".format(mylist))
y = int(input("Which element do you want to find the number? : "))
count(mylist,y)
Shorter version
def count(mylist,y):
length = mylist.count(y)
print("The number {} appears {} times in the mylist".format(y,length))
one issue, you're trying to acces the i'th element in list, but i is not initialized. Try replacing i with j
for j in range(0,x):
if(list[i]==y):
new_list.append(list[i])
If you don't mind me taking liberties with your code, here's an example using the Counter from collections. Note that it doesn't do exactly the same thing as your code, as Counter doesn't use indexes as you were using before.
from collections import Counter
input_counter = Counter()
while True:
value = input("Please enter a value (or nothing to finish): ")
if value == '':
break
input_counter[value] += 1
print(input_counter)
y = input("Which number do you want to count the instances of? ")
print(input_counter[y])

printing matrix (2-d) in python

I'm trying to print this code into a matrix but keep getting:
line 22, in <module>
print(matrix[i][j], end=" ")
IndexError: list index out of range
This is my code:
A basic code for matrix input from user
R = int(input("Enter the number of runners:"))
C = int(input("Enter the number of days to log:"))
names_runners = []
runners_time =[]
# Initialize matrix
matrix = []
# For user input
for i in range(R): # A for loop for row entries
a = []
names_runners.append(input("enter name of runner" + str(i+1)))
for j in range(C): # A for loop for column entries
runners_time.append(int(input("enter time for day" + str(j+1))))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end=" ")
print()
The first thing that pops out to me is that the number R is never initialized. I don't know if you maybe did this somewhere else in your code, but perhaps make sure that you have a valid value of R.
The second thing I'm noticing is that in the first outer for-loop, you create an empty list a = []... and then don't do anything with it. Make sure you're appending the actual data you care about into the matrix, because right now you're inserting it into unrelated lists and then appending an empty list. Hence, when you try to iterate over as many items as there are in your names_runners and runners_times lists, you end up going out-of-bounds.
I think it would be better to use dictionary in your case, here:
runners_dict = {}
runners_total = 2
days_to_log = int(input("Enter the number of days to log:"))
for i in range(runners_total):
runner_name = input("enter name of runner" + str(i+1))
runners_dict[runner_name] = []
for j in range(days_to_log):
todays_time = int(input("enter time for day" + str(j+1)))
runners_dict[runner_name].append(todays_time)
print(runners_dict)
Results:
Enter the number of days to log:2
enter name of runner1joe
enter time for day1123
enter time for day2321
enter name of runner2bill
enter time for day1123
enter time for day2321
{'joe': [123, 321], 'bill': [123, 321]}

Categories