How to print out the index of an odd number in python - python

My goal is to print out a new list of the index of any odd numbers that a user enter into a list. For example, if the list is [1,2,5,15,4,7] I would like the output to be a list that contains the indexes of the odd numbers like so: [0,2,3,5]
length=int(input('Please enter how long you want your list: '))
list1=[ ]
for i in range(length):
list1.append(int(input('Please enter an integer: ')))
print(list1)
odd_i = []
for i in range(0, len(list1)):
if i % 2:
pass
else:
odd_i.append(list1[i])
print(odd_i)
That is the code I have written, the current output for the example given above is [1,5,15,7] but I would like the index of the odd numbers to be printed [0,2,3,5], not the odd number itself.

You're testing whether the index is odd or even, not the value.
Use enumerate() to iterate over the indexes and values.
for index, value in enumerate(list1):
if value % 2 == 1:
odd_i.append(index)
Also, your test is backwards, you're appending the even elements, not the odd ones.

Solution
Your issue is that you're performing the modulus operator on the indexes themselves rather than the values of the array. Also you're appending the values at the indexes into the array rather than the indexes.
So the quick fix:
odd_i = []
for i in range(0, len(list1)):
if list1[i] % 2:
continue
else:
odd_i.append(i)
print(odd_i)
If any value of the array is not evenly divisible, then append that index, otherwise continue.

Related

list of list comparing

I want to compare the amount of values in a list of a list.
If there would be an empty list in the one of the "sub" lists, it should print "too short".
If the list is long enough, meaning that it has more or 1 value in it, it should print "good". how can I do this?
No library imports please.
You can iterate through the sub-lists and check for len, or just for falsey for empty lists as Python evaluates [] as False.
lists = [[1,2],[],[3,4,5]]
for l in lists:
if len(l) < 1: #or just `if not l:`
print('too short')
else:
print('good')
You need to iterate each element in the list and compare the length using the len function.
Please see sample code below:
#list with one element sublist and 3 element sublist
a = [[1],[3,4,5]]
for index_length in a:
if len(index_length) > 1:
print("Good")
else:
print("too short")
Output:
Reference:
https://www.geeksforgeeks.org/how-to-get-the-number-of-elements-in-a-python-list/#:~:text=Using%20Len()%20function%20to,elements%20present%20in%20the%20list.

Eliminate numbers between 1 and 100 present in list

I have written a code that should input numbers from the user and report back the numbers from 1 to 100 that are missing from their input.
My code is below which doesn't work:
num_list = []
number = input('Enter numbers (remember a space): ')
number.split()
num_list.append(number)
for i in range(1, 101):
if i in num_list:
continue
else:
print(i, end =', ')
The code outputs all the numbers from 1 to 100 but doesn't exclude the numbers.
Note: The code has to exclude all the numbers entered not only one number.
E.g. if the user inputted 1 2 3 4 the output should start from 5 and list the numbers through to 100.
There are three of problems
1) your are not saving the returned list from split method
result = number.split()
2) Use extend instead of append
num_list.extend(result)
3) By default input will read everything as string, you need to convert them into int from string after splitting, below is example using List Comprehensions
result = [int(x) for x in number.split()]
append : Will just add an item to the end of the list
So in you case after appending user input your list will be
num_list.append(number) #[[1,2,3,4,5]] so use extend
extend : Extend the list by appending all the items from the iterable.
num_list.append(number) #[1,2,3,4,5]
Note : If the num_list empty you can directly use result from split method, no need of extend

How to ask the user to enter numbers and then sum the numbers which are divisible by 3?

I want to make a Python script which has the user enter 7 numbers and then check which numbers can be divided by 3, then sum those numbers, and show it to the user as "sum=xx".
I tried:
input_string = input("Enter a list element separated by space ")
list = input_string.split()
Here is using list comprehension,
input_string = input("Enter a list element separated by space ")
numbers = [int(num) for num in input_string.split(',') if int(num) % 3 == 0]
print('Sum = {}'.format(sum(numbers)))
This is based on your question above.
But, you also said that you would want user to input 7 numbers and find sum for numbers which are divisible by 3.
Here is other simple example, where we ask user to input 7 numbers, one number at a time and print sum at the end.
all_numbers = []
for i in range(7):
num = int(input(f'Enter number {i + 1}:\n1'))
all_numbers.append(num)
sum_of_numbers = sum([num for num in all_numbers if num % 3 == 0])
print(f'Sum = {sum_of_numbers}')
You can get a list of integers from the input using the int function which gives you an integer object from a string, since the split function only gives you a list of separated strings.
input_string = input("Enter a list element separated by space ")
my_list = input_string.split()
numbers = []
for n in my_list:
numbers.append(int(n))
However, this will throw a ValueError if n is not a valid number (e.g. "a"), which you can catch with a try-exceptstatement.
Notice how I changed the name of your variable to my_list because the name list already has a meaning in Python and it's a good practice to not assign it to a variable.
If you want to do it in a single step, you can use the useful map function to apply the int function to all of the elements in list. You can check the documentation for this function, as well as any other on the python documentation, or using the help built-in function. (e.g. help(map))
numbers = map(int, my_list)
You can then check if there are 7 numbers in the list by using the len function, and if there aren't 7 you can prompt the user to input the numbers again if that is what you want to do.
>>> my_list = [1, 2, 3]
>>> len(my_list) == 3
True
If you want to keep prompting the user until there are seven numbers on your list, you can put the prompt inside a while block, like shown:
numbers = [] # We create an empty list
while len(numbers) != 7:
input_string = input("Enter a list element separated by space ")
my_list = input_string.split()
numbers = list(map(int, my_list)) # Get the numbers
After getting the numbers, you can see which ones are divisible by 3 by using the modulo operator, which gives you the rest of dividing a number by another (3 in your case). Some examples:
>>> 7%3 # 7 = 3*2 + 1
1
>>> 19%5 # 14 = 5*3 + 4
4
>>> 8%4 # 8 = 4*2 + 0
0
Since you want to check which numbers of your list are divisible by 3 you can check whether this module is 0 or not inside of a loop through the list.
If the numbers are divisible by 3, you can add them to a counting variable, you could initialize to 0 before the loop. That way, after the loop you'd get the sum you want in this variable.
Another, more elegant way of doing so is using a list comprehension instead of a loop, which would only retain the numbers divisible by 3, and then sum its elements using the sum function.
new_list = [x for x in numbers if x%3 == 0]
sum = sum(new_list)

counting the number of terms that are not repeated in the python list

the question was actually like
Write a program that says the number of terms to be replaced to get all the numbers same in the list
ex
a=[1,1,2,1,1,4,1,1]
then the expected output is 2
I guess you are looking for the minimum number of numbers to be replaced so that all numbers are the same.
# store occurrences of each number in a dictionary
d = {}
for i in a:
if i not in d:
d[i] = 1
else:
d[i] += 1
# get key with max value: i.e. most frequent number in initial list
max_k = max(d, key=d.get)
# delete element that appears most often in the initial list
del d[max_k]
# count rest of the numbers => numbers to be replaced
nums_to_replaces = sum([d[k] for k in d])
Your wording is a bit strange.
If you want the number of items that are not one:
len([i for i in a if i!=1])
or
len(a)-a.count(1)
if you want the unique set of numbers that are not repeated as the question says:
len([i for i in set(a) if a.count(i)==1])
You could iterate over the list and make a dictionary of the occurrence:
occurrences = {}
for x in range(len(a)):
if a[x] not in occurences:
occurrences[x] = 1
else:
occurrences[x] += 1
Now you could have a dict of the occurrences and you could do this to get the number of terms to be replaced:
nums = list(occurrences.values()).sort(reverse=True) # Sort I descending order with num of repetitions
print(sum(nums[1:])) # Add occurrences of all but the element with max occurrences
#Or just subtract the max occurrence from the length of list
print(len(a) - max(list(occurrences.values())))
This will give you the least number of changes need to be made. In this way you cannot specify which element you want the whole list to contain

how can i compare string within a list to an integer number?

my task today is to create a function which takes a list of string and an integer number. If the string within the list is larger then the integer value it is then discarded and deleted from the list. This is what i have so far:
def main(L,n):
i=0
while i<(len(L)):
if L[i]>n:
L.pop(i)
else:
i=i+1
return L
#MAIN PROGRAM
L = ["bob", "dave", "buddy", "tujour"]
n = int (input("enter an integer value)
main(L,n)
So really what im trying to do here is to let the user enter a number to then be compared to the list of string values. For example, if the user enters in the number 3 then dave, buddy, and tujour will then be deleted from the list leaving only bob to be printed at the end.
Thanks a million!
Looks like you are doing to much here. Just return a list comprehension that makes use of the appropriate conditional.
def main(L,n):
return([x for x in L if len(x) <= n])
Just use the built-in filter method, where n is the cut off length:
newList = filter(lambda i:len(i) <= n, oldList)
You should not remove elements from a list you are iterating over, you need to copy or use reversed:
L = ["bob", "dave", "buddy", "tujour"]
n = int(input("enter an integer value"))
for name in reversed(L):
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
Making a copy using [:] syntax:
for name in l[:]:
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
This is a simple solution where you can print L after calling the main function. Hope this helps.
def main(L,n):
l=len(L)
x=0
while x<l:
#if length is greater than n, remove the element and decrease the list size by 1
if len(L[x])>n:
L.remove(L[x])
l=l-1
#else move to the next element in the list
else:
x=x+1

Categories

Resources