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.
Related
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.
Here I want to remove any vowels which repeat consecutively. But it shows error as "list out of index".
So I tried break if last element in list is reached, but still won't work.
Here is the code I tried:-
a=[]
b=str(input("enter the string"))
a=b.split(',')
c=['a','e','i','o','u']
for i in c:
for j in range(0,len(a)):
if (a[j+1] == a[len(a)]) is True:
break;
elif ((a[j] == a[j+1]) & (a[j+1] == i)) is True:
del[j]
e.join(a)
print(e)
Please show me how to solve this problem, or any other problem if in there.
How about maintaining a stack for consecutive vowels? whenever you see non-vowel string re-initialize the stack list and when you see vowels but are not consecutive you just add to the final list
stack=[]
new_list=[]
vowel=['a','i','o','u','e']
for i in your_string: # replace your string with actual string
if i not in vowel:
if len(stack) == 1:
new_list.append(stack[0])
new_list.append(i)
stack = []
else:
stack.append(i)
if len(stack) == 1:
new_list.append(stack[0])
You get a list out of index error because you are indexing at a value not in a
if (a[j+1] == a[len(a)]) is True:
a[len(a)] does not exist, arrays are zero indexed so they start from 0. An array with 5 items has index 0,1,2,3,4
the line should be:
if (a[j+1] == a[len(a) - 1]) is True:
Also 'is True' is redundant, so further refined:
if a[j+1] == a[len(a) - 1]:
Also is del[j] an error? should it be del a[j]?
If this is the case, the program will run into further errors as you are iterating over the entire Original size of the array but deleting values during this iteration, so it will look for items that no longer exist.
First detail is this: if (a[j+1] == a[len(a)]) is True: from what I understood this is to break the code when it is necessary. But that is completely unnecessary. Instead you should fix the number of iterations in the beginning, which should be for j in range(0,len(a)-1):
Another problem is that you aren't really iterating through the letters, just each comma separated phrases. If you put "Hello, World" you aren't checking the letters, you check "Hello" and " World". You might as well remove b and let a just be the raw input.
Since a would then be a string, to erase the i-th letter of a string you can use the function below.
def remove_jth(word, j):
word = word[:j] + word[j+1:]
Finally since you are using range, it will build a "list" that has the size len(a) when you start the for, but as you remove vowels, the length of a gets shorter and the range you had at the beginning will be to much. If you fix all of these things you should have it right
You can do it this way:
a=[]
b=str("a,a,a,b,e,e,e,c,x,d")
a=b.split(',')
c=['a','e','i','o','u']
j = 0
for i in c:
while j < len(a)-1:
if a[j] == a[j+1] and a[j] == i:
del a[j]
else:
j = j+1
j=0
Use a while loop to check through the list and delete consecutive duplicates. Then reset the the while loop back to zero and run through the list again.
Using a for loop will not work,if you are deleting items in the list that is being used to iterate over.
b=str("a,a,a,b,e,e,e,c,x,d") was just used to test the code.
To print the results you can just do print(a) it will print the list out.
I used this Stack Overflow post as reference.
I edited it to suit you:
result=original.replace('a','').replace('e',''),replace('i','').replace('o','').replace('u','')
original is your input string and result is your output string.
t=input()
st=""
vow=['a','e','i','o','u']
st+=t[0]
for i in range(1,len(t)):
if(t[i].lower() in vow):
if(t[i-1].lower() not in vow and i-1>=0):
st+=t[i]
else:
st+=t[i]
print(st)
I have to sort a user inputed list from lowest to highest without . sort, but when I try to replace two values to put them in order I find myself in an infinite loop
list = input('Enter list of numbers separated by a space: ').split()
list = [int(b) for b in list]
def list_sort(list):
while list:
a = list[0] # random number in list
for x in list: # to check every number in the list
if x < a: # find if the new number is less than original
c, d = list.index(x), list.index(a)
list[d], list[c] = list[c], list[d]
print(list_sort(list))
You are setting your while loop to run as long as list is True, which in your code is always going to be true. What you want to do instead is set up a condition inside your while loop to break out of your loop with a break statement.
while True:
if some_break_condition_met:
break
else:
# do logic
Also, list is used in python to create a list, so I strongly suggest not using list as your variable, maybe change it to lst or my_list. Using list could cause problems.
list = input('Enter list of numbers separated by a space: ').split(' ')
list = [int(b) for b in list]
def list_sort(list):
updated = True
while updated:
updated = False
for orig_index in range(0, len(list)):
for check_index in range(orig_index, len(list)):
if list[check_index] < list[orig_index]:
list[orig_index], list[check_index] = list[check_index], list[orig_index]
updated = True
print(list_sort(list))
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
list1 = []
elective = []
prereq = []
someNumber = 1
dict2 = {
1: SEM2period1, 2: SEM2period2,
2: SEM2period3, 4: SEM2period4,
5: SEM2period5, 6: SEM2period6,
7: SEM2period7, 8: SEM2period8
}
for key, dlist in dict2.items():
if not dlist:
list1.append("Free Period")
someNumber += 1
continue
for item in dlist:
if item in list1:
continue
elif item in elective:
elecStorage.append(item)
elif item in prereq:
list1.append(item)
someNumber += 1
break
if someNumber > len(list1):
for index in elecStorage:
if index in list1:
break
else:
list1.append(index)
someNumber += 1
elecStorage[:] = []
break
Notes: Electives and Prereq both contain strings like "Calculus 1" (for prereq), or "Astronomy" (for elective.) The variables in dict2 are lists that contain class (as in classroom) names that were called earlier by the function.
What the snippet that starts out with "for key, dlist in dict2.items()" should do is search through the the elements of the first list, checking first if there is a list, if there isn't then append "Free Period" into the list. Then it should check if any of the elements of the list exist in prereq, and finally if there isn't, append something from electives into it. (Because if it gets past the first condition, it's safe to assume there is at least an elective.) and then loop back around and perform the same operation to the next list of elements.
Issue is, unless all of the lists contain nothing, it won't append 'Free Period' and I can't figure out why.
Ideas?
Something in your SEM*period* is likely returning an empty list, and not None. The correct checks for empty list '[]', is 'if list1 == []' or 'if len(list1) == 0'.
None is placeholder meaning a non-existing object. [] is a valid list object, it just has no entries in the list. 'if not foo' is simply checking for None, not an empty list.
You should verify the contents of your SEM2period variables, this is hard to diagnose without them. I didn't follow the rest of your logic, but it's really just the first block in the loop that you are interested in, yes? You may have a list containing an empty list, perhaps? That would mess up your logic:
d2 = {1:['elec'], 2:[]}
for key, dlist in d2.items():
if not dlist:
print 'empty!'
else:
print dlist
gives you
['elec']
empty!
but
d2 = {1:['elec'], 2:[[]]}
for key, dlist in d2.items():
if not dlist:
print 'empty!'
else:
print dlist
gives you
['elec']
[[]]