How do I use composite strategies in hypothesis (hypothesis.errors.InvalidArgument: Expected SearchStrategy but got function) - python-hypothesis

This example is a variation of the one in the docs:
import hypothesis.strategies as st
from hypothesis import given
#st.composite
def s(draw):
x = draw(st.text(), min_size=1)
y = draw(st.text(alphabet=x))
return (x, y)
#given(s1=s, s2=s)
def test_subtraction(s1, s2):
print(s1, s2)
assert 0
It fails:
E hypothesis.errors.InvalidArgument: Expected SearchStrategy but got <function accept.<locals>.s at 0x7fd7e5c05620> (type=function)
/mnt/work/unfuncat/software/anaconda/lib/python3.6/site-packages/hypothesis/internal/validation.py:40: InvalidArgument
What am I doing wrong?

You need to call the composite functions. This is not explained in the docs, but there is an example in a 2016 blog post.
#given(s1=s(), s2=s()) # <===== change
def test_subtraction(s1, s2):
print(s1, s2)
assert 0

Related

Unable to compare types of identical but redeclared namedtuples in Python

While working on a difference engine to identify differences in very large data structures, I noticed that a type comparison between identical-but-redeclared namedtuples misbehaves. Redeclaring the namedtuples is unavoidable*. Here is a minimal example:
def test_named_tuples_same_type():
from collections import namedtuple
X = namedtuple("X", "x")
a = X(1)
# We are unable to avoid redeclaring X
X = namedtuple("X", "x")
b = X(1)
print(repr(a))
print(repr(b))
# X(x=1)
# X(x=1)
assert isinstance(type(a), type(b)) # fail
assert type(a) == type(b) # fail
The asserts return:
> assert isinstance(type(a), type(b)) # fail
E AssertionError: assert False
E + where False = isinstance(<class 'tests.test_deep_diff.X'>, <class 'tests.test_deep_diff.X'>)
E + where <class 'tests.test_deep_diff.X'> = type(X(x=1))
E + and <class 'tests.test_deep_diff.X'> = type(X(x=1))
and
> assert type(a) == type(b) # fail
E AssertionError: assert <class 'tests.test_deep_diff.X'> == <class 'tests.test_deep_diff.X'>
How to assert the type of both are equal or semantically equal (without str(type()))?
*Redeclaring the namedtuple is unavoidable because it takes place in unmodifiable exec'd code to generate the data structures being diffed.
It isn't entirely clear what you mean by semantically equivalent precisely. But consider:
>>> from collections import namedtuple
>>> X1 = namedtuple("X", "x")
>>> X2 = namedtuple("X", "x")
Then you can use something like:
>>> def equivalent_namedtuple_types(t1, t2):
... return (t1.__name__, t1._fields) == (t2.__name__, t2._fields)
...
>>> equivalent_namedtuple_types(X1, X2)
True
>>>
From your comments, it seems like you may care about the .__module__ attribute as well.

Why its Showing None when it should show Which IP Class it belongs to

import pandas as pd
ecom = pd.read_csv("data science pack\Ecommerce Purchases.csv")
ecom['Class_IP'] = ecom['IP Address'].apply(lambda x:x.split(".")[0])
def ipc(x):
if x in range(0,128):
print("A")
if x in range(128,192):
print("B")
if x in range(192,224):
print('C')
if x in range(224,240):
print("D")
if x in range(240,255):
print("E")
ecom['new_c'] = ecom['Class_IP'].apply(lambda y : ipc(y))
print(ecom['new_c'])
Above is the code. It should print it IP class but it shows None values.
can you please try to pass int(y) instead of y to ipc() method in lambda function as below:
ecom['new_c'] = ecom['Class_IP'].apply(lambda y : ipc(int(y)))
It is returning None because ipc function is expecting int value and you are passing string value to it.
Hope this answer solves your problem.

define a "derivation" function in sympy

I am trying to make a derivation Function in sympy (I am using sympy version 1.4), but I am not sure how. In particular, I am trying to define a general function (that could just take sympy variables, not functions for now) that has the following properties:
d(f+g)=d(f)+d(g)
d(f*g)=f*d(g)+d(f)*g
I have tried reading the sympy documentation on defining Functions but I am not sure how to define a Function class that has the above properties for any two symbols.
For some background/context, I know how to make derivations in Mathematica; I would just type
d[f_+g_]:=d[f]+d[g]
d[f_ g_]:=f d[g] + d[f] g
You can write your own rule. The following might get you started:
def d(e, func):
"""
>>> from sympy import x, y
>>> from sympy import Function
>>> D = Function('D')
>>> d(x + y, D)
D(x) + D(y)
"""
if e.is_Add:
return Add(*[d(a, func) for a in e.args])
elif e.is_Mul:
return Add(*[Mul(*(e.args[:i]+(d(e.args[i],func),)+e.args[i+1:]))
for i in range(len(e.args))])
else:
return func(e)
Or you could try this with a class:
class d(Function):
#classmethod
def eval(cls, e):
if e.is_Add:
return Add(*[d(a) for a in e.args])
elif e.is_Mul:
return Add(*[Mul(*(e.args[:i]+(d(e.args[i]),)+e.args[i+1:]))
for i in range(len(e.args))])
else:
return d(e, evaluate=False)
See also, linapp.

Add two vectors using python's operator overloading feauture

I want to add two vectors with n dimensions using the add method operator overloading . The elements of the 2 vectors will be input by the user. I don't understand how to define the vector as a single object.
In my example code vectors s1 and s2 have 2 defined values.I want the vectors to take input from the user having N dimensions and then add them using class and the add method.I can do it using only functions without using class and object but it is for a homework and the use of class is required.For example :
s1 = [float(x) for x in input().split()]
s2= [float(x) for x in input().split()]
s3=s1+s2
I am clueless on what to do and any help will be appreciated.
class Student :
def __init__(self,m1,m2) :
self.m1=m1
self.m2=m2
def __add__(self,other) :
m1=self.m1+other.m1
m2=self.m2+other.m2
s3=Student(m1,m2)
return s3
s1=Student(58,69)
s2=Student(60,65)
s3=s1+s2
print(s3.m1,s3.m2)
If you are allowed to use numpy following solution will work:
import numpy as np
x = np.array([float(x) for x in "1 2 3".split()])
y = np.array([float(x) for x in "3 4 5".split()])
print(x)
# [1. 2. 3.]
print(y)
# [3. 4. 5.]
print(x+y)
# [4. 6. 8.]
class Student:
def __init__(self, data):
self.data = data
def __add__(self, other):
return Student(self.data+other.data)
student_x = Student(x)
student_y = Student(y)
print((student_x+student_y).data)
# [4. 6. 8.]

Set partition with fixed size

I need to find the set partition with fixed size blocks. For example set S=(1,2,3,4,5,6,7) and I want to partition it as block of (4,2,1). The answers are
([1,2,3,4][5,6][7])
([2,3,4,5][6,7][1])
([1,4,5,6][2,3][7])
.....................
.....................
Anybody knows how to solve it in Python easily. Please give some clue
You have to permute your table in 7*6*5*4*3*2*1 ways and then each table cut into parts.
For example:
def permute(table):
return [[],[],[],[],...]//table of permuted tables
def cut_into_parts(lengths_list, table):
rlist = []
for i in lengths_list[:-1]:
rlist.append(table[:-len(table) + i])
table = table[i:]
rlist.append(table[:lengths_list[-1]])
return rlist
I hope it is a helpful and easy way to do this.
Try the following function:
from itertools import permutations
def take(l, partition):
if len(partition) == 1:
for p in permutations(l):
yield (p,)
else:
for p in permutations(l,partition[0]):
for t in take([x for x in l if x not in p], partition[1:]):
yield (p,) + t
Then take([1,2,3,4,5,6,7],(4,2,1)) should be what you are looking for.
EDIT: Different solution now I understand the requirements better:
from itertools import permutations
def take(l, partition):
offsets = [0]
for x in partition:
offsets.append(offsets[-1]+x)
for p in permutations(l):
yield frozenset([frozenset(p[offsets[i]:offsets[i+1]]) for i in range(len(offsets)-1)])
for x in frozenset(take([1,2,3,4,5],(3,1,1))):
print([[z for z in y] for y in x])

Resources