Best Python code snippet using molotov_python
filterSpec.js
Source:filterSpec.js
1'use strict';2describe('Filter: filter', function() {3 var filter;4 beforeEach(inject(function($filter) {5 filter = $filter('filter');6 }));7 it('should filter by string', function() {8 var items = ['MIsKO', {name: 'shyam'}, ['adam'], 1234];9 expect(filter(items, '').length).toBe(4);10 expect(filter(items, undefined).length).toBe(4);11 expect(filter(items, 'iSk').length).toBe(1);12 expect(filter(items, 'isk')[0]).toBe('MIsKO');13 expect(filter(items, 'yam').length).toBe(1);14 expect(filter(items, 'yam')[0]).toEqual(items[1]);15 expect(filter(items, 'da').length).toBe(1);16 expect(filter(items, 'da')[0]).toEqual(items[2]);17 expect(filter(items, '34').length).toBe(1);18 expect(filter(items, '34')[0]).toBe(1234);19 expect(filter(items, "I don't exist").length).toBe(0);20 });21 it('should not read $ properties', function() {22 expect(''.charAt(0)).toBe(''); // assumption23 var items = [{$name: 'misko'}];24 expect(filter(items, 'misko').length).toBe(0);25 });26 it('should filter on specific property', function() {27 var items = [{ignore: 'a', name: 'a'}, {ignore: 'a', name: 'abc'}];28 expect(filter(items, {}).length).toBe(2);29 expect(filter(items, {name: 'a'}).length).toBe(2);30 expect(filter(items, {name: 'b'}).length).toBe(1);31 expect(filter(items, {name: 'b'})[0].name).toBe('abc');32 });33 it('should ignore undefined properties of the expression object', function() {34 var items = [{name: 'a'}, {name: 'abc'}];35 expect(filter(items, {name: undefined})).toEqual([{name: 'a'}, {name: 'abc'}]);36 items = [{first: 'misko'}, {deep: {first: 'misko'}}, {deep: {last: 'hevery'}}];37 expect(filter(items, {deep: {first: undefined}})).toEqual([{deep: {first: 'misko'}}, {deep: {last: 'hevery'}}]);38 });39 it('should take function as predicate', function() {40 var items = [{name: 'a'}, {name: 'abc', done: true}];41 expect(filter(items, function(i) {return i.done;}).length).toBe(1);42 });43 it('should pass the index to a function predicate', function() {44 var items = [0, 1, 2, 3];45 var result = filter(items, function(value, index) {46 return index % 2 === 0;47 });48 expect(result).toEqual([0, 2]);49 });50 it('should match primitive array values against top-level `$` property in object expression',51 function() {52 var items, expr;53 items = ['something', 'something else', 'another thing'];54 expr = {$: 'some'};55 expect(filter(items, expr).length).toBe(2);56 expect(filter(items, expr)).toEqual([items[0], items[1]]);57 items = [{val: 'something'}, {val: 'something else'}, {val: 'another thing'}];58 expr = {$: 'some'};59 expect(filter(items, expr).length).toBe(2);60 expect(filter(items, expr)).toEqual([items[0], items[1]]);61 items = [123, 456, 789];62 expr = {$: 1};63 expect(filter(items, expr).length).toBe(1);64 expect(filter(items, expr)).toEqual([items[0]]);65 items = [true, false, 'true'];66 expr = {$: true, ignored: 'false'};67 expect(filter(items, expr).length).toBe(2);68 expect(filter(items, expr)).toEqual([items[0], items[2]]);69 }70 );71 it('should match items with array properties containing one or more matching items', function() {72 var items, expr;73 items = [74 {tags: ['web', 'html', 'css', 'js']},75 {tags: ['hybrid', 'html', 'css', 'js', 'ios', 'android']},76 {tags: ['mobile', 'ios', 'android']}77 ];78 expr = {tags: 'html'};79 expect(filter(items, expr).length).toBe(2);80 expect(filter(items, expr)).toEqual([items[0], items[1]]);81 items = [82 {nums: [1, 345, 12]},83 {nums: [0, 46, 78]},84 {nums: [123, 4, 67]}85 ];86 expr = {nums: 12};87 expect(filter(items, expr).length).toBe(2);88 expect(filter(items, expr)).toEqual([items[0], items[2]]);89 items = [90 {customers: [{name: 'John'}, {name: 'Elena'}, {name: 'Bill'}]},91 {customers: [{name: 'Sam'}, {name: 'Klara'}, {name: 'Bill'}]},92 {customers: [{name: 'Molli'}, {name: 'Elena'}, {name: 'Lora'}]}93 ];94 expr = {customers: {name: 'Bill'}};95 expect(filter(items, expr).length).toBe(2);96 expect(filter(items, expr)).toEqual([items[0], items[1]]);97 }98 );99 it('should take object as predicate', function() {100 var items = [{first: 'misko', last: 'hevery'},101 {first: 'adam', last: 'abrons'}];102 expect(filter(items, {first:'', last:''}).length).toBe(2);103 expect(filter(items, {first:'', last:'hevery'}).length).toBe(1);104 expect(filter(items, {first:'adam', last:'hevery'}).length).toBe(0);105 expect(filter(items, {first:'misko', last:'hevery'}).length).toBe(1);106 expect(filter(items, {first:'misko', last:'hevery'})[0]).toEqual(items[0]);107 });108 it('should support predicate object with dots in the name', function() {109 var items = [{'first.name': 'misko', 'last.name': 'hevery'},110 {'first.name': 'adam', 'last.name': 'abrons'}];111 expect(filter(items, {'first.name':'', 'last.name':''}).length).toBe(2);112 expect(filter(items, {'first.name':'misko', 'last.name':''})).toEqual([items[0]]);113 });114 it('should support deep predicate objects', function() {115 var items = [{person: {name: 'John'}},116 {person: {name: 'Rita'}},117 {person: {name: 'Billy'}},118 {person: {name: 'Joan'}}];119 expect(filter(items, {person: {name: 'Jo'}}).length).toBe(2);120 expect(filter(items, {person: {name: 'Jo'}})).toEqual([121 {person: {name: 'John'}}, {person: {name: 'Joan'}}122 ]);123 });124 it('should support deep expression objects with multiple properties', function() {125 var items = [{person: {name: 'Annet', email: 'annet@example.com'}},126 {person: {name: 'Billy', email: 'me@billy.com'}},127 {person: {name: 'Joan', email: 'joan@example.net'}},128 {person: {name: 'John', email: 'john@example.com'}},129 {person: {name: 'Rita', email: 'rita@example.com'}}];130 var expr = {person: {name: 'Jo', email: '!example.com'}};131 expect(filter(items, expr).length).toBe(1);132 expect(filter(items, expr)).toEqual([items[2]]);133 });134 it('should match any properties for given "$" property', function() {135 var items = [{first: 'tom', last: 'hevery'},136 {first: 'adam', last: 'hevery', alias: 'tom', done: false},137 {first: 'john', last: 'clark', middle: 'tommy'}];138 expect(filter(items, {$: 'tom'}).length).toBe(3);139 expect(filter(items, {$: 'a'}).length).toBe(2);140 expect(filter(items, {$: false}).length).toBe(1);141 expect(filter(items, {$: 10}).length).toBe(0);142 expect(filter(items, {$: 'hevery'})[0]).toEqual(items[0]);143 });144 it('should match any properties in the nested object for given deep "$" property', function() {145 var items = [{person: {name: 'Annet', email: 'annet@example.com'}},146 {person: {name: 'Billy', email: 'me@billy.com'}},147 {person: {name: 'Joan', email: 'joan@example.net'}},148 {person: {name: 'John', email: 'john@example.com'}},149 {person: {name: 'Rita', email: 'rita@example.com'}}];150 var expr = {person: {$: 'net'}};151 expect(filter(items, expr).length).toBe(2);152 expect(filter(items, expr)).toEqual([items[0], items[2]]);153 });154 it('should match named properties only against named properties on the same level', function() {155 var expr = {person: {name: 'John'}};156 var items = [{person: 'John'}, // No match (1 level higher)157 {person: {name: 'John'}}, // Match (same level)158 {person: {name: {first: 'John', last: 'Doe'}}}]; // No match (1 level deeper)159 expect(filter(items, expr).length).toBe(1);160 expect(filter(items, expr)).toEqual([items[1]]);161 });162 it('should match any properties on same or deeper level for given "$" property', function() {163 var items = [{level1: 'test', foo1: 'bar1'},164 {level1: {level2: 'test', foo2:'bar2'}, foo1: 'bar1'},165 {level1: {level2: {level3: 'test', foo3: 'bar3'}, foo2: 'bar2'}, foo1: 'bar1'}];166 expect(filter(items, {$: 'ES'}).length).toBe(3);167 expect(filter(items, {$: 'ES'})).toEqual([items[0], items[1], items[2]]);168 expect(filter(items, {level1: {$: 'ES'}}).length).toBe(2);169 expect(filter(items, {level1: {$: 'ES'}})).toEqual([items[1], items[2]]);170 expect(filter(items, {level1: {level2: {$: 'ES'}}}).length).toBe(1);171 expect(filter(items, {level1: {level2: {$: 'ES'}}})).toEqual([items[2]]);172 });173 it('should respect the nesting level of "$"', function() {174 var items = [{supervisor: 'me', person: {name: 'Annet', email: 'annet@example.com'}},175 {supervisor: 'me', person: {name: 'Billy', email: 'me@billy.com'}},176 {supervisor: 'me', person: {name: 'Joan', email: 'joan@example.net'}},177 {supervisor: 'me', person: {name: 'John', email: 'john@example.com'}},178 {supervisor: 'me', person: {name: 'Rita', email: 'rita@example.com'}}];179 var expr = {$: {$: 'me'}};180 expect(filter(items, expr).length).toBe(1);181 expect(filter(items, expr)).toEqual([items[1]]);182 });183 it('should support boolean properties', function() {184 var items = [{name: 'tom', current: true},185 {name: 'demi', current: false},186 {name: 'sofia'}];187 expect(filter(items, {current:true}).length).toBe(1);188 expect(filter(items, {current:true})[0].name).toBe('tom');189 expect(filter(items, {current:false}).length).toBe(1);190 expect(filter(items, {current:false})[0].name).toBe('demi');191 });192 it('should support negation operator', function() {193 var items = ['misko', 'adam'];194 expect(filter(items, '!isk').length).toBe(1);195 expect(filter(items, '!isk')[0]).toEqual(items[1]);196 });197 it('should ignore function properties in items', function() {198 // Own function properties199 var items = [200 {text: 'hello', func: noop},201 {text: 'goodbye'},202 {text: 'kittens'},203 {text: 'puppies'}204 ];205 var expr = {text: 'hello'};206 expect(filter(items, expr).length).toBe(1);207 expect(filter(items, expr)[0]).toBe(items[0]);208 expect(filter(items, expr, true).length).toBe(1);209 expect(filter(items, expr, true)[0]).toBe(items[0]);210 // Inherited function properties211 function Item(text) {212 this.text = text;213 }214 Item.prototype.func = noop;215 items = [216 new Item('hello'),217 new Item('goodbye'),218 new Item('kittens'),219 new Item('puppies')220 ];221 expect(filter(items, expr).length).toBe(1);222 expect(filter(items, expr)[0]).toBe(items[0]);223 expect(filter(items, expr, true).length).toBe(1);224 expect(filter(items, expr, true)[0]).toBe(items[0]);225 });226 it('should ignore function properties in expression', function() {227 // Own function properties228 var items = [229 {text: 'hello'},230 {text: 'goodbye'},231 {text: 'kittens'},232 {text: 'puppies'}233 ];234 var expr = {text: 'hello', func: noop};235 expect(filter(items, expr).length).toBe(1);236 expect(filter(items, expr)[0]).toBe(items[0]);237 expect(filter(items, expr, true).length).toBe(1);238 expect(filter(items, expr, true)[0]).toBe(items[0]);239 // Inherited function properties240 function Expr(text) {241 this.text = text;242 }243 Expr.prototype.func = noop;244 expr = new Expr('hello');245 expect(filter(items, expr).length).toBe(1);246 expect(filter(items, expr)[0]).toBe(items[0]);247 expect(filter(items, expr, true).length).toBe(1);248 expect(filter(items, expr, true)[0]).toBe(items[0]);249 });250 it('should consider inherited properties in items', function() {251 function Item(text) {252 this.text = text;253 }254 Item.prototype.doubleL = 'maybe';255 var items = [256 new Item('hello'),257 new Item('goodbye'),258 new Item('kittens'),259 new Item('puppies')260 ];261 var expr = {text: 'hello', doubleL: 'perhaps'};262 expect(filter(items, expr).length).toBe(0);263 expect(filter(items, expr, true).length).toBe(0);264 expr = {text: 'hello', doubleL: 'maybe'};265 expect(filter(items, expr).length).toBe(1);266 expect(filter(items, expr)[0]).toBe(items[0]);267 expect(filter(items, expr, true).length).toBe(1);268 expect(filter(items, expr, true)[0]).toBe(items[0]);269 });270 it('should consider inherited properties in expression', function() {271 function Expr(text) {272 this.text = text;273 }274 Expr.prototype.doubleL = true;275 var items = [276 {text: 'hello', doubleL: true},277 {text: 'goodbye'},278 {text: 'kittens'},279 {text: 'puppies'}280 ];281 var expr = new Expr('e');282 expect(filter(items, expr).length).toBe(1);283 expect(filter(items, expr)[0]).toBe(items[0]);284 expr = new Expr('hello');285 expect(filter(items, expr, true).length).toBe(1);286 expect(filter(items, expr)[0]).toBe(items[0]);287 });288 it('should not be affected by `Object.prototype` when using a string expression', function() {289 Object.prototype.someProp = 'oo';290 var items = [291 createMap(),292 createMap(),293 createMap(),294 createMap()295 ];296 items[0].someProp = 'hello';297 items[1].someProp = 'goodbye';298 items[2].someProp = 'kittens';299 items[3].someProp = 'puppies';300 // Affected by `Object.prototype`301 expect(filter(items, {}).length).toBe(1);302 expect(filter(items, {})[0]).toBe(items[1]);303 expect(filter(items, {$: 'll'}).length).toBe(0);304 // Not affected by `Object.prototype`305 expect(filter(items, 'll').length).toBe(1);306 expect(filter(items, 'll')[0]).toBe(items[0]);307 delete Object.prototype.someProp;308 });309 it('should throw an error when is not used with an array', function() {310 var item = {'not': 'array'};311 expect(function() { filter(item, {}); }).312 toThrowMinErr('filter', 'notarray', 'Expected array but received: {"not":"array"}');313 item = Object.create(null);314 expect(function() { filter(item, {}); }).315 toThrowMinErr('filter', 'notarray', 'Expected array but received: {}');316 item = {317 toString: null,318 valueOf: null319 };320 expect(function() { filter(item, {}); }).321 toThrowMinErr('filter', 'notarray', 'Expected array but received: {"toString":null,"valueOf":null}');322 });323 it('should not throw an error if used with an array like object', function() {324 function getArguments() {325 return arguments;326 }327 var argsObj = getArguments({name: 'Misko'}, {name: 'Igor'}, {name: 'Brad'});328 var nodeList = jqLite("<p><span>Misko</span><span>Igor</span><span>Brad</span></p>")[0].childNodes;329 function nodeFilterPredicate(node) {330 return node.innerHTML.indexOf("I") !== -1;331 }332 expect(filter(argsObj, 'i').length).toBe(2);333 expect(filter('abc','b').length).toBe(1);334 expect(filter(nodeList, nodeFilterPredicate).length).toBe(1);335 });336 it('should return undefined when the array is undefined', function() {337 expect(filter(undefined, {})).toBeUndefined();338 });339 it('should return null when the value of the array is null', function() {340 var item = null;341 expect(filter(item, {})).toBe(null);342 });343 it('should not throw an error if property is null when comparing object', function() {344 var items = [345 { office:1, people: {name:'john'}},346 { office:2, people: {name:'jane'}},347 { office:3, people: null}348 ];349 var f = { };350 expect(filter(items, f).length).toBe(3);351 f = { people:null };352 expect(filter(items, f).length).toBe(1);353 f = { people: {}};354 expect(filter(items, f).length).toBe(2);355 f = { people:{ name: '' }};356 expect(filter(items, f).length).toBe(2);357 f = { people:{ name:'john' }};358 expect(filter(items, f).length).toBe(1);359 f = { people:{ name:'j' }};360 expect(filter(items, f).length).toBe(2);361 });362 it('should match `null` against `null` only', function() {363 var items = [364 {value: null},365 {value: undefined},366 {value: true},367 {value: false},368 {value: NaN},369 {value: 42},370 {value: 'null'},371 {value: 'test'},372 {value: {}},373 {value: new Date()}374 ];375 var flt;376 flt = null;377 expect(filter(items, flt).length).toBe(1);378 expect(filter(items, flt)[0]).toBe(items[0]);379 flt = {value: null};380 expect(filter(items, flt).length).toBe(1);381 expect(filter(items, flt)[0]).toBe(items[0]);382 flt = {value: undefined};383 expect(filter(items, flt).length).toBe(items.length);384 flt = {value: NaN};385 expect(includes(filter(items, flt), items[0])).toBeFalsy();386 flt = {value: false};387 expect(includes(filter(items, flt), items[0])).toBeFalsy();388 flt = '';389 expect(includes(filter(items, flt), items[0])).toBeFalsy();390 flt = {value: 'null'};391 expect(includes(filter(items, flt), items[0])).toBeFalsy();392 });393 describe('should support comparator', function() {394 it('not convert `null` or `undefined` to string in non-strict comparison', function() {395 var items = [396 {value: null},397 {value: undefined}398 ];399 var flt = {value: 'u'};400 expect(filter(items, flt).length).toBe(0);401 });402 it('not consider objects without a custom `toString` in non-strict comparison', function() {403 var items = [{test: {}}];404 var expr = '[object';405 expect(filter(items, expr).length).toBe(0);406 });407 it('should consider objects with custom `toString()` in non-strict comparison', function() {408 var obj = new Date(1970, 1);409 var items = [{test: obj}];410 expect(filter(items, '1970').length).toBe(1);411 expect(filter(items, 1970).length).toBe(1);412 obj = {413 toString: function() { return 'custom'; }414 };415 items = [{test: obj}];416 expect(filter(items, 'custom').length).toBe(1);417 });418 it('should cope with objects that have no `toString()` in non-strict comparison', function() {419 var obj = Object.create(null);420 var items = [{test: obj}];421 expect(function() {422 filter(items, 'foo');423 }).not.toThrow();424 expect(filter(items, 'foo').length).toBe(0);425 });426 it('should cope with objects where `toString` is not a function in non-strict comparison', function() {427 var obj = {428 toString: 'moo'429 };430 var items = [{test: obj}];431 expect(function() {432 filter(items, 'foo');433 }).not.toThrow();434 expect(filter(items, 'foo').length).toBe(0);435 });436 it('as equality when true', function() {437 var items = ['misko', 'adam', 'adamson'];438 var expr = 'adam';439 expect(filter(items, expr, true)).toEqual([items[1]]);440 expect(filter(items, expr, false)).toEqual([items[1], items[2]]);441 items = [442 {key: 'value1', nonkey: 1},443 {key: 'value2', nonkey: 2},444 {key: 'value12', nonkey: 3},445 {key: 'value1', nonkey: 4},446 {key: 'Value1', nonkey: 5}447 ];448 expr = {key: 'value1'};449 expect(filter(items, expr, true)).toEqual([items[0], items[3]]);450 items = [451 {key: 1, nonkey: 1},452 {key: 2, nonkey: 2},453 {key: 12, nonkey: 3},454 {key: 1, nonkey: 4}455 ];456 expr = {key: 1};457 expect(filter(items, expr, true)).toEqual([items[0], items[3]]);458 expr = 12;459 expect(filter(items, expr, true)).toEqual([items[2]]);460 });461 it('and use the function given to compare values', function() {462 var items = [463 {key: 1, nonkey: 1},464 {key: 2, nonkey: 2},465 {key: 12, nonkey: 3},466 {key: 1, nonkey: 14}467 ];468 var expr = {key: 10};469 var comparator = function(obj, value) {470 return obj > value;471 };472 expect(filter(items, expr, comparator)).toEqual([items[2]]);473 expr = 10;474 expect(filter(items, expr, comparator)).toEqual([items[2], items[3]]);475 });476 it('and use it correctly with deep expression objects', function() {477 var items = [478 {id: 0, details: {email: 'admin@example.com', role: 'admin'}},479 {id: 1, details: {email: 'user1@example.com', role: 'user'}},480 {id: 2, details: {email: 'user2@example.com', role: 'user'}}481 ];482 var expr, comp;483 expr = {details: {email: 'user@example.com', role: 'adm'}};484 expect(filter(items, expr)).toEqual([]);485 expr = {details: {email: 'admin@example.com', role: 'adm'}};486 expect(filter(items, expr)).toEqual([items[0]]);487 expr = {details: {email: 'admin@example.com', role: 'adm'}};488 expect(filter(items, expr, true)).toEqual([]);489 expr = {details: {email: 'admin@example.com', role: 'admin'}};490 expect(filter(items, expr, true)).toEqual([items[0]]);491 expr = {details: {email: 'user', role: 'us'}};492 expect(filter(items, expr)).toEqual([items[1], items[2]]);493 expr = {id: 0, details: {email: 'user', role: 'us'}};494 expect(filter(items, expr)).toEqual([]);495 expr = {id: 1, details: {email: 'user', role: 'us'}};496 expect(filter(items, expr)).toEqual([items[1]]);497 comp = function(actual, expected) {498 return isString(actual) && isString(expected) && (actual.indexOf(expected) === 0);499 };500 expr = {details: {email: 'admin@example.com', role: 'min'}};501 expect(filter(items, expr, comp)).toEqual([]);502 expr = {details: {email: 'admin@example.com', role: 'adm'}};503 expect(filter(items, expr, comp)).toEqual([items[0]]);504 });505 });...
test_dictviews.py
Source:test_dictviews.py
...6 def test_constructors_not_callable(self):7 kt = type({}.keys())8 self.assertRaises(TypeError, kt, {})9 self.assertRaises(TypeError, kt)10 it = type({}.items())11 self.assertRaises(TypeError, it, {})12 self.assertRaises(TypeError, it)13 vt = type({}.values())14 self.assertRaises(TypeError, vt, {})15 self.assertRaises(TypeError, vt)16 def test_dict_keys(self):17 d = {1: 10, "a": "ABC"}18 keys = d.keys()19 self.assertEqual(len(keys), 2)20 self.assertEqual(set(keys), {1, "a"})21 self.assertEqual(keys, {1, "a"})22 self.assertNotEqual(keys, {1, "a", "b"})23 self.assertNotEqual(keys, {1, "b"})24 self.assertNotEqual(keys, {1})25 self.assertNotEqual(keys, 42)26 self.assertIn(1, keys)27 self.assertIn("a", keys)28 self.assertNotIn(10, keys)29 self.assertNotIn("Z", keys)30 self.assertEqual(d.keys(), d.keys())31 e = {1: 11, "a": "def"}32 self.assertEqual(d.keys(), e.keys())33 del e["a"]34 self.assertNotEqual(d.keys(), e.keys())35 def test_dict_items(self):36 d = {1: 10, "a": "ABC"}37 items = d.items()38 self.assertEqual(len(items), 2)39 self.assertEqual(set(items), {(1, 10), ("a", "ABC")})40 self.assertEqual(items, {(1, 10), ("a", "ABC")})41 self.assertNotEqual(items, {(1, 10), ("a", "ABC"), "junk"})42 self.assertNotEqual(items, {(1, 10), ("a", "def")})43 self.assertNotEqual(items, {(1, 10)})44 self.assertNotEqual(items, 42)45 self.assertIn((1, 10), items)46 self.assertIn(("a", "ABC"), items)47 self.assertNotIn((1, 11), items)48 self.assertNotIn(1, items)49 self.assertNotIn((), items)50 self.assertNotIn((1,), items)51 self.assertNotIn((1, 2, 3), items)52 self.assertEqual(d.items(), d.items())53 e = d.copy()54 self.assertEqual(d.items(), e.items())55 e["a"] = "def"56 self.assertNotEqual(d.items(), e.items())57 def test_dict_mixed_keys_items(self):58 d = {(1, 1): 11, (2, 2): 22}59 e = {1: 1, 2: 2}60 self.assertEqual(d.keys(), e.items())61 self.assertNotEqual(d.items(), e.keys())62 def test_dict_values(self):63 d = {1: 10, "a": "ABC"}64 values = d.values()65 self.assertEqual(set(values), {10, "ABC"})66 self.assertEqual(len(values), 2)67 def test_dict_repr(self):68 d = {1: 10, "a": "ABC"}69 self.assertIsInstance(repr(d), str)70 r = repr(d.items())71 self.assertIsInstance(r, str)72 self.assertTrue(r == "dict_items([('a', 'ABC'), (1, 10)])" or73 r == "dict_items([(1, 10), ('a', 'ABC')])")74 r = repr(d.keys())75 self.assertIsInstance(r, str)76 self.assertTrue(r == "dict_keys(['a', 1])" or77 r == "dict_keys([1, 'a'])")78 r = repr(d.values())79 self.assertIsInstance(r, str)80 self.assertTrue(r == "dict_values(['ABC', 10])" or81 r == "dict_values([10, 'ABC'])")82 def test_keys_set_operations(self):83 d1 = {'a': 1, 'b': 2}84 d2 = {'b': 3, 'c': 2}85 d3 = {'d': 4, 'e': 5}86 self.assertEqual(d1.keys() & d1.keys(), {'a', 'b'})87 self.assertEqual(d1.keys() & d2.keys(), {'b'})88 self.assertEqual(d1.keys() & d3.keys(), set())89 self.assertEqual(d1.keys() & set(d1.keys()), {'a', 'b'})90 self.assertEqual(d1.keys() & set(d2.keys()), {'b'})91 self.assertEqual(d1.keys() & set(d3.keys()), set())92 self.assertEqual(d1.keys() & tuple(d1.keys()), {'a', 'b'})93 self.assertEqual(d1.keys() | d1.keys(), {'a', 'b'})94 self.assertEqual(d1.keys() | d2.keys(), {'a', 'b', 'c'})95 self.assertEqual(d1.keys() | d3.keys(), {'a', 'b', 'd', 'e'})96 self.assertEqual(d1.keys() | set(d1.keys()), {'a', 'b'})97 self.assertEqual(d1.keys() | set(d2.keys()), {'a', 'b', 'c'})98 self.assertEqual(d1.keys() | set(d3.keys()),99 {'a', 'b', 'd', 'e'})100 self.assertEqual(d1.keys() | (1, 2), {'a', 'b', 1, 2})101 self.assertEqual(d1.keys() ^ d1.keys(), set())102 self.assertEqual(d1.keys() ^ d2.keys(), {'a', 'c'})103 self.assertEqual(d1.keys() ^ d3.keys(), {'a', 'b', 'd', 'e'})104 self.assertEqual(d1.keys() ^ set(d1.keys()), set())105 self.assertEqual(d1.keys() ^ set(d2.keys()), {'a', 'c'})106 self.assertEqual(d1.keys() ^ set(d3.keys()),107 {'a', 'b', 'd', 'e'})108 self.assertEqual(d1.keys() ^ tuple(d2.keys()), {'a', 'c'})109 self.assertEqual(d1.keys() - d1.keys(), set())110 self.assertEqual(d1.keys() - d2.keys(), {'a'})111 self.assertEqual(d1.keys() - d3.keys(), {'a', 'b'})112 self.assertEqual(d1.keys() - set(d1.keys()), set())113 self.assertEqual(d1.keys() - set(d2.keys()), {'a'})114 self.assertEqual(d1.keys() - set(d3.keys()), {'a', 'b'})115 self.assertEqual(d1.keys() - (0, 1), {'a', 'b'})116 self.assertFalse(d1.keys().isdisjoint(d1.keys()))117 self.assertFalse(d1.keys().isdisjoint(d2.keys()))118 self.assertFalse(d1.keys().isdisjoint(list(d2.keys())))119 self.assertFalse(d1.keys().isdisjoint(set(d2.keys())))120 self.assertTrue(d1.keys().isdisjoint({'x', 'y', 'z'}))121 self.assertTrue(d1.keys().isdisjoint(['x', 'y', 'z']))122 self.assertTrue(d1.keys().isdisjoint(set(['x', 'y', 'z'])))123 self.assertTrue(d1.keys().isdisjoint(set(['x', 'y'])))124 self.assertTrue(d1.keys().isdisjoint(['x', 'y']))125 self.assertTrue(d1.keys().isdisjoint({}))126 self.assertTrue(d1.keys().isdisjoint(d3.keys()))127 de = {}128 self.assertTrue(de.keys().isdisjoint(set()))129 self.assertTrue(de.keys().isdisjoint([]))130 self.assertTrue(de.keys().isdisjoint(de.keys()))131 self.assertTrue(de.keys().isdisjoint([1]))132 def test_items_set_operations(self):133 d1 = {'a': 1, 'b': 2}134 d2 = {'a': 2, 'b': 2}135 d3 = {'d': 4, 'e': 5}136 self.assertEqual(137 d1.items() & d1.items(), {('a', 1), ('b', 2)})138 self.assertEqual(d1.items() & d2.items(), {('b', 2)})139 self.assertEqual(d1.items() & d3.items(), set())140 self.assertEqual(d1.items() & set(d1.items()),141 {('a', 1), ('b', 2)})142 self.assertEqual(d1.items() & set(d2.items()), {('b', 2)})143 self.assertEqual(d1.items() & set(d3.items()), set())144 self.assertEqual(d1.items() | d1.items(),145 {('a', 1), ('b', 2)})146 self.assertEqual(d1.items() | d2.items(),147 {('a', 1), ('a', 2), ('b', 2)})148 self.assertEqual(d1.items() | d3.items(),149 {('a', 1), ('b', 2), ('d', 4), ('e', 5)})150 self.assertEqual(d1.items() | set(d1.items()),151 {('a', 1), ('b', 2)})152 self.assertEqual(d1.items() | set(d2.items()),153 {('a', 1), ('a', 2), ('b', 2)})154 self.assertEqual(d1.items() | set(d3.items()),155 {('a', 1), ('b', 2), ('d', 4), ('e', 5)})156 self.assertEqual(d1.items() ^ d1.items(), set())157 self.assertEqual(d1.items() ^ d2.items(),158 {('a', 1), ('a', 2)})159 self.assertEqual(d1.items() ^ d3.items(),160 {('a', 1), ('b', 2), ('d', 4), ('e', 5)})161 self.assertEqual(d1.items() - d1.items(), set())162 self.assertEqual(d1.items() - d2.items(), {('a', 1)})163 self.assertEqual(d1.items() - d3.items(), {('a', 1), ('b', 2)})164 self.assertEqual(d1.items() - set(d1.items()), set())165 self.assertEqual(d1.items() - set(d2.items()), {('a', 1)})166 self.assertEqual(d1.items() - set(d3.items()), {('a', 1), ('b', 2)})167 self.assertFalse(d1.items().isdisjoint(d1.items()))168 self.assertFalse(d1.items().isdisjoint(d2.items()))169 self.assertFalse(d1.items().isdisjoint(list(d2.items())))170 self.assertFalse(d1.items().isdisjoint(set(d2.items())))171 self.assertTrue(d1.items().isdisjoint({'x', 'y', 'z'}))172 self.assertTrue(d1.items().isdisjoint(['x', 'y', 'z']))173 self.assertTrue(d1.items().isdisjoint(set(['x', 'y', 'z'])))174 self.assertTrue(d1.items().isdisjoint(set(['x', 'y'])))175 self.assertTrue(d1.items().isdisjoint({}))176 self.assertTrue(d1.items().isdisjoint(d3.items()))177 de = {}178 self.assertTrue(de.items().isdisjoint(set()))179 self.assertTrue(de.items().isdisjoint([]))180 self.assertTrue(de.items().isdisjoint(de.items()))181 self.assertTrue(de.items().isdisjoint([1]))182 def test_recursive_repr(self):183 d = {}184 d[42] = d.values()185 self.assertRaises(RecursionError, repr, d)186 def test_copy(self):187 d = {1: 10, "a": "ABC"}188 self.assertRaises(TypeError, copy.copy, d.keys())189 self.assertRaises(TypeError, copy.copy, d.values())190 self.assertRaises(TypeError, copy.copy, d.items())191 def test_compare_error(self):192 class Exc(Exception):193 pass194 class BadEq:195 def __hash__(self):196 return 7197 def __eq__(self, other):198 raise Exc199 k1, k2 = BadEq(), BadEq()200 v1, v2 = BadEq(), BadEq()201 d = {k1: v1}202 self.assertIn(k1, d)203 self.assertIn(k1, d.keys())204 self.assertIn(v1, d.values())205 self.assertIn((k1, v1), d.items())206 self.assertRaises(Exc, d.__contains__, k2)207 self.assertRaises(Exc, d.keys().__contains__, k2)208 self.assertRaises(Exc, d.items().__contains__, (k2, v1))209 self.assertRaises(Exc, d.items().__contains__, (k1, v2))210 with self.assertRaises(Exc):211 v2 in d.values()212 def test_pickle(self):213 d = {1: 10, "a": "ABC"}214 for proto in range(pickle.HIGHEST_PROTOCOL + 1):215 self.assertRaises((TypeError, pickle.PicklingError),216 pickle.dumps, d.keys(), proto)217 self.assertRaises((TypeError, pickle.PicklingError),218 pickle.dumps, d.values(), proto)219 self.assertRaises((TypeError, pickle.PicklingError),220 pickle.dumps, d.items(), proto)221 def test_abc_registry(self):222 d = dict(a=1)223 self.assertIsInstance(d.keys(), collections.KeysView)224 self.assertIsInstance(d.keys(), collections.MappingView)225 self.assertIsInstance(d.keys(), collections.Set)226 self.assertIsInstance(d.keys(), collections.Sized)227 self.assertIsInstance(d.keys(), collections.Iterable)228 self.assertIsInstance(d.keys(), collections.Container)229 self.assertIsInstance(d.values(), collections.ValuesView)230 self.assertIsInstance(d.values(), collections.MappingView)231 self.assertIsInstance(d.values(), collections.Sized)232 self.assertIsInstance(d.items(), collections.ItemsView)233 self.assertIsInstance(d.items(), collections.MappingView)234 self.assertIsInstance(d.items(), collections.Set)235 self.assertIsInstance(d.items(), collections.Sized)236 self.assertIsInstance(d.items(), collections.Iterable)237 self.assertIsInstance(d.items(), collections.Container)238if __name__ == "__main__":...
sort_algorithm.py
Source:sort_algorithm.py
1# -*- coding: utf-8 -*-2def select_sort(items, comp=lambda x, y: x < y):3 """4 éæ©æåºï¼å¤å±for循ç¯æ¯æ¬¡æ¾å°ä¸ä¸ªæå°å¼5 """6 items = items[:]7 for i in range(len(items) - 1):8 min_index = i9 for j in range(i + 1, len(items)):10 if comp(items[j], items[min_index]):11 min_index = j12 items[i], items[min_index] = items[min_index], items[i]13 return items14def bubble_sort(items, comp=lambda x, y: x > y):15 """å泡æåº16 1ãæ¯è¾ç¸é»çå
ç´ ãå¦æ第ä¸ä¸ªæ¯ç¬¬äºä¸ªå¤§ï¼å°±äº¤æ¢å®ä»¬ä¸¤ä¸ªã17 2ã对æ¯ä¸å¯¹ç¸é»å
ç´ ä½åæ ·çå·¥ä½ï¼ä»å¼å§ç¬¬ä¸å¯¹å°ç»å°¾çæåä¸å¯¹ãè¿æ¥åå®åï¼æåçå
ç´ ä¼æ¯æ大çæ°ã18 3ãé对ææçå
ç´ éå¤ä»¥ä¸çæ¥éª¤ï¼é¤äºæåä¸ä¸ªã19 4ãæç»æ¯æ¬¡å¯¹è¶æ¥è¶å°çå
ç´ éå¤ä¸é¢çæ¥éª¤ï¼ç´å°æ²¡æä»»ä½ä¸å¯¹æ°åéè¦æ¯è¾ã20 """21 # items = items[:]22 # for i in range(len(items)-1):23 # for j in range(1,len(items)-i):24 # if comp(items[j-1],items[j]):25 # items[j-1],items[j] = items[j],items[j-1]26 # return items27 # å¢å ä¸ä¸ªä¼å项ï¼å¦æå¨å¤å±æä¸è½®å¾ªç¯ä¸ï¼æ²¡æåç交æ¢ï¼è¯´æå·²ç»æåºï¼ååæ¢å¾ªç¯ã28 items = items[:]29 for i in range(len(items) - 1):30 swapped = False31 for j in range(1, len(items) - i):32 if comp(items[j - 1], items[j]):33 items[j - 1], items[j] = items[j], items[j - 1]34 swapped = True35 if not swapped:36 break37 print(i, items)38 return items39def cocktail_sort(items, comp=lambda x, y: x > y):40 """41 1ãå
对æ°ç»ä»å·¦å°å³è¿è¡å泡æåºï¼ååºï¼ï¼åæ大çå
ç´ å»å°æå³ç«¯ï¼42 2ãå对æ°ç»ä»å³å°å·¦è¿è¡å泡æåºï¼éåºï¼ï¼åæå°çå
ç´ å»å°æ左端ï¼43 """44 items = items[:]45 for i in range(len(items) - 1):46 swapped = False47 for j in range(len(items) - 1 - i):48 if comp(items[j], items[j + 1]):49 items[j], items[j + 1] = items[j + 1], items[j]50 swapped = True51 if swapped: # å¦æä»å·¦å°å³åçäºäº¤æ¢ï¼åè¿è¡ä»å³å°å·¦çå泡æåº52 for j in range(len(items) - 2 - i, i, -1): # å¯ä»¥åå°len(items)-2-iï¼ä½æ¯åä¸å°len(items)-1-i53 if comp(items[j], items[j - 1]):54 items[j], items[j - 1] = items[j - 1], items[j]55 swapped = True56 if not swapped:57 break58 print(i, items)59 return items60def merge(items1, items2, comp=lambda x, y: x < y):61 """å并(å°ä¸¤ä¸ªæåºçå表å并æä¸ä¸ªæåºçå表)"""62 items = []63 index1, index2 = 0, 064 while index1 < len(items1) and index2 < len(items2):65 if comp(items1[index1], items2[index2]): # å°ä¸¤ä¸ªå表ä¸çæå°å¼æ·»å å°items66 items.append(items1[index1])67 index1 += 168 else:69 items.append(items2[index2])70 index2 += 171 # while循ç¯çæ¨åºæ¡ä»¶ï¼ä¸¤ä¸ªå表æä¸ä¸ªçç´¢å¼å·²ç»å°äºæ«ä½ï¼æ¤æ¶æå¦ä¸ä¸ªå表å©ä½å
ç´ çæ·»å å°items72 items += items1[index1:]73 items += items2[index2:]74 return items75def _merge_sort(items, comp):76 """å½å¹¶æåº"""77 if len(items) < 2:78 return items79 mid = len(items) // 280 left = _merge_sort(items[:mid], comp)81 right = _merge_sort(items[mid:], comp)82 return merge(left, right, comp)83def merge_sort(items):84 return _merge_sort(items, comp=lambda x, y: x < y)85"""86å¿«éæåº 87éè¿ä¸è¶æåºå°è¦æåºçæ°æ®åå²æç¬ç«ç两é¨åï¼å
¶ä¸ä¸é¨åçæææ°æ®é½æ¯å¦å¤ä¸é¨åçæææ°æ®é½è¦å°ï¼88ç¶ååææ¤æ¹æ³å¯¹è¿ä¸¤é¨åæ°æ®åå«è¿è¡å¿«éæåºï¼æ´ä¸ªæåºè¿ç¨å¯ä»¥éå½è¿è¡ï¼ä»¥æ¤è¾¾å°æ´ä¸ªæ°æ®åææåºåºåã89æ ¸å¿ææ³:901.å¨å¾
æåºçå
ç´ ä»»åä¸ä¸ªå
ç´ ä½ä¸ºåºå(é常é第ä¸ä¸ªå
ç´ ï¼ç§°ä¸ºåºåå
ç´ ï¼912.å°å¾
æåºçå
ç´ è¿è¡ååï¼æ¯åºåå
ç´ å¤§çå
ç´ ç§»å¨å°åºåå
ç´ çå³ä¾§ï¼æ¯åºåå
ç´ å°ç移å¨å°ä½å·¦ä¾§ï¼ä»èä¸è¶æåºè¿ç¨ï¼å°±å¯ä»¥éå®åºåå
ç´ çæç»ä½ç½®923.对左å³ä¸¤ä¸ªååéå¤ä»¥ä¸æ¥éª¤ç´å°ææå
ç´ é½æ¯æåºçï¼éå½è¿ç¨ï¼93"""94def quick_sort(items, comp=lambda x, y: x <= y):95 items = list(items)[:]96 _quick_sort(items, 0, len(items) - 1, comp)97 return items98def _quick_sort(items, start, end, comp):99 if start < end:100 pos = _partition(items, start, end, comp)101 print(pos,items)102 _quick_sort(items, start, pos - 1, comp)103 _quick_sort(items, pos + 1, end, comp)104def _partition(items, start, end, comp):105 """å®æï¼å°å¾
æåºçå
ç´ è¿è¡ååï¼æ¯åºåå
ç´ å¤§çå
ç´ ç§»å¨å°åºåå
ç´ çå³ä¾§ï¼æ¯åºåå
ç´ å°ç移å¨å°ä½å·¦ä¾§"""106 pivot = items[end] # éæ©æ¢è½´å¯¹å
ç´ è¿è¡ååï¼å·¦è¾¹é½æ¯æ¢è½´å°ï¼å³è¾¹é½æ¯æ¢è½´å¤§107 i = start - 1108 for j in range(start, end):109 if comp(items[j], pivot):110 i += 1111 items[i], items[j] = items[j], items[i]112 items[i + 1], items[end] = items[end], items[i + 1]113 return i + 1114if __name__ == '__main__':115 a = [1, 2, 10, 4, 3, 7, 6, 9, 8]116 #r = merge_sort(a)117 r = quick_sort(a)...
knapsack_problem.py
Source:knapsack_problem.py
...272829def Greedy_algorithm_mean(items: dict, optimal_items: list, total_knapsack_volume: int) -> int: # жаднÑй алгоÑиÑм по ÑÑÐµÐ´Ð½Ð¸Ð¼Ñ Ð¿Ð¾ÐºÐ°Ð·Ð°ÑелÑ30 unit_price = dict((i, items[i][1] / items[i][0]) for i in items.keys())31 sort_price = (sorted(unit_price.items(), key=lambda item: item[1]))32 sort_price.reverse()33 # print(sort_price)3435 #optimal_items = []36 opt = 037 cur_volume = 038 for index in range(len(items)):39 if cur_volume + items[sort_price[index][0]][0] <= total_knapsack_volume:40 cur_volume += items[sort_price[index][0]][0]41 optimal_items.append(sort_price[index][0])42 opt += items[sort_price[index][0]][1]4344 for el in sort_price:45 if el[0] not in optimal_items:46 optimal_items.append(el[0])4748 # print(opt, end='\n')49 # print(optimal_items)50 return opt5152def Greedy_algorithm_volume(items: dict, optimal_items: list, total_knapsack_volume: int) -> int: # жаднÑй алгоÑиÑм по ÑазмеÑÑ53 sort_volume = sorted(items.items(), key= lambda item: item[1], reverse=False)54 # print(sort_volume)55 opt = 056 cur_volume = 057 for i in range(len(items)):58 if cur_volume + sort_volume[i][1][0] <= total_knapsack_volume:59 cur_volume += sort_volume[i][1][0]60 optimal_items.append(sort_volume[i][0])61 opt += sort_volume[i][1][1]6263 for el in sort_volume:64 if el[0] not in optimal_items:65 optimal_items.append(el[0])6667 return opt68697071def Greedy_algorithm_value(items: dict, optimal_items: list, total_knapsack_volume: int) -> int: # жаднÑй алгоÑиÑм по Ñене72 sort_value = sorted(items.items(), key= lambda item: item[0], reverse=True)73 # print(sort_volume)74 opt = 075 cur_volume = 076 for i in range(len(items)):77 if cur_volume + sort_value[i][1][0] <= total_knapsack_volume:78 cur_volume += sort_value[i][1][0]79 optimal_items.append(sort_value[i][0])80 opt += sort_value[i][1][1]8182 for el in sort_value:83 if el[0] not in optimal_items:84 optimal_items.append(el[0])85 return opt86
...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!