Best JavaScript code snippet using best
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
1import collections2import copy3import pickle4import unittest5class DictSetTest(unittest.TestCase):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
1from scipy.optimize import linprog2import sys34precision = 10^-556sys.setrecursionlimit(1500)78def comparison(a1: float, a2: float):9 if abs(a1-a2) <= precision:10 return 011 else:12 return 1131415def LP_solution(items: dict, V: int, number_of_items: int) -> float:16 cor = []17 for i in range(number_of_items):18 cor.append(tuple((0, 1)))19 cor = tuple(cor)2021 values = [-items[i][1] for i in items.keys()]22 volumes = [[items[i][0] for i in items.keys()]]2324 res_lin_solv = linprog(c=values, A_ub=volumes, b_ub=V, bounds=cor, method='interior-point')25 # print(res_lin_solv)26 return -res_lin_solv.fun272829def 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 opt86878889def Pruning(items: dict, n_items: int, path: list, price: int, opt: int, V: int):90 if len(items) == 0:91 return price9293 index = number_of_items - n_items94 new_price = 09596 items_right = items.copy()97 items_right.pop(optimal_items[index])98 #print("eeeeeeeeeeeee ", items[optimal_items[index]][0])99 if len(items_right) != 0:100 OPT_right = LP_solution(items_right, V - items[optimal_items[index]][0], n_items-1)101 else:102 OPT_right = 0103 if price + OPT_right + items[optimal_items[index]][1] >= opt and V-items[optimal_items[index]][0] >= 0:104 path_right = path.copy()105 path_right.append(items[optimal_items[index]][1])106 #price += items[optimal_items[index]][1]107 price = sum(path_right)108 # if price != sum(path_right):109 # print("Waaaarning", price, sum(path_right))110 new_price = Pruning(items_right, n_items-1, path_right, price, opt, V-items[optimal_items[index]][0])111 # return new_price112113 if new_price > opt:114 opt = new_price115# ---------------------------------------------------------------------------116 items_left = items.copy()117 items_left.pop(optimal_items[index])118 if len(items_left) != 0:119 OPT_left = LP_solution(items_left, V, n_items-1)120 else:121 OPT_left = 0122 if price + OPT_left >= opt:123 path_left = path.copy()124 path_left.append(0)125 new_price = Pruning(items_left, n_items-1, path_left, price, opt, V)126 # return new_price127128129 if new_price > opt:130 opt = new_price131 # ---------------------------------------------------------------------------132 print(opt)133 print(path)134 if opt == 12248:135 print("aaaaaaaaaaaa", path)136 exit(0)137138 return opt139140141142total_knapsack_volume = int(input())143number_of_items = int(input())144145items = dict((i,[]) for i in range(number_of_items))146for i in items.keys():147 item_volume_value = list(map(int,input().split()))148 items[i] = item_volume_value149150# Ñдвлим ÑлеменÑÑ, коÑоÑÑе не ÑмогÑÑ Ð²Ð¾Ð¹Ñи в ÑÑкзак151new_items = items.copy()152for i in items.keys():153 if items[i][0] > total_knapsack_volume:154 new_items.pop(i)155items = new_items156number_of_items = len(items)157# print(items)158# print(number_of_items)159160optimal_items_mean, optimal_items_value, optimal_items_volume= [], [], []161opt_mean = Greedy_algorithm_mean(items,optimal_items_mean, total_knapsack_volume)162opt_value = Greedy_algorithm_value(items, optimal_items_value, total_knapsack_volume)163opt_volume = Greedy_algorithm_volume(items, optimal_items_volume, total_knapsack_volume)164165optimal_items = []166opt = max(opt_mean, opt_value, opt_volume)167if opt == opt_mean:168 optimal_items = optimal_items_mean169elif opt == opt_volume:170 optimal_items = optimal_items_volume171else:172 optimal_items = optimal_items_value173174175# my_path = dict((i,[items[i][0], items[i][1]]) for i in optimal_items)176#print(optimal_items)177178path = []179price = 0180181print(Pruning(items, number_of_items, path, price, opt, total_knapsack_volume))182# print(LP_solution(items, total_knapsack_volume, number_of_items))183184185
...
example02.py
Source:example02.py
1"""2æåº - å泡æåºãéæ©æåºãå½å¹¶æåºãå¿«éæåº3å泡æåº - O(n ** 2)ï¼ä¸¤ä¸¤æ¯è¾ï¼å¤§çä¸æ²435, 97, 12, 68, 55, 73, 81, 40535, 12, 68, 55, 73, 81, 40, [97]612, 35, 55, 68, 73, 40, [81]712, 35, 55, 68, 40, [73]8...9éæ©æåº - O(n ** 2)ï¼æ¯æ¬¡ä»å©ä¸å
ç´ ä¸éæ©æå°10-----------------------------------------11å½å¹¶æåº - O(n * log_2 n) - é«çº§æåºç®æ³1235, 97, 12, 68, 55, 73, 81, 4013[35, 97, 12, 68], [55, 73, 81, 40]14[35, 97], [12, 68], [55, 73], [81, 40]15[35], [97], [12], [68], [55], [73], [81], [40]16[35, 97], [12, 68], [55, 73], [40, 81]17[12, 35, 68, 97], [40, 55, 73, 81]18[12, 35, 40, 55, 68, 73, 81, 97]19-----------------------------------------20å¿«éæåº - 以æ¢è½´ä¸ºçå°å表ä¸çå
ç´ åå为两个é¨åï¼å·¦è¾¹é½æ¯æ¢è½´å°ï¼å³è¾¹é½æ¯æ¢è½´å¤§2135, 97, 12, 68, 55, 73, 81, 402235, 12, [40], 68, 55, 73, 81, 9723[12], 35, [40], 68, 55, 73, 81, [97]24[12], 35, [40], 55, [68], 73, 81, [97]25[12], 35, [40], 55, [68], 73, [81], [97]26"""27class Person(object):28 """人"""29 def __init__(self, name, age):30 self.name = name31 self.age = age32 # def __gt__(self, other):33 # return self.name > other.name34 def __str__(self):35 return f'{self.name}: {self.age}'36 def __repr__(self):37 return self.__str__()38def select_sort(origin_items, comp=lambda x, y: x < y):39 """ç®åéæ©æåº"""40 items = origin_items[:]41 for i in range(len(items) - 1):42 min_index = i43 for j in range(i + 1, len(items)):44 if comp(items[j], items[min_index]):45 min_index = j46 items[i], items[min_index] = items[min_index], items[i]47 return items48# å½æ°ç设计è¦å°½éåå°æ å¯ä½ç¨ï¼ä¸å½±åè°ç¨è
ï¼49# 9 1 2 3 4 5 6 7 850# 9 2 3 4 5 6 7 8 151# *åé¢çåæ°å«ä½ç½®åæ°ï¼ä¼ åæ¶åªéè¦å¯¹å·å
¥åº§å³å¯52# *åé¢çåæ°å«å½åå
³é®ååæ°ï¼ä¼ åæ¶å¿
é¡»ç»åºåæ°åååæ°å¼53# *args - å¯ååæ° - å
ç»54# **kwargs - å
³é®ååæ° - åå
¸55def bubble_sort(origin_items, *, comp=lambda x, y: x > y):56 """å泡æåº"""57 items = origin_items[:]58 for i in range(1, len(items)):59 swapped = False60 for j in range(i - 1, len(items) - i):61 if comp(items[j], items[j + 1]):62 items[j], items[j + 1] = items[j + 1], items[j]63 swapped = True64 if swapped:65 swapped = False66 for j in range(len(items) - i - 1, i - 1, -1):67 if comp(items[j - 1], items[j]):68 items[j], items[j - 1] = items[j - 1], items[j]69 swapped = True70 if not swapped:71 break72 return items73def merge_sort(items, comp=lambda x, y: x <= y):74 """å½å¹¶æåº"""75 if len(items) < 2:76 return items[:]77 mid = len(items) // 278 left = merge_sort(items[:mid], comp)79 right = merge_sort(items[mid:], comp)80 return merge(left, right, comp)81def merge(items1, items2, comp=lambda x, y: x <= y):82 """å并ï¼å°ä¸¤ä¸ªæåºå表å并æä¸ä¸ªæ°çæåºå表ï¼"""83 items = []84 index1, index2 = 0, 085 while index1 < len(items1) and index2 < len(items2):86 if comp(items1[index1], items2[index2]):87 items.append(items1[index1])88 index1 += 189 else:90 items.append(items2[index2])91 index2 += 192 items += items1[index1:]93 items += items2[index2:]94 return items95def quick_sort(origin_items, comp=lambda x, y: x <= y):96 """å¿«éæåº"""97 items = origin_items[:]98 _quick_sort(items, 0, len(items) - 1, comp)99 return items100def _quick_sort(items, start, end, comp):101 """éå½è°ç¨åååæåº"""102 if start < end:103 pos = _partition(items, start, end, comp)104 _quick_sort(items, start, pos - 1, comp)105 _quick_sort(items, pos + 1, end, comp)106def _partition(items, start, end, comp):107 """åå"""108 pivot = items[end]109 i = start - 1110 for j in range(start, end):111 if comp(items[j], pivot):112 i += 1113 items[i], items[j] = items[j], items[i]114 items[i + 1], items[end] = items[end], items[i + 1]115 return i + 1116def main():117 """主å½æ°"""118 items = [35, 97, 12, 68, 55, 73, 81, 40]119 # print(bubble_sort(items))120 # print(select_sort(items))121 # print(merge_sort(items))122 print(quick_sort(items))123 items2 = [124 Person('Wang', 25), Person('Luo', 39),125 Person('Zhang', 50), Person('He', 20)126 ]127 # print(bubble_sort(items2, comp=lambda p1, p2: p1.age > p2.age))128 # print(select_sort(items2, comp=lambda p1, p2: p1.name < p2.name))129 # print(merge_sort(items2, comp=lambda p1, p2: p1.age <= p2.age))130 print(quick_sort(items2, comp=lambda p1, p2: p1.age <= p2.age))131 items3 = ['apple', 'orange', 'watermelon', 'durian', 'pear']132 # print(bubble_sort(items3))133 # print(bubble_sort(items3, comp=lambda x, y: len(x) > len(y)))134 # print(merge_sort(items3))135 print(merge_sort(items3))136if __name__ == '__main__':...
DragFrom.js
Source:DragFrom.js
1export const dragFrom = {2 '0:0:0': {3 items: []4 },5 '0:0:0.5': {6 items: []7 },8 '0:0:1': {9 items: []10 },11 '0:0:1.5': {12 items: []13 },14 '0:0:2': {15 items: []16 },17 '0:0:2.5': {18 items: []19 },20 '0:0:3': {21 items: []22 },23 '0:0:3.5': {24 items: []25 },26 '0:1:0': {27 items: []28 },29 '0:1:0.5': {30 items: []31 },32 '0:1:1': {33 items: []34 },35 '0:1:1.5': {36 items: []37 },38 '0:1:2': {39 items: []40 },41 '0:1:2.5': {42 items: []43 },44 '0:1:3': {45 items: []46 },47 '0:1:3.5': {48 items: []49 },50 '0:2:0': {51 items: []52 },53 '0:2:0.5': {54 items: []55 },56 '0:2:1': {57 items: []58 },59 '0:2:1.5': {60 items: []61 },62 '0:2:2': {63 items: []64 },65 '0:2:2.5': {66 items: []67 },68 '0:2:3': {69 items: []70 },71 '0:2:3.5': {72 items: []73 },74 '0:3:0': {75 items: []76 },77 '0:3:0.5': {78 items: []79 },80 '0:3:1': {81 items: []82 },83 '0:3:1.5': {84 items: []85 },86 '0:3:2': {87 items: []88 },89 '0:3:2.5': {90 items: []91 },92 '0:3:3': {93 items: []94 },95 '0:3:3.5': {96 items: []97 },98 '1:0:0': {99 items: []100 },101 '1:0:0.5': {102 items: []103 },104 '1:0:1': {105 items: []106 },107 '1:0:1.5': {108 items: []109 },110 '1:0:2': {111 items: []112 },113 '1:0:2.5': {114 items: []115 },116 '1:0:3': {117 items: []118 },119 '1:0:3.5': {120 items: []121 },122 '1:1:0': {123 items: []124 },125 '1:1:0.5': {126 items: []127 },128 '1:1:1': {129 items: []130 },131 '1:1:1.5': {132 items: []133 },134 '1:1:2': {135 items: []136 },137 '1:1:2.5': {138 items: []139 },140 '1:1:3': {141 items: []142 },143 '1:1:3.5': {144 items: []145 },146 '1:2:0': {147 items: []148 },149 '1:2:0.5': {150 items: []151 },152 '1:2:1': {153 items: []154 },155 '1:2:1.5': {156 items: []157 },158 '1:2:2': {159 items: []160 },161 '1:2:2.5': {162 items: []163 },164 '1:2:3': {165 items: []166 },167 '1:2:3.5': {168 items: []169 },170 '1:3:0': {171 items: []172 },173 '1:3:0.5': {174 items: []175 },176 '1:3:1': {177 items: []178 },179 '1:3:1.5': {180 items: []181 },182 '1:3:2': {183 items: []184 },185 '1:3:2.5': {186 items: []187 },188 '1:3:3': {189 items: []190 },191 '1:3:3.5': {192 items: []193 },194 '2:0:0': {195 items: []196 },197 '2:0:0.5': {198 items: []199 },200 '2:0:1': {201 items: []202 },203 '2:0:1.5': {204 items: []205 },206 '2:0:2': {207 items: []208 },209 '2:0:2.5': {210 items: []211 },212 '2:0:3': {213 items: []214 },215 '2:0:3.5': {216 items: []217 },218 '2:1:0': {219 items: []220 },221 '2:1:0.5': {222 items: []223 },224 '2:1:1': {225 items: []226 },227 '2:1:1.5': {228 items: []229 },230 '2:1:2': {231 items: []232 },233 '2:1:2.5': {234 items: []235 },236 '2:1:3': {237 items: []238 },239 '2:1:3.5': {240 items: []241 },242 '2:2:0': {243 items: []244 },245 '2:2:0.5': {246 items: []247 },248 '2:2:1': {249 items: []250 },251 '2:2:1.5': {252 items: []253 },254 '2:2:2': {255 items: []256 },257 '2:2:2.5': {258 items: []259 },260 '2:2:3': {261 items: []262 },263 '2:2:3.5': {264 items: []265 },266 '2:3:0': {267 items: []268 },269 '2:3:0.5': {270 items: []271 },272 '2:3:1': {273 items: []274 },275 '2:3:1.5': {276 items: []277 },278 '2:3:2': {279 items: []280 },281 '2:3:2.5': {282 items: []283 },284 '2:3:3': {285 items: []286 },287 '2:3:3.5': {288 items: []289 },290 '3:0:0': {291 items: []292 },293 '3:0:0.5': {294 items: []295 },296 '3:0:1': {297 items: []298 },299 '3:0:1.5': {300 items: []301 },302 '3:0:2': {303 items: []304 },305 '3:0:2.5': {306 items: []307 },308 '3:0:3': {309 items: []310 },311 '3:0:3.5': {312 items: []313 },314 '3:1:0': {315 items: []316 },317 '3:1:0.5': {318 items: []319 },320 '3:1:1': {321 items: []322 },323 '3:1:1.5': {324 items: []325 },326 '3:1:2': {327 items: []328 },329 '3:1:2.5': {330 items: []331 },332 '3:1:3': {333 items: []334 },335 '3:1:3.5': {336 items: []337 },338 '3:2:0': {339 items: []340 },341 '3:2:0.5': {342 items: []343 },344 '3:2:1': {345 items: []346 },347 '3:2:1.5': {348 items: []349 },350 '3:2:2': {351 items: []352 },353 '3:2:2.5': {354 items: []355 },356 '3:2:3': {357 items: []358 },359 '3:2:3.5': {360 items: []361 },362 '3:3:0': {363 items: []364 },365 '3:3:0.5': {366 items: []367 },368 '3:3:1': {369 items: []370 },371 '3:3:1.5': {372 items: []373 },374 '3:3:2': {375 items: []376 },377 '3:3:2.5': {378 items: []379 },380 '3:3:3': {381 items: []382 },383 '3:3:3.5': {384 items: []385 }...
starterpacks.py
Source:starterpacks.py
1from bflib import items2from bflib.characters import classes3from core.outfits.base import Outfit4class BasicPack(Outfit):5 name = "Basic Pack"6 worn_items = [7 items.Backpack,8 ]9 inventory_items = [10 (6, items.Torch),11 items.TinderboxFlintAndSteel,12 items.Waterskin,13 items.WinterBlanket,14 items.DryRations,15 items.LargeSack,16 (2, items.SmallSack),17 items.PotionOfHealing,18 ]19 coins = items.coins.Gold(60)20 @classmethod21 def check_if_applicable(cls, game_object):22 return True23class FighterPack1(Outfit):24 name = "Fighter Pack 1"25 worn_items = [26 items.ChainMail,27 ]28 wielded_items = [29 items.MediumShield,30 items.Longsword,31 ]32 @classmethod33 def check_if_applicable(cls, game_object):34 character_class = game_object.character_class35 if character_class and character_class.contains(classes.Fighter):36 return True37class FighterPack2(Outfit):38 name = "Fighter Pack 2"39 worn_items = [40 items.ChainMail,41 ]42 wielded_items = [43 items.Polearm,44 ]45 @classmethod46 def check_if_applicable(cls, game_object):47 character_class = game_object.character_class48 if character_class and character_class.contains(classes.Fighter):49 return True50class FighterPack3(Outfit):51 name = "Fighter Pack 3"52 worn_items = [53 items.LeatherArmor,54 items.Quiver,55 ]56 wielded_items = [57 items.Longsword,58 items.Shortbow,59 ]60 inventory_items = [61 (30, items.ShortbowArrow)62 ]63 @classmethod64 def check_if_applicable(cls, game_object):65 character_class = game_object.character_class66 if character_class and character_class.contains(classes.Fighter):67 return True68class MagicUserPack1(Outfit):69 name = "Magic User Pack 1"70 worn_items = [71 ]72 wielded_items = [73 items.WalkingStaff,74 ]75 inventory_items = [76 (2, items.Dagger),77 items.MagicScroll,78 ]79 @classmethod80 def check_if_applicable(cls, game_object):81 character_class = game_object.character_class82 if character_class and character_class.contains(classes.MagicUser):83 return True84class MagicUserPack2(Outfit):85 name = "Magic User Pack 2"86 worn_items = [87 ]88 wielded_items = [89 items.WalkingStaff,90 ]91 inventory_items = [92 (2, items.Dagger),93 ]94 coins = items.coins.Gold(50)95 @classmethod96 def check_if_applicable(cls, game_object):97 character_class = game_object.character_class98 if character_class and character_class.contains(classes.MagicUser):99 return True100class ClericPack1(Outfit):101 name = "Cleric Pack 1"102 worn_items = [103 items.LeatherArmor,104 ]105 wielded_items = [106 items.Mace,107 items.MediumShield,108 ]109 inventory_items = [110 items.HolySymbol,111 items.Vial,112 ]113 @classmethod114 def check_if_applicable(cls, game_object):115 character_class = game_object.character_class116 if character_class and character_class.contains(classes.Cleric):117 return True118class ClericPack2(Outfit):119 name = "Cleric Pack 2"120 worn_items = [121 items.LeatherArmor,122 ]123 wielded_items = [124 items.Maul,125 ]126 inventory_items = [127 items.Sling,128 (30, items.SlingBullet),129 items.HolySymbol,130 items.Vial,131 ]132 @classmethod133 def check_if_applicable(cls, game_object):134 character_class = game_object.character_class135 if character_class and character_class.contains(classes.Cleric):136 return True137class ThiefPack1(Outfit):138 name = "Thief Pack 1"139 worn_items = [140 items.LeatherArmor,141 ]142 wielded_items = [143 items.Shortsword,144 ]145 inventory_items = [146 (2, items.Dagger),147 items.SilkRope,148 items.ThievesPickAndTools,149 ]150 @classmethod151 def check_if_applicable(cls, game_object):152 character_class = game_object.character_class153 if character_class and character_class.contains(classes.Thief):...
test_itemcollection.py
Source:test_itemcollection.py
1import os2import unittest3from satstac import ItemCollection, Item4from shutil import rmtree5testpath = os.path.dirname(__file__)6class Test(unittest.TestCase):7 path = os.path.join(testpath, 'test-item')8 @classmethod9 def tearDownClass(cls):10 """ Remove test files """11 if os.path.exists(cls.path):12 rmtree(cls.path)13 def load_items(self):14 return ItemCollection.load(os.path.join(testpath, 'items.json'))15 def test_load(self):16 """ Initialize Scenes with list of Scene objects """17 items = self.load_items()18 assert(len(items._collections) == 1)19 assert(len(items) == 2)20 assert(isinstance(items[0], Item))21 def test_save(self):22 """ Save items list """23 items = self.load_items()24 fname = os.path.join(testpath, 'save-test.json')25 items.save(fname)26 assert(os.path.exists(fname))27 os.remove(fname)28 assert(not os.path.exists(fname))29 def test_collection(self):30 """ Get a collection """31 items = self.load_items()32 col = items.collection('landsat-8-l1')33 assert(col.id == 'landsat-8-l1')34 def test_no_collection(self):35 """ Attempt to get non-existent collection """36 items = self.load_items()37 col = items.collection('nosuchcollection')38 assert(col is None)39 def test_get_properties(self):40 """ Get set of properties """41 items = self.load_items()42 p = items.properties('eo:platform')43 assert(len(p) == 1)44 assert(p[0] == 'landsat-8')45 def test_print_items(self):46 """ Print summary of items """47 items = self.load_items()48 print(items.summary())49 def test_dates(self):50 """ Get dates of all items """51 items = self.load_items()52 dates = items.dates()53 assert(len(dates) == 1)54 def test_text_calendar(self):55 """ Get calendar """56 items = self.load_items()57 cal = items.calendar()58 assert(len(cal) > 250)59 def test_download_thumbnails(self):60 """ Download all thumbnails """61 items = self.load_items()62 fnames = items.download(key='thumbnail')63 for f in fnames:64 assert(os.path.exists(f))65 os.remove(f)66 assert(not os.path.exists(f))67 #shutil.rmtree(os.path.join(testpath, 'landsat-8-l1'))68 def test_filter(self):69 items = self.load_items()70 items.filter('eo:cloud_cover', [100])71 assert(len(items) == 1)72 def test_download_assets(self):73 """ Download multiple assets from all items """74 items = self.load_items()75 filenames = items.download_assets(keys=['MTL', 'ANG'], filename_template=self.path)76 assert(len(filenames) == 2)77 for fnames in filenames:78 assert(len(fnames) == 2)79 for f in fnames:80 assert(os.path.exists(f))81 def test_download(self):82 """ Download a data file from all items """83 items = self.load_items()84 85 fnames = items.download(key='MTL', filename_template=self.path)86 assert(len(fnames) == 2)87 for f in fnames:...
Using AI Code Generation
1var request = require('request');2var fs = require('fs');3var bestBuy = require('./bestBuy.js');4var async = require('async');5var csv = require('csv');6var cheerio = require('cheerio');7var _ = require('underscore');8var moment = require('moment');9var mongoose = require('mongoose');10var bestBuyProduct = require('./bestBuyProduct.js');11var bestBuyProductModel = mongoose.model('bestBuyProduct');12var bestBuyProductModel2 = mongoose.model('bestBuyProduct2');13var bestBuyProductModel3 = require('./bestBuyProduct3.js');14var bestBuyProductModel4 = require('./bestBuyProduct4.js');15var bestBuyProductModel5 = require('./bestBuyProduct5.js');16var bestBuyProductModel6 = require('./bestBuyProduct6.js');17var bestBuyProductModel7 = require('./bestBuyProduct7.js');18var bestBuyProductModel8 = require('./bestBuyProduct8.js');19var bestBuyProductModel9 = require('./bestBuyProduct9.js');20var bestBuyProductModel10 = require('./bestBuyProduct10.js');21var bestBuyProductModel11 = require('./bestBuyProduct11.js');22var bestBuyProductModel12 = require('./bestBuyProduct12.js');23var bestBuyProductModel13 = require('./bestBuyProduct13.js');24var bestBuyProductModel14 = require('./bestBuyProduct14.js');25var bestBuyProductModel15 = require('./bestBuyProduct15.js');26var bestBuyProductModel16 = require('./bestBuyProduct16.js');
Using AI Code Generation
1var http = require('http');2var url = require('url');3var querystring = require('querystring');4var port = 3000;5http.createServer(function (req, res) {6 var url_parts = url.parse(req.url, true);7 var query = url_parts.query;8 var search = querystring.unescape(query.search);9 var key = querystring.unescape(query.key);10 var path = '/v1/products((search=' + search + '))?show=name,salePrice,longDescription&pageSize=2&format=json&apiKey=' + key;11 var options = {12 };13 http.request(options, function (bb_res) {14 var str = '';15 bb_res.on('data', function (chunk) {16 str += chunk;17 });18 bb_res.on('end', function () {19 var json = JSON.parse(str);20 var products = json.products;21 res.writeHead(200, {'Content-Type': 'text/plain'});22 res.write('Best Buy for ' + search + ':23');24 for (var i = 0; i < products.length; i++) {25 var product = products[i];26 res.write(product.name + ' - $' + product.salePrice + '27');28 }29 res.end();30 });31 }).end();32}).listen(port);
Using AI Code Generation
1function showItems(response) {2 console.log(response);3 var items = response.items;4 var html = "";5 for (var i = 0; i < items.length; i++) {6 var item = items[i];7 var name = item.name;8 var image = item.image;9 var salePrice = item.salePrice;10 var regularPrice = item.regularPrice;11 var buyUrl = item.url;12 html += "<tr>";13 html += "<td>" + name + "</td>";14 html += "<td><img src='" + image + "'></td>";15 html += "<td>$" + salePrice + "</td>";16 html += "<td>$" + regularPrice + "</td>";17 html += "<td><a href='" + buyUrl + "'>Buy Now</a></td>";18 html += "</tr>";19 }20 document.getElementById("target").innerHTML = html;21}22function showError() {23 document.getElementById("target").innerHTML = "Error!";24}25function search() {26 var searchTerm = document.getElementById("search").value;27 var request = new XMLHttpRequest();
Using AI Code Generation
1function getProducts() {2 var searchTerm = $("#searchTerm").val();3 var sortBy = $("#sortBy").val();4 $.getJSON(url, function(data) {5 if (data.error) {6 $("#results").html("<p>" + data.error + "</p>");7 } else {8 var html = "";9 for (var i = 0; i < data.products.length; i++) {10 var name = data.products[i].name;11 var image = data.products[i].image;12 var price = data.products[i].salePrice;13 var sku = data.products[i].sku;14 html += '<div class="product"><img src="' + image + '" /><p>' + name + '</p><p>$' + price + '</p><p>' + sku + '</p></div>';15 }16 $("#results").html(html);17 }18 });19}20$(document).ready(function() {21 getProducts();22});23function getProducts() {24 var searchTerm = $("#searchTerm").val();
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!!