I have list in list:
a = [
[123123, 'juststring', '129.123.41.4'],
[456456, 'usrnm', '129.123.41.4'],
[78970, 'Something', '129.123.41.4']
]
I have another list:
b = [123123, 354634, 54234, 6734]
If b contains numbers in a, must put 'YES' or 'NO'
Output:
a = [[123123, 'juststring', '129.123.41.4', 'YES'], [456456, 'usrnm', '129.123.41.4', 'NO'], [78970, 'Something', '129.123.41.4', 'NO']]
This is my code:
for i in range(len(tbl_list)):
for l in tbl_list:
for p in pid:
if int(l[0]) == int(p):
tbl_list[i].append('YES')
break
else:
tbl_list[i].append('NO')
break
def draw_table():
global tbl_list
global pid
for i in range(len(tbl_list)):
for l in tbl_list:
for p in pid:
if int(l[0]) == int(p):
tbl_list[i].append('YES')
break
else:
tbl_list[i].append('NO')
break
tbl.add_row(l)
print(tbl_list)
print(tbl.draw())
tbl.reset()
tbl.header(Heading)
You could do this:
a = [[123123, 'juststring', '129.123.41.4'], [456456, 'usrnm', '129.123.41.4'], [78970, 'Something', '129.123.41.4']]
b = [123123, 354634, 54234, 6734]
for list_a in a:
if any(pid == list_a[0] for pid in b):
list_a.append('YES')
else:
list_a.append('NO')
print(a)
Related
I have a dictionary of topics with lists as values.
topics = {'sports':sports, 'food':food, 'movies':movies, 'singers':singers, 'goats':goats}
These are the values
sports = ['soccer','basketball','tennis'],
food = ['burger','fried rice', 'spaghetti','curry', 'lamb','wings']
movies = ['spider man', 'batman', 'iron man', 'hustle', 'desperado']
singers = ['drake']
goats = ['messi', 'jordan']
I want to transform the dictionary in a manner that, given size k, the elements in the list shouldn't be greater than k. If they are, create a new list, and put the elements in. For instance, if k = 2, that means I want the list values to be split like this:
{'goats':['messi', 'jordan'],
'sports_1', ['soccer','basketball'],
'sports_2': ['tennis'],
'food_1': ['burger','fried rice'],
'food_2': ['spaghetti','curry'],
'food_3': ['lamb','wings'],
'movies_1': ['spider man', 'batman'],
'movies_2: ['iron man', 'hustle'],
'movies_3':['desperado'],
'singers':['drake']}
Try:
def chunks(lst, n):
for i in range(0, len(lst), n):
yield lst[i : i + n]
out = {}
for k, v in topics.items():
c = list(chunks(v, 2))
if len(c) == 1:
out[k] = c[0]
else:
for i, ch in enumerate(c, 1):
out[f"{k}_{i}"] = ch
print(out)
Prints:
{
"sports_1": ["soccer", "basketball"],
"sports_2": ["tennis"],
"food_1": ["burger", "fried rice"],
"food_2": ["spaghetti", "curry"],
"food_3": ["lamb", "wings"],
"movies_1": ["spider man", "batman"],
"movies_2": ["iron man", "hustle"],
"movies_3": ["desperado"],
"singers": ["drake"],
"goats": ["messi", "jordan"],
}
I have two files students and grades that has to be read and converted to a dictionary and finally print to a prettytable:
Grades:
10103 SSW 567 A 98765
10103 SSW 564 A- 98764
10103 CS 501 B 98764
10115 SSW 567 A 98765
10115 SSW 564 B+ 98764
Students:
10103 Baldwin, C SFEN
10115 Wyatt, X SFEN
Below is the code to do that:
from collections import defaultdict
from prettytable import PrettyTable
import os
class University:
def __init__(self,path):
self.students=dict()
self.instructors=dict()
self.grades=defaultdict(list)
def gg(self):
for filename in os.listdir(self.path):
with open(os.path.join(self.path, filename), 'r') as f:
if filename=="students.txt":
for line in f:
a,b,c = line.split("\t")
self.students[a] = {
"name": b, "major": c}
elif filename=="grades.txt":
for line in f:
d,e,f,g = line.split("\t")
self.grades[d].append({
"course": e, "grade": f,"instructor":g})
pt: PrettyTable = PrettyTable(
field_names=[
'CWID',
'Name',
'cc',])
for i,j in self.students.items():
for x,y in self.grades.items():
if i==x:
pt.add_row([i,j["name"],y["course"]])
return pt
a = University("C://Users/Swayam/Documents/Downloads")
c = a.gg()
print(c)
The output is supposed to be:
10103 Baldwin,C SSW567,SSW564,CS501
10115 Wyatt, X SSW 567,SSW564
When I run the above code I get the below error:
TypeError: list indices must be integers or slices, not str
I am not supposed to use the variables in the add_row line and I know that, but what can I replace it with so I get the output.
The issue with your code is that y is a list:
for i,j in self.students.items():
for x,y in self.grades.items():
print(type(y))
>>> <class 'list'>
This is because of you code where you define grades:
self.grades=defaultdict(list)
So, you need some extra code to go through the list of dictionaries:
courses = ",".join(h["course"] for h in y)
And so, the final code becomes:
from collections import defaultdict
from prettytable import PrettyTable
import os
class University:
def __init__(self, path):
self.students = dict()
self.instructors = dict()
self.grades = defaultdict(list)
self.path = path
def gg(self):
for filename in os.listdir(self.path):
with open(os.path.join(self.path, filename), "r") as f:
if filename == "students.txt":
for line in f:
a, b, c = line.split("\t")
self.students[a] = {"name": b, "major": c}
elif filename == "grades.txt":
for line in f:
d, e, f, g = line.split("\t")
self.grades[d].append(
{"course": e, "grade": f, "instructor": g}
)
pt: PrettyTable = PrettyTable(
field_names=[
"CWID",
"Name",
"cc",
]
)
for i, j in self.students.items():
for x, y in self.grades.items():
if i == x:
courses = ",".join(h["course"] for h in y)
pt.add_row([i, j["name"], courses])
return pt
a = University("C://Users/Swayam/Documents/Downloads")
c = a.gg()
print(c)
I get this output when running the above code:
+-------+------------+------------------------+
| CWID | Name | cc |
+-------+------------+------------------------+
| 10103 | Baldwin, C | SSW 567,SSW 564,CS 501 |
| 10115 | Wyatt, X | SSW 567,SSW 564 |
+-------+------------+------------------------+
Note however that I did have to change:
The split you were using to regex split since \t wasn't getting recognised for me
Added self.path = path to your __init__ method
Of course, the path too
Alien Dictionary
Link to the online judge -> LINK
Given a sorted dictionary of an alien language having N words and k starting alphabets of standard dictionary. Find the order of characters in the alien language.
Note: Many orders may be possible for a particular test case, thus you may return any valid order and output will be 1 if the order of string returned by the function is correct else 0 denoting incorrect string returned.
Example 1:
Input:
N = 5, K = 4
dict = {"baa","abcd","abca","cab","cad"}
Output:
1
Explanation:
Here order of characters is
'b', 'd', 'a', 'c' Note that words are sorted
and in the given language "baa" comes before
"abcd", therefore 'b' is before 'a' in output.
Similarly we can find other orders.
My working code:
from collections import defaultdict
class Solution:
def __init__(self):
self.vertList = defaultdict(list)
def addEdge(self,u,v):
self.vertList[u].append(v)
def topologicalSortDFS(self,givenV,visited,stack):
visited.add(givenV)
for nbr in self.vertList[givenV]:
if nbr not in visited:
self.topologicalSortDFS(nbr,visited,stack)
stack.append(givenV)
def findOrder(self,dict, N, K):
list1 = dict
for i in range(len(list1)-1):
word1 = list1[i]
word2 = list1[i+1]
rangej = min(len(word1),len(word2))
for j in range(rangej):
if word1[j] != word2[j]:
u = word1[j]
v = word2[j]
self.addEdge(u,v)
break
stack = []
visited = set()
vlist = [v for v in self.vertList]
for v in vlist:
if v not in visited:
self.topologicalSortDFS(v,visited,stack)
result = " ".join(stack[::-1])
return result
#{
# Driver Code Starts
#Initial Template for Python 3
class sort_by_order:
def __init__(self,s):
self.priority = {}
for i in range(len(s)):
self.priority[s[i]] = i
def transform(self,word):
new_word = ''
for c in word:
new_word += chr( ord('a') + self.priority[c] )
return new_word
def sort_this_list(self,lst):
lst.sort(key = self.transform)
if __name__ == '__main__':
t=int(input())
for _ in range(t):
line=input().strip().split()
n=int(line[0])
k=int(line[1])
alien_dict = [x for x in input().strip().split()]
duplicate_dict = alien_dict.copy()
ob=Solution()
order = ob.findOrder(alien_dict,n,k)
x = sort_by_order(order)
x.sort_this_list(duplicate_dict)
if duplicate_dict == alien_dict:
print(1)
else:
print(0)
My problem:
The code runs fine for the test cases that are given in the example but fails for ["baa", "abcd", "abca", "cab", "cad"]
It throws the following error for this input:
Runtime Error:
Runtime ErrorTraceback (most recent call last):
File "/home/e2beefe97937f518a410813879a35789.py", line 73, in <module>
x.sort_this_list(duplicate_dict)
File "/home/e2beefe97937f518a410813879a35789.py", line 58, in sort_this_list
lst.sort(key = self.transform)
File "/home/e2beefe97937f518a410813879a35789.py", line 54, in transform
new_word += chr( ord('a') + self.priority[c] )
KeyError: 'f'
Running in some other IDE:
If I explicitly give this input using some other IDE then the output I'm getting is b d a c
Interesting problem. Your idea is correct, it is a partially ordered set you can build a directed acyclcic graph and find an ordered list of vertices using topological sort.
The reason for your program to fail is because not all the letters that possibly some letters will not be added to your vertList.
Spoiler: adding the following line somewhere in your code solves the issue
vlist = [chr(ord('a') + v) for v in range(K)]
A simple failing example
Consider the input
2 4
baa abd
This will determine the following vertList
{"b": ["a"]}
The only constraint is that b must come before a in this alphabet. Your code returns the alphabet b a, since the letter d is not present you the driver code will produce an error when trying to check your solution. In my opinion it should simply output 0 in this situation.
I'm looking to take a log file in the following format and turn it into the json format of the snippet below.
2020:03:29-23:07:22 sslvpnpa ulogd[19880]: id="2001" severity="info" sys="SecureNet" sub="packetfilter" name="Packet dropped" action="drop" fwrule="60001" initf="eth0"
and turn it into the json format of the snippet below.
{"timestamp": "2020:03:29-23:07:22", "object": "sslvpnpa", "code": "ulogd[19880]", "id":"2001", severity="info", sys="SecureNet", sub="packetfilter" ...}
My start was to loop like this:
log_fields = log_row.split()
obj={}
for k in log_fields:
if k.find('=') > -1:
obj[k.split('=')[0]] = k.split('=')[1]
But then i realized some of the values have spaces and that there might be some list comprehension or generator expression that is more efficient or easier to read.
The object/json this generates will then be added to a field in a larger object.
Thanks in advance.
I think this will work out for you:
def split_string(s):
d = {}
ind = 0
split_s = s.split()
while ind < len(split_s):
current_s = split_s[ind]
if "=" in current_s:
key, value, ind = get_full_string(split_s, ind)
d[key] = value
else:
d[f"key{ind}"] = current_s
ind += 1
return d
def get_full_string(split_s, ind):
current_s = split_s[ind]
current_s_split = current_s.split("=")
key = current_s_split[0]
current_value = current_s_split[1]
if current_value[-1] == '"':
current_value = current_value.replace('"', '')
return key, current_value, ind
value_list = [current_value]
ind += 1
while ind < len(split_s):
current_value = split_s[ind]
value_list.append(current_value)
if current_value[-1] == '"':
break
ind += 1
value = " ".join(value_list)
value = value.replace('"', '')
return key, value, ind
Input:
s = '2020:03:29-23:07:22 sslvpnpa ulogd[19880]: id="2001" severity="info" sys="SecureNet" sub="packetfilter" name="Packet dropped" action="drop" fwrule="60001" initf="eth0"'
print(split_string(s))
Output:
{'key0': '2020:03:29-23:07:22', 'key1': 'sslvpnpa', 'key2': 'ulogd[19880]:', 'id': '2001', 'severity': 'info', 'sys': 'SecureNet', 'sub': 'packetfilter', 'name': 'Packet dropped', 'action': 'drop', 'fwrule': '60001', 'initf': 'eth0'}
Python 3
Hello guys I'm a python beginner studying dictionary now
below is what I have learned so far how to save list into a file
and count items in list like below.
class item:
name = None
score = None
def save_list_in_file(file_name:str, L:[item]):
f = open(file_name,'w')
for it in L:
f.write(it.name + "" + str(it.score))
f.close()
def count_item_in_list(L:[item])->int:
n = 0
for it in L:
if it.score >= 72:
n += 1
return n
and I'm not sure if using dictionary is same way as I use in list
for example:
def save_dict_to_file(file_name:str, D:{item}):
f = open(file_name,'w')
for it in D:
f.write(it.name + "" + str(it.score))
f.close()
def count_item_in_dict(D:{item})->int:
n = 0
for it in D:
if it.score <= 72:
n += 1
return n
will be correct? i thought dict would be different than using a list.
Thanks for any comment!
You can't use a dictionary the same way as using a list.
A list is defined as a sequence of elements. So when you have the list:
L=['D','a','v','i','d']
You can loop it like this:
for it in L:
print(it)
And it will print:
D
a
v
i
d
Instead, a dictionary is a group of tuples of two elements where one is the key and the second is the value. So for example you have a Dictonary like this:
D = {'firstletter' : 'D', 'secondletter': 'a', 'thirdletter' : 'v' }
And when you loop it like a list:
for it in L:
print(it)
it will print only the keys:
firstletter
secondletter
thirdletter
so in order to obtain the values you have to print it like this:
for it in D:
print(D[it])
that will display this result:
D
a
v
If you need more information you can check de documentation for dictionary :)
Python 3 documentation of Data Structures