keylist = ['A/P', 'A/Q', 'B/P', 'B/Q', 'C/P', 'C/Q']
List = ['A','B','C']
I want to make an Operation for every element in List and for every element in keylist :
for n in List:
for key in keylist:
if key.split('/')[0] == List[n] and key.split('/')[-1] == 'P':
try:
print(n) #placeholder
except:
pass
Basically, I want to check if the first split element of keylist is an element of List but the Output is an error:
TypeError: list indices must be integers or slices, not str
Because n you are using in List[n] is not an index to element in List.
for n in List: # here n is not the index to element in list but element itself.
for key in keylist: # so you can't use List[n] below e.g. n is 'A' in first iteration
if key.split('/')[0] == List[n] and key.split('/')[-1] == 'P':
try:
print(n) #placeholder
except:
pass
If you need index of element in the list, use code as below.
for idx, ele in enumerate(List):
for key in keylist:
if key.split('/')[0] == List[idx] and key.split('/')[-1] == 'P':
try:
print(List[idx]) # or print(ele)
except:
pass
Here, ele == List[idx]
keylist = ['A/P', 'A/Q', 'B/P', 'B/Q', 'C/P', 'C/Q']
List = ['A','B','C']
for n in List:
for key in keylist:
if ((key.split('/')[0] in List) and (key.split('/')[1] == 'P')):
try:
print(n) #placeholder
except:
pass
Keeping with the Zen of Python.
Flat is better than nested
for key in keylist:
s = key.split('/')
if s[0] in List and s[-1] == 'P':
try:
print(s[0]) #placeholder
except:
pass
This will work as long as the elements in List are unique. Your algorithm will duplicate outputs for duplicates in List. This algorithm will not.
Related
I would be very happy if somebody could help me solve the following exercise about dictionaries.
Write a function that takes a dictionary where every key is a string and the value is a whole number (integer) and returns a sorted list of the keys corresponding to their even numbers.
Example
dictionary = {'Kurt':35, 'Alex':26, 'Laura':31}
Should return
mylist= ['Alex'] # because it's the only key that has a matching even number
This is my code
def even_numbers (mydict):
mylist = []
for num in mydict.values():
if num % 2 == 0:
mylist.append(mydict.keys())
return mylist
Please help me
use dict.items instead of dict.values:
def even_numbers (mydict):
mylist = []
for key, num in mydict.items():
if num % 2 == 0:
mylist.append(key)
return mylist
when you do mylist.append(mydict.keys()) you'll have a list of keys for every pair value, so the need of using dict.items which return an iterable of key, value pair
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.
So the above is what I am trying to accomplish. And I am extremely new to all this so sorry if I don't make sense at times. Right now I am just trying to set up running through my list and appending any str to string list, and any int to my num list. Ive tried tons of ways and read documentation, and tried to search for help but I am either misreading stuff or just searching the wrong stuff. any help would be greatly appreciated.
stuff = ['magical unicorns',19,'hello',98.98,'world']
string = []
num = []
for i in range(len(stuff)):
if isinstance(i,str):
string.append(value,i)
if isinstance(i,int):
num.append(i)
print (string)
print (num)
You can use list comprehension for a quick, concise solution:
stuff = ['magical unicorns',19,'hello',98.98,'world']
s = ''.join(i for i in stuff if isinstance(i, str))
a = sum(i for i in stuff if isinstance(i, int) or isinstance(i, float))
print(s)
print(a)
if len(s) > 0 and a > 0:
print("mixed")
elif len(s) > 0 and a == 0:
print("string")
elif len(s) == 0 and a > 0:
print("integer")
Output:
magical unicornshelloworld
19
mixed
for i in range(len(stuff))
This will iterate over the indexes of your lists. So, you will only append this indexes to your list num.
Do the same loop but replace for i in range(len(stuff)) by for i in stuff. With this, you will iterate over your list elements.
stuff = ['magical unicorns',19,'hello',98.98,'world']
string = []
num = []
for i in stuff:
if isinstance(i,str):
string.append(i)
if isinstance(i,int):
num.append(i)
print (string)
print (num)
Think about python for loops as foreach loops in other languages. So we want to iterate over each item in the stuff list.
We then want to make running totals of the strings and numbers.
Here is a simple loop which accomplishes this :)
from numbers import Number
stuff = ['magical unicorns',19,'hello',98.98,'world']
running_string = ''
running_total = 0
for item in stuff:
if isinstance(item, basestring):
running_string += item
if isinstance(item, Number):
running_total += item
print running_total
print running_string
if running_string and running_total:
print 'mixed'
elif running_string:
print 'string'
elif running_total:
print 'int'
else:
print 'empty'
This should do the trick.
stuff = ['magical unicorns',19,'hello',98.98,'world']
s = ""
num = 0
hasnum = False
hasstr = False
for i in stuff:
if isinstance(i, str):
s += i
hasstr = True
if isinstance(i, int):
num += i
hasnum = True
print (string)
print (num)
if hasnum and not hasstr:
print "Only ints"
elif hasstr:
print "Only strs"
else:
print "Mixed"
Let's say I have this array:
arr = ["foo","bar","hey"]
I can print the "foo" string with this code :
for word in arr:
if word == "foo":
print word
But I want also check the next word if it equals to "bar" then it should print "foobar"
How can I check the next element in a for loop?
The items in a list can be referred to by their index. Using the enumerate() method to receive an iterator along with each list element (preferable to the C pattern of instantiating and incrementing your own), you can do so like this:
arr = ["foo","bar","hey"]
for i, word in enumerate(arr):
if word == "foo" and arr[i+1] == 'bar':
print word
However, when you get to the end of the list, you will encounter an IndexError that needs to be handled, or you can get the length (len()) of the list first and ensure i < max.
for i in range(len(arr)):
if arr[i] == "foo":
if arr[i+1] == 'bar':
print arr[i] + arr[i+1]
else:
print arr[i]
Rather than check for the next value, track the previous:
last = None
for word in arr:
if word == "foo":
print word
if last == 'foo' and word == 'bar':
print 'foobar'
last = word
Tracking what you already passed is easier than peeking ahead.
You can also do it with zip:
for cur, next in zip(arr, arr[1:]):
if nxt=='bar':
print cur+nxt
But keep in mind that the number of iterations will be only two since len(ar[1:]) will be 2
I started study python and I arrive at list and recursion. I saw an exercise. It says Write a function that takes two lists as parameters and checks whether the first is a sublist of the second. Note that the elements in the lists may be lists themselves. At the beginning I thought it was easy but then I saw that the tricky thing is that my function has to accept nested lists (like [1,2,[3,[4,5]]]) and has to be in recursion. I know how to do it with recursion and with normal lists. I have no idea of how to apply the recursion to the nested lists. Can you help me?
el1 = ''
el2 = ''
list1 = []
list2 = []
while el1 != "exit":
el1 = input("Insert the words of the first list: ")
print("write exit to finish")
list1.append(el1)
while el2 != "exit":
el2 = input("Insert the words of the second list: ")
print("write exit to finish")
list2.append(el2)
for x in list2:
if x not in list1:
print("FALSE")
break
else:
print("TRUE")
break
Another way to do it, try to substruct the items of first list from the second one. If the length changes, it means that the items of the first list are in the second one too, else: True.
To clarify the idea, check this quick example:
l1= ['alpha','beta']
l2= ['alpha','beta','gama','theta']
l3= ['AnotherWord']
print len(list(set(l2)-set(l1)))==len(l2) #Case where l1 is a sublist of l2
print len(list(set(l2)-set(l3)))==len(l2) #case where l3 is not a sublist of l2
SO your code would look like:
el1 = ''
el2 = ''
list1 = []
list2 = []
while el1 != "exit":
el1 = input("Insert the words of the first list: ")
print("write exit to finish")
list1.append(el1)
while el2 != "exit":
el2 = input("Insert the words of the second list: ")
print("write exit to finish")
list2.append(el2)
if len(list(set(list2)-set(list1)))==len(list2):
print("List 1 is a sublist of List 2")
else:
print("List 1 is not a sublist of List 2")
UPDATE
a,b= [1,2,[3,[4,5]]], [4,5]
c,d= [1,2,[3,[4,5]]], [3,4,5]
def isSublist(a,b):
return any(x if x==b else isSublist(x,b) for x in a if isinstance(x,list) )
print isSublist(a,b) #True
print isSublist(c,d) #False
The way I would understand this exercise is that [1,3] is not a sublist of [1,2,3], but rather [2,3] is a sublist of [1,[2,3]]. In this case, a list A is a sublist of B if there exists an element el in B such that el == A. In order to find this el you need to traverse B recursively, and here is a skeleton for your code so that you can figure out the rest and complete the exercise:
def is_sublist(x,y):
for item in x:
# some comparison and control flow
if isinstance(item, list):
# some code recursively calling is_sublist and more control flow
And here are a few tests for the final code:
print is_sublist([1,2,[3,[4,5]]], [4,5]) # True
print is_sublist([1,2,[3,[4,5]]], [3,[4,5]]) # True
print is_sublist([1,2,[3,[4,5]]], [3,4,5]) # False
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']
[[]]