def main():
    a = [1, 2, 3]
    b = ["a", "b", "c"]

    print("a =", a)
    print("b =", b)

    print("\nConstructive:")
    print("  concat(a, b)", operator.concat(a, b))

    print("\nSearching:")
    print("  contains(a, 1)  :", operator.contains(a, 1))
    print("  contains(b, 'd'):", operator.contains(b, "d"))
    print("  countOf(a, 1)   :", operator.countOf(a, 1))
    print("  countOf(b, 'd') :", operator.countOf(b, "d"))
    print("  indexOf(a, 1)   :", operator.indexOf(a, 1))

    print("\nAccess Items:")
    print("  getitem(b, 1)                  :", operator.getitem(b, 1))
    print("  getitem(b, slice(1, 3))        :",
          operator.getitem(b, slice(1, 3)))
    print("  setitem(b, 1, 'd')             :", end=" ")
    operator.setitem(b, 1, "d")
    print(b)
    print("  setitem(a, slice(1, 3), [4,5]):", end=" ")
    operator.setitem(a, slice(1, 3), [4, 5])
    print(a)

    print("\nDestructive:")
    print("  delitem(b, 1)          :", end=" ")
    operator.delitem(b, 1)
    print(b)
    print("  delitem(a, slice(1, 3)):", end=" ")
    operator.delitem(a, slice(1, 3))
    print(a)
示例#2
0
def run301_04():
    """
    sequence ops
    :return:
    """
    a = [1, 2, 3]
    b = ['a', 'b', 'c']

    print('a=', a)
    print('b=', b)

    print('Constructive:')
    print('concat(a,b): ', concat(a, b))

    print('\nSearching:')
    print('contains(a,1):', contains(a, 1))
    print('contains(b,"d"):', contains(b, 'd'))
    print('countOf(a,1):', countOf(a, 1))
    print('countOf(b,"d"):', countOf(b, 'd'))
    print('indexOf(a,1):', indexOf(a, 1))
    # print('indexOf(a,5):', indexOf(a, 5)) # ValueError

    print('\nAccess Items:')
    print('getitem(b,1):', getitem(b, 1))
    print('getitem(b,slice(1,3)):', getitem(b, slice(1, 3)))
    print('setitem(b,1,"d"):', setitem(b, 1, 'd'))
    print(b)
    print('setitem(a,slice(1,3),[4,5]):', setitem(a, slice(1, 3), [4, 5]))
    print(a)

    print('\nDestructive:')
    print('delitem(b,1)', delitem(b, 1))
    print(b)
    print('delitem(a,slice(1,3))', delitem(b, slice(1, 3)))
    print(a)
    def test_countOf(self):
        from operator import countOf
        self.assertEqual(countOf([1,2,2,3,2,5], 2), 3)
        self.assertEqual(countOf((1,2,2,3,2,5), 2), 3)
        self.assertEqual(countOf("122325", "2"), 3)
        self.assertEqual(countOf("122325", "6"), 0)

        self.assertRaises(TypeError, countOf, 42, 1)
        self.assertRaises(TypeError, countOf, countOf, countOf)

        d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
        for k in d:
            self.assertEqual(countOf(d, k), 1)
        self.assertEqual(countOf(d.values(), 3), 3)
        self.assertEqual(countOf(d.values(), 2j), 1)
        self.assertEqual(countOf(d.values(), 1j), 0)

        f = open(TESTFN, "w")
        try:
            f.write("a\n" "b\n" "c\n" "b\n")
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            for letter, count in ("a", 1), ("b", 2), ("c", 1), ("d", 0):
                f.seek(0, 0)
                self.assertEqual(countOf(f, letter + "\n"), count)
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
示例#4
0
 def test_countOf(self):
     from operator import countOf
     self.assertEqual(countOf([1, 2, 2, 3, 2, 5], 2), 3)
     self.assertEqual(countOf((1, 2, 2, 3, 2, 5), 2), 3)
     self.assertEqual(countOf('122325', '2'), 3)
     self.assertEqual(countOf('122325', '6'), 0)
     self.assertRaises(TypeError, countOf, 42, 1)
     self.assertRaises(TypeError, countOf, countOf, countOf)
     d = {'one': 3, 'two': 3, 'three': 3, (1j): 2j}
     for k in d:
         self.assertEqual(countOf(d, k), 1)
     self.assertEqual(countOf(d.values(), 3), 3)
     self.assertEqual(countOf(d.values(), 2j), 1)
     self.assertEqual(countOf(d.values(), 1j), 0)
     f = open(TESTFN, 'w')
     try:
         f.write('a\nb\nc\nb\n')
     finally:
         f.close()
     f = open(TESTFN, 'r')
     try:
         for letter, count in (('a', 1), ('b', 2), ('c', 1), ('d', 0)):
             f.seek(0, 0)
             self.assertEqual(countOf(f, letter + '\n'), count)
     finally:
         f.close()
         try:
             unlink(TESTFN)
         except OSError:
             pass
示例#5
0
    def test_countOf(self):
        from operator import countOf
        self.assertEqual(countOf([1, 2, 2, 3, 2, 5], 2), 3)
        self.assertEqual(countOf((1, 2, 2, 3, 2, 5), 2), 3)
        self.assertEqual(countOf("122325", "2"), 3)
        self.assertEqual(countOf("122325", "6"), 0)

        self.assertRaises(TypeError, countOf, 42, 1)
        self.assertRaises(TypeError, countOf, countOf, countOf)

        d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
        for k in d:
            self.assertEqual(countOf(d, k), 1)
        self.assertEqual(countOf(d.values(), 3), 3)
        self.assertEqual(countOf(d.values(), 2j), 1)
        self.assertEqual(countOf(d.values(), 1j), 0)

        f = open(TESTFN, "w")
        try:
            f.write("a\n" "b\n" "c\n" "b\n")
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            for letter, count in ("a", 1), ("b", 2), ("c", 1), ("d", 0):
                f.seek(0, 0)
                self.assertEqual(countOf(f, letter + "\n"), count)
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
示例#6
0
def TuringClassInformationValueWoEMetrics(
        data_frame: '<class pandas.core.frame.DataFrame>',
        target: str,
        variables: list,
        missing: str = 'missing'
) -> ('<class pandas.core.frame.DataFrame>', list):
    """
    :param data_frame:  initial data frame
    :param target:      target variable contained in the data_frame parameter
    :param variables:   list of variables contained in the data_frame parameter
    :param missing:     Value to be inserted in categories with no values
    :return[0]:         data frame of Weight of Evidence (WoE)
    :return[1]:         list of tuples of Information Value (IV)
    """

    from operator import countOf
    import numpy as np
    import pandas as pd

    if len(data_frame[target].unique()) > 2:
        raise Exception('Your target is not binary, please check')

    qtd_all_targets = [countOf(data_frame[target], x) for x in range(0, 2)]
    df_woe = pd.DataFrame(columns=['Variavel', 'Categoria', 'WoE'])
    lst_iv = list()
    index = 0

    for variable in variables:
        data_frame[variable] = [
            missing if pd.isna(x) else x for x in data_frame[variable]
        ]
        iv = 0

        for category in data_frame[variable].unique():
            df_aux = data_frame[data_frame[variable] == category]

            try:
                goods, bads = [
                    (countOf(df_aux[target], x)) / qtd_all_targets[x]
                    for x in range(0, 2)
                ]
                woe = np.log(goods / bads)
            except ZeroDivisionError:
                print('division by zero occurred, please check your target')
            else:
                df_woe.loc[index] = [variable, category, woe]
                iv = iv + woe * (goods - bads)
            index += 1
        lst_iv.append((variable, round(iv, 10)))

    df_woe.sort_values(by=['Variavel', 'WoE'], ascending=True, inplace=True)
    df_woe = df_woe.reset_index(drop=True)

    return df_woe, lst_iv
示例#7
0
    def test_countOf(self):
        from operator import countOf
        self.assertEqual(countOf([1,2,2,3,2,5], 2), 3)
        self.assertEqual(countOf((1,2,2,3,2,5), 2), 3)
        self.assertEqual(countOf("122325", "2"), 3)
        self.assertEqual(countOf("122325", "6"), 0)

        self.assertRaises(TypeError, countOf, 42, 1)
        self.assertRaises(TypeError, countOf, countOf, countOf)

        d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
        for k in d:
            self.assertEqual(countOf(d, k), 1)
示例#8
0
    def test_countOf(self):
        from operator import countOf
        self.assertEqual(countOf([1, 2, 2, 3, 2, 5], 2), 3)
        self.assertEqual(countOf((1, 2, 2, 3, 2, 5), 2), 3)
        self.assertEqual(countOf("122325", "2"), 3)
        self.assertEqual(countOf("122325", "6"), 0)

        self.assertRaises(TypeError, countOf, 42, 1)
        self.assertRaises(TypeError, countOf, countOf, countOf)

        d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
        for k in d:
            self.assertEqual(countOf(d, k), 1)
示例#9
0
    def count_vertices(self):
        """Counts the numbers of vertices of each valency in a justgraph.

        INPUT: A justgraph

        OUTPUT: A list of non-negative integers

        Note that the first entry in the list is the number of vertices of
        valency zero and so will always be zero. The second entry is the
        number of vertices of valency one and so will almost always be zero.
        The last entry is the number of vertices of maximum valency.

        EXAMPLES:

        >>> justgraph.polygon(4).count_vertices()
        [0, 0, 0, 4]

        >>> f=justgraph.vertex(4)
        >>> g=justgraph.vertex(3)
        >>> r=f.get_bd()[:2]
        >>> s=g.get_bd()[:2]
        >>> h=join(f,g,r,s)
        >>> h.count_vertices()
        [0, 0, 0, 1, 1]

        """
        v = [ len(a) for a in self.vertices ]
        #return [ len([ 0 for a in v if a == i ]) for i in range(max(v)+1) ]
        return [ countOf(v,i) for i in range(max(v)+1) ]
def cfg2bf(g, n):
  """Converts a CFG to a boolean function with n variables
  Input: the set of tuples, an integer
  Output: a boolean function as string like this: A B' + C"""
  d = dict()  # for determining the kind of a non-terminal
  for p in g:
    if p[0] not in d:
      d[p[0]] = set()
    if len(p) == 2:
      d[p[0]].add(p[1])
  implicants = set()
  for s in allSentences(g, n):
    if all(v in d and d[v] for v in s):
      i = tuple(3 if d[v] == {'0', '1'} \
        else (1 if '1' in d[v] else 0) for v in s)
      implicants.add(i)
  sortkey = lambda i: countOf(i, 3)
  t = sorted(implicants, key=sortkey)
  ino = len(implicants)
  for j in xrange(ino-1):
    for k in xrange(j+1, ino):
      if all(a == 3 or a == b for (a, b) in zip(t[k], t[j])):
        implicants.remove(t[j])
        break
  return " + ".join(map(i2str, implicants))
def cfg2bf(g, n):
    """Converts a CFG to a boolean function with n variables
  Input: the set of tuples, an integer
  Output: a boolean function as string like this: A B' + C"""
    d = dict()  # for determining the kind of a non-terminal
    for p in g:
        if p[0] not in d:
            d[p[0]] = set()
        if len(p) == 2:
            d[p[0]].add(p[1])
    implicants = set()
    for s in allSentences(g, n):
        if all(v in d and d[v] for v in s):
            i = tuple(3 if d[v] == {'0', '1'} \
              else (1 if '1' in d[v] else 0) for v in s)
            implicants.add(i)
    sortkey = lambda i: countOf(i, 3)
    t = sorted(implicants, key=sortkey)
    ino = len(implicants)
    for j in xrange(ino - 1):
        for k in xrange(j + 1, ino):
            if all(a == 3 or a == b for (a, b) in zip(t[k], t[j])):
                implicants.remove(t[j])
                break
    return " + ".join(map(i2str, implicants))
示例#12
0
 def test_exports__unique(self):
     """Test that __all__ contains unique names."""
     exports = callee.__all__
     export_set = set(exports)
     repeats = [name for name in export_set if countOf(exports, name) > 1]
     self.assertEmpty(repeats,
                      msg="callee.__all__ contains repeated entries: %s" %
                      repeats)
示例#13
0
文件: test_all.py 项目: Xion/callee
 def test_exports__unique(self):
     """Test that __all__ contains unique names."""
     exports = callee.__all__
     export_set = set(exports)
     repeats = [name for name in export_set if countOf(exports, name) > 1]
     self.assertEmpty(
         repeats,
         msg="callee.__all__ contains repeated entries: %s" % repeats)
示例#14
0
def count(values): 
    """Count Unique Values
    
    Example:
    >>> count(['red', 'green', 'red', 'blue'])
    '1 blue, 1 green, 2 red'
    """
    return ', '.join(str(countOf(values, x)) + ' ' + str(x) 
            for x in sorted(set(values)))
示例#15
0
def operator_sequence_operation():
    """
    we do some sequence operation like following.
    ---CRUD---
    container :: in, append, extend, clear, remove, __new__, __eq__
    sized     :: len, index
    iterable  :: set, get
    """
    a = [1, 2, 3]
    b = list('abc')
    print('a =', a)
    print('b =', b)

    # concatenate
    print('\nConstructive:')
    print('  concat(a, b):', operator.concat(a, b))

    # search
    print('\nSearch:')
    print('  contains(a, 1)  :', operator.contains(a, 1))
    print('  contains(b, "d"):', operator.contains(b, "d"))
    print('  countOf(a, 1)   :', operator.countOf(a, 1))
    print('  countOf(b, "d") :', operator.countOf(b, "d"))
    print('  indexOf(a, 1)   :', operator.indexOf(a, 1))
    # access items
    print('\nAccess:')
    print('  getitem(b, 1)                   :', operator.getitem(b, 1))
    print('  getitem(b, slice(1, 3))         :',
          operator.getitem(b, slice(1, 3)))
    print('  setitem(b, 1, "d")              :', end=' ')
    operator.setitem(b, 1, "d")
    print(b)
    print('  setitem(a, slice(1, 3), [4, 5]) :', end=' ')
    operator.setitem(a, slice(1, 3), [4, 5])
    print(a)
    # remove items
    print('\nDestructive:')
    print('  delitem(b, 1)                   :', end=' ')
    operator.delitem(b, 1)
    print(b)
    print('  delitem(a, slice(1, 3))         :', end=' ')
    operator.delitem(a, slice(1, 3))
    print(a)
示例#16
0
    def test_countOf(self):
        from operator import countOf
        with self.nohtyPCheck(enabled=False):
            self.assertEqual(countOf(yp_list([1, 2, 2, 3, 2, 5]), 2), 3)
            self.assertEqual(countOf(yp_tuple((1, 2, 2, 3, 2, 5)), 2), 3)
            self.assertEqual(countOf(yp_str("122325"), "2"), 3)
            self.assertEqual(countOf(yp_str("122325"), "6"), 0)

            self.assertRaises(TypeError, countOf, yp_int(42), 1)
            self.assertRaises(TypeError, countOf, yp_func_chr, yp_func_chr)

            d = yp_dict({"one": 3, "two": 3, "three": 3, 1.1: 2.2})
            for k in d:
                self.assertEqual(countOf(d, k), 1)
            self.assertEqual(countOf(d.values(), 3), 3)
            self.assertEqual(countOf(d.values(), 2.2), 1)
            self.assertEqual(countOf(d.values(), 1.1), 0)
示例#17
0
def ftch_asp(url_string):
	r = requests.get(url_string)
	type(r)
	html = r.text
	soup = BeautifulSoup(html, "html5lib")
	type(soup)
	text = soup.get_text()	
	words = word_tokenize(text)	
	word_freq = []	
	count = 0
	for s in ph_word9:
		t = ph_word0[count]
		count += 1
		n = operator.countOf(words, s)
		if n > 0:
			word_freq.append([t])
			word_freq.append([n])		
	return url_string,buf_word,word_freq	
示例#18
0
文件: operator.py 项目: suned/pfun
def count_of(elem: A, container: Container[A]) -> int:
    """
    Return count of how many times `elem` appears in `container`. \
    Note that the order of arguments are flipped comparet to the builtins \
    `operator` module

    Example:
        >>> count_of(2)([1, 2, 3])
        1

    Args:
        elem: left element of `in` expression
        container: right element of `in` expression

    Return:
        `elem in container`
    """
    return operator.countOf(container, elem)
示例#19
0
 def test_countOf_file(self):
     f = open(TESTFN, "w", encoding="utf-8")
     try:
         f.write("a\n" "b\n" "c\n" "b\n")
     finally:
         f.close()
     f = open(TESTFN, "r", encoding="utf-8")
     try:
         for letter, count in yp_tuple(
             (("a", 1), ("b", 2), ("c", 1), ("d", 0))):
             f.seek(0, 0)
             self.assertEqual(countOf(f, letter + "\n"), count)
     finally:
         f.close()
         try:
             unlink(TESTFN)
         except OSError:
             pass
示例#20
0
def ftch_ece(url_string):
	r = requests.get(url_string)
	type(r)
	html = r.text
	soup = BeautifulSoup(html, "html5lib")
	type(soup)
	text = soup.get_text()
	words = re.findall('\w+', text)
	sw = nltk.corpus.stopwords.words('english')
	words_ns = []
	for word in words:
		if word not in sw:
			words_ns.append(word.lower())
	word_freq = []
	for w in ph_word0:
		n = operator.countOf(words_ns, w)
		if n > 0:
			word_freq.append([w])
			word_freq.append([n])	
	
	return url,buf_word,word_freq
示例#21
0
    def searchImages(self, query: str, limit: 50) -> List[str]:
        """
        Returns a list of images corresponding to the query.
        Breaks down the query to compute a score depending
        on the keywords previously computed.

        Args:
            query (str): The query string
            limit (int): The maximum number of images to return

        Returns:
            [{"id": str, "filename": str, "extension": str}]:
                A list of images corresponding to the query.
        """
        ranking = {}
        ranking_sorted = []
        ranking_sorted_returned = []

        # Browse each file keywords and compute their matching
        # score for the search query submitted.
        for key in range(0, len(self.keywords_images[0])):
            score = 0
            keywords = self.keywords_images[0][key]
            file_hash = self.keywords_images[1][key]["id"]
            query_tokens = query.split(' ')
            for query_token in query_tokens:
                score += countOf(keywords, query_token)
                score += keywords[len(keywords) - 1].count(query_token)
            if (score > 0):
                ranking[file_hash] = (ranking[file_hash] + score) if (file_hash in ranking) else score

        # If match are found, sort them by score
        if (len(ranking) > 0):
            ranking_sorted = sorted(ranking, key=ranking.__getitem__, reverse=True)
            nb_processed = 0
            while (nb_processed < limit and nb_processed < len(ranking_sorted)):
                returned_data = self.images_data[ranking_sorted[nb_processed]]
                ranking_sorted_returned.append(self.filterImageData(returned_data))
                nb_processed+=1
        return ranking_sorted_returned
示例#22
0
        chain_info.write("Expressions by decreasing log posterior\n")
        for lp in decreasing_lps:
            chain_info.write(f'lp = {lp} [{len(lps_to_exps[lp])} exps]:\n')
            for exp in lps_to_exps[lp]:
                chain_info.write(f'    {exp}\n')
            chain_info.write('\n')
        chain_info.write('\n')

    all_exps = set(itertools.chain(*exps_in_chains))
    chain_info.write(f'Total num. distinct exps across all chains (including warm-up): {len(all_exps)}\n')

    with open("params.yaml", 'r') as fd:
        params = yaml.safe_load(fd)
    true_norm_exp = params['true_norm']['exp']
    true_norm_tuple = to_tuple(true_norm_exp)
    
    chain_info.write(f'True norm in some chain(s): {true_norm_tuple in all_exps}\n')

    num_chains_in_to_exps = defaultdict(set)
    for exp in all_exps:
        num_chains_in = operator.countOf(map(operator.contains, 
                                                exps_in_chains,
                                                (exp for _ in range(len(exps_in_chains)))
                                            ),
                                        True)
        num_chains_in_to_exps[num_chains_in].add(exp)
    for num in sorted(num_chains_in_to_exps.keys(), reverse=True):
        chain_info.write(f'Out of {len(exps_in_chains)} chains ...\n')
        chain_info.write(f'{len(num_chains_in_to_exps[num])} exps are in {num} chains.\n')

    
示例#23
0
#是否包含,同样是序列
print operator.contains([1,2,3],2)
print operator.contains([1,2,3],0)

#包含位置,同样是序列
print operator.indexOf([1,2,3],2)
#如果没有,则会抛出一个异常
# print operator.indexOf([1,2,3],0)

#包含 同 in
print operator.sequenceIncludes([1,2,3],1)
print operator.sequenceIncludes("123","1")

#计数,计算某个值在序列中出现的次数
print operator.countOf([1,2,1,3,1],1)
#set序列可以去重
print operator.countOf(set([1,2,1,3,1]),1)

#变量的值 同__index__()
a = 12
print operator.index(a)

#删除字典中的某对数值 同del a[b]
a = {0:"zero",1:"one",2:"two"}
operator.delitem(a,0)
print a

#删除序列中的某片数值 同del a[b:c]
a = [1,2,3,4,5]
operator.delslice(a,0,1)
示例#24
0
import operator
示例#25
0
	判断对象类型:
			isMappingType:
			isNumberType:
			isSequenceType:
"""

import operator

a = [1, 2, 3]
b = ['a', 'b', 'c']

print operator.concat(a,b)
print operator.repeat(b, 3)
print operator.contains(a, 2)
print operator.contains(b, 'hhhhhh')
print operator.countOf(operator.repeat(b, 4), 'a')
print operator.countOf(a, 8)
print operator.indexOf(a, 2)
# output
# [1, 2, 3, 'a', 'b', 'c']
# ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
# True
# False
# 4
# 0
# 1

c = [1, 'a', None, 10.01, {'key':'value'}]


# 通过下标操作序列
示例#26
0
# Test iterators.
示例#27
0
 def test_countOf(self):
     self.assertRaises(TypeError, operator.countOf)
     self.assertRaises(TypeError, operator.countOf, None, None)
     self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
     self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
示例#28
0
文件: second.py 项目: tegla/solutions
import input
import operator


def matches(l):
    return (l.password[l.min - 1] == l.letter) != (l.password[l.max - 1]
                                                   == l.letter)


print(operator.countOf([matches(l) for l in input.ls], True))
 def test_countOf(self):
     self.failUnlessRaises(TypeError, operator.countOf)
     self.failUnlessRaises(TypeError, operator.countOf, None, None)
     self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
     self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
示例#30
0
 def test_countOf(self):
     self.assertRaises(TypeError, operator.countOf)
     self.assertRaises(TypeError, operator.countOf, None, None)
     self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
     self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
示例#31
0
    def test_contains(self):
        nan = float('nan')
        nan2 = float('nan')

        # lists

        l = [nan]
        self.assertTrue(nan in l)
        self.assertTrue(nan2 not in l)
        self.assertTrue(l == [nan])
        self.assertTrue(l.index(nan) == 0)
        self.assertTrue(l.count(nan) == 1)

        if is_cli:
            self.assertTrue(l.IndexOf(nan) == 0)

        # tuples

        t = (nan, )
        self.assertTrue(nan in t)
        self.assertTrue(nan2 not in t)
        self.assertTrue(t == (nan, ))
        self.assertTrue(t.index(nan) == 0)
        self.assertTrue(t.count(nan) == 1)

        if is_cli:
            self.assertTrue(l.IndexOf(nan) == 0)

        # sets

        s = {nan}
        self.assertTrue(nan in s)
        self.assertTrue(nan2 not in s)
        self.assertTrue(s == {nan})
        s.add(nan)
        self.assertTrue(len(s) == 1)
        s.remove(nan)
        s.add(nan)
        s.discard(nan)
        self.assertTrue(len(s) == 0)
        s.add(nan)
        s.symmetric_difference_update({nan})
        self.assertTrue(len(s) == 0)

        # dictionaries

        d = {nan: nan2}
        self.assertTrue(nan in d)
        self.assertTrue(nan2 not in d)
        self.assertTrue(d == {nan: nan2})
        self.assertTrue((nan, nan2) in d.items())
        self.assertTrue(nan in d.keys())
        self.assertTrue(nan2 in d.values())

        if is_cli:
            from System.Collections.Generic import Dictionary, KeyValuePair
            d2 = Dictionary[object, object]()
            d2.Add(nan, nan2)
            self.assertTrue(d == d2)

            self.assertTrue(d.Contains(KeyValuePair[object, object](nan,
                                                                    nan2)))

        # deque

        from _collections import deque

        q = deque([nan])
        self.assertTrue(nan in q)
        self.assertTrue(nan2 not in q)
        self.assertTrue(q == deque([nan]))
        q.remove(nan)
        self.assertTrue(len(q) == 0)

        # operator

        import operator

        self.assertTrue(operator.contains([nan], nan))
        self.assertTrue(operator.indexOf([nan], nan) == 0)
        self.assertTrue(operator.countOf([nan], nan) == 1)
示例#32
0
文件: array.py 项目: alkorzt/pypy
 def count(self, x):
     """Return number of occurences of x in the array."""
     return operator.countOf(self, x)
示例#33
0
 def count(self, arg):
     """ Return a counter of some argument inside a sequence.
     """
     return lambda x: operator.countOf(self(x), arg), ('count', arg)
示例#34
0
def countOf(a, b):
    return operator.countOf(a, b)
示例#35
0
import numpy as np
import operator
from pylab import *

nodes = np.genfromtxt("nodes.csv", dtype=str, delimiter=',', skip_header=1,
                     usecols=(2))


counter = operator.countOf(nodes, 'male')
male = (counter *100) / len(nodes)
female = 100 - male
print(female)

figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Male', 'Female'
fracs = [male,female]
explode=(0, 0.05)

pie(fracs, explode=explode, labels=labels,
                autopct='%1.1f%%', shadow=True, startangle=90)
             
title('Male to Female Ratio', bbox={'facecolor':'0.8', 'pad':5})

show()
示例#36
0
links = np.genfromtxt("links.csv", dtype=str, delimiter=',', skip_header=1,
                     usecols=(0,1))

dic = {}
#Node Degree
for n in sorted(np.reshape(links,558)):

    if n not in dic:
        dic[n] = 1
    else:
        dic[n] += 1
    
size = len(dic)

#Centrality
sort = sorted(dic.items(), key=lambda x: x[1], reverse=True)

plt.bar(range(size),list(dic.values()))
plt.xticks(range(size), list(dic.keys()), rotation=90)
plt.show()


#Histogram
histogram = {}

for n in range(26):
    histogram[n] = operator.countOf(list(dic.values()), n)

plt.plot(range(26),list(histogram.values()))
plt.show()
示例#37
0
    phword.append(row['telugu'])

for index, row in en_data.iterrows():
    enword.append(row['english'])

for link in soup.select("a[href$='.aspx']"):
    url2 = link.get('href')
    result = urlparse(url2)

    if all([result.scheme, result.netloc]):
        r = requests.get(url2)
        type(r)

        html = r.text
        soup = BeautifulSoup(html, "html5lib")
        type(soup)
        text = soup.get_text()
        words = word_tokenize(text)

        word_freq = []
        count = 0
        for s in phword:
            t = enword[count]
            count = count + 1
            n = operator.countOf(words, s)
            if n > 0:
                word_freq.append([t])
                word_freq.append([n])

        print(url2, '	frequency=	', word_freq)
示例#38
0
# Test iterators.
 def test_countOf(self):
     self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
     self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
示例#40
0
 def test_error_message_module_function(self):
     import operator  # use countOf because it's defined at applevel
     exc = raises(TypeError, lambda: operator.countOf(1, 2, 3))
     # does not contain the warning
     # 'Did you forget 'self' in the function definition?'
     assert 'self' not in str(exc.value)
示例#41
0
 def get_all_same(arr):
     if not arr: return (False, None)
     import operator
     val = arr[0]
     return (len(arr) == operator.countOf(arr,val), val)
示例#42
0
 def test_countOf(self):
     self.failUnlessRaises(TypeError, operator.countOf)
     self.failUnlessRaises(TypeError, operator.countOf, None, None)
     self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
     self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
示例#43
0
def lst_ope():
    lst = [1, 2, 3]
    print operator.indexOf(lst, 2)
    # 1
    lst1 = [1, 2, 3, 2]
    print operator.countOf(lst1, 2)
示例#44
0
文件: t505.py 项目: Afey/skulpt
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9]
s = "hello world"
t = ("a", "b", "c")
d = {1:1, 2:2, 3:3, 4:4, 5:5}

print operator.contains(l, 2)
print operator.contains(l, 30)
print operator.contains(s, "ll")
print operator.contains(s, "z")
print operator.contains(t, "a")
print operator.contains(t, 2)
print operator.contains(d, 3)
print operator.contains(d, 0)

print operator.countOf(l, 9)
print operator.countOf(l, 30)
print operator.countOf(s, "l")
print operator.countOf(t, "a")

operator.delitem(l, 9)
print l

operator.delitem(l, 0)
print l

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9]
s = "hello world"
t = ("a", "b", "c")
d = {1:1, 2:2, 3:3, 4:4, 5:5}
示例#45
0
 def __eq__(self, other):
     try:
         return _operator.countOf(other, self.item) == self.count
     except TypeError:
         return NotImplemented
示例#46
0
文件: second.py 项目: tegla/solutions
def trees(right,down):
    return operator.countOf(input.m.slope(right=right,down=down), '#')
示例#47
0
 def __eq__(self, other):
     return _operator.countOf(self.conditions, other) == 1
示例#48
0
 def operator_countOf(size, fill_value, b):
     a = Array(size, 'int64')
     for i in range(size):
         a[i] = fill_value
     return operator.countOf(a, b)
示例#49
0
import numpy as np
import operator
from pylab import *

nodes = np.genfromtxt("nodes.csv",
                      dtype=str,
                      delimiter=',',
                      skip_header=1,
                      usecols=(2))

counter = operator.countOf(nodes, 'male')
male = (counter * 100) / len(nodes)
female = 100 - male
print(female)

figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Male', 'Female'
fracs = [male, female]
explode = (0, 0.05)

pie(fracs,
    explode=explode,
    labels=labels,
    autopct='%1.1f%%',
    shadow=True,
    startangle=90)

title('Male to Female Ratio', bbox={'facecolor': '0.8', 'pad': 5})