How to loop for choosing data in Jupyter Notebook by Python - python-3.x

I have 2 columns in data frames.
Column 1 = Source
Column 2 = Target
My data source
Source Target
A B
W X
B C
C D
C Z
A Z
Z Y
Input = A, The output should be display as below.
Source Target
A B
B C
C D
C Z
A Z
Z Y
I try to code as below but not finished yet.
In [1]:
a = input()
b = []
for Source, Target in zip(data.Source,data.Target):
if Source == a:
b.append(True)
else:
b.append(False)
Input = A
In [2]: is_long = pd.Series(b)
is_long
Out [2]: 0 True
1 False
2 True
3 True
4 ...
In [3]: data[is_long]
Out [3]: Source Target
A B
B C
C D
C Z
A Z
Z Y

As I understood, the idea is:
try in turn each vertice from the source DataFrame,
the current vertice is "OK" when its Source node has been visited
before,
the visited list contains initially only the node given by the user and
should be extended by Target node of each checked vertice.
Start from defining the following class:
class Visitor:
def __init__(self):
self.clear()
def addNode(self, node):
if not self.isVisited(node):
self._nodes.append(node)
def isVisited(self, node):
return node in self._nodes
def clear(self):
self._nodes = []
This class keeps a register of visited nodes. It will be used soon.
Then define a function checking the "continuation criterion" for the current
row:
def isContinued(row, vs):
res = vs.isVisited(row.Source)
if res:
vs.addNode(row.Target)
return res
The first argument is the current row and the second is a Visitor object.
Then run:
vs = Visitor()
vs.addNode(a)
df[df.apply(isContinued, axis=1, vs=vs)]
The first line creates a Visitor object.
The second adds the "starting node" (just given by the user) to the
"visited list".
Then df.apply(isContinued, axis=1, vs=vs) creates a Boolean vector
- the continuation criteria for edges.
As isContinued function is applied to subsequent edges, the "visited list"
is extended with Target node.
The (just updated) visited list is then used to compute the continuation
criteria for subsequent edges.
The result is a list of edges meeting the continuation criterion.

Related

Alien Dictionary Python

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.

Convert values in a list to RGB values

I'm trying the following to convey the value in a list to a list of [R,G,B] values.
data = range(0,6)
minima = min(data)
maxima = max(data)
norm = matplotlib.colors.Normalize(vmin=minima, vmax=maxima, clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap=cm.Greys_r)
node_color = []
for d in data:
node_color.append(mapper.to_rgba(d))
The above returns a 4th dimension A. I would like to know if there is a way to obtain only RGB values.
mapper.to_rgba(d) returns a tuple of the form (r, g, b, a). You can directly assign the result to a 4-tuple as r, g, b, a = mapper.to_rgba(d). And then create a triple as (r, g, b) to be stored in a list.
mapper.to_rgba also works when it gets a list or array as parameter, so calling mapper.to_rgba(data) directly gets the list of all rgba-tuples. Via a list comprehension, a new list of rgb-triples can be created:
import matplotlib
from matplotlib import cm
data = range(0, 6)
norm = matplotlib.colors.Normalize(vmin=min(data), vmax=max(data), clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap=cm.Greys_r)
node_color = [(r, g, b) for r, g, b, a in mapper.to_rgba(data)]
PS: The above code gives r, g and b values between 0 and 1. Depending on the application, integer values from 0 to 255 could be needed:
node_color = [(r, g, b) for r, g, b, a in mapper.to_rgba(data, bytes=True)]

FROM --> IMPORT function & return values

I'm using python 3.7
How do you handle multiple "returned" values from an imported function after being called? Is there a way to set the return values to variables?
File = 'Func_File'
In 'Func_File':
def how():
x = x
y = y
z = z
return x, y z
So now I import the function from 'func_file' to the script i'm using it on.
From func_file import how
When I call how(), how can I show the returned values individually?
a, b, c = how ()
print (a)
print (b)
print (c)

Python partial derivative

I am trying to put numbers in a function that has partial derivatives but I can't find a correct way to do it,I have searched all the internet and I always get an error.Here is the code:
from sympy import symbols,diff
import sympy as sp
import numpy as np
from scipy.misc import derivative
a, b, c, d, e, g, h, x= symbols('a b c d e g h x', real=True)
da=0.1
db=0.2
dc=0.05
dd=0
de=0
dg=0
dh=0
f = 4*a*b+a*sp.sin(c)+a**3+c**8*b
x = sp.sqrt(pow(diff(f, a)*da, 2)+pow(diff(f, b)*db, 2)+pow(diff(f, c)*dc, 2))
def F(a, b, c):
return x
print(derivative(F(2 ,3 ,5)))
I get the following error: derivative() missing 1 required positional argument: 'x0'
I am new to python so maybe it's a stupid question but I would feel grateful if someone helped me.
You can find three partial derivatives of function foo by variables a, b and c at the point (2,3,5):
f = 4*a*b+a*sp.sin(c)+a**3+c**8*b
foo = sp.sqrt(pow(diff(f, a)*da, 2)+pow(diff(f, b)*db, 2)+pow(diff(f, c)*dc, 2))
foo_da = diff(foo, a)
foo_db = diff(foo, b)
foo_dc = diff(foo, c)
print(foo_da," = ", float(foo_da.subs({a:2, b:3, c:5})))
print(foo_db," = ", float(foo_db.subs({a:2, b:3, c:5})))
print(foo_dc," = ", float(foo_dc.subs({a:2, b:3, c:5})))
I have used a python package 'sympy' to perform the partial derivative. The point at which the partial derivative is to be evaluated is val. The argument 'val' can be passed as a list or tuple.
# Sympy implementation to return the derivative of a function in x,y
# Enter ginput as a string expression in x and y and val as 1x2 array
def partial_derivative_x_y(ginput,der_var,val):
import sympy as sp
x,y = sp.symbols('x y')
function = lambda x,y: ginput
derivative_x = sp.lambdify((x,y),sp.diff(function(x,y),x))
derivative_y = sp.lambdify((x,y),sp.diff(function(x,y),y))
if der_var == 'x' :
return derivative_x(val[0],val[1])
if der_var == 'y' :
return derivative_y(val[0],val[1])
input1 = 'x*y**2 + 5*log(x*y +x**7) + 99'
partial_derivative_x_y(input1,'y',(3,1))

How to append a string at the beginning to every tuple within a list?

tuple_list = [('1','2'),('2','3'),('2','6')]
string = Point
Desired_List = [Point('1','2'),Point('2','3'),Point('2','6')]
I have tried the following code:
for x in tuple_list:
x.append("Point")
for x in tuple_list:
x + 'Point'
How to append a string at the beginning to every tuple within a list?
Updates for your info, I have 2 columns and hundreds of rows in csv file of x and y points:
x y
1 3
2 4
I want to get that as:
Points = [Point(1,3),Point(2,4),......]
If strings are all you need, this is the way to go :
desired_list = []
for x,y in tuple_list:
desired_list.append(f"Point({x},{y})")
Which produces the following output :
>>> print(desired_list)
['Point(1,2)', 'Point(2,3)', 'Point(2,6)']
As far as named tuples are concerned, you'd do it as follows :
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
tuple_list = [('1','2'),('2','3'),('2','6')]
desired_list = []
for x,y in tuple_list:
desired_list.append(Point(x, y))
And the corresponding result is :
>>> print(desired_list)
[Point(x='1', y='2'), Point(x='2', y='3'), Point(x='2', y='6')]

Resources