Search Results

Search found 878 results on 36 pages for 'pairs'.

Page 1/36 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • (SQL) Selecting from a database based on multiple pairs of pairs

    - by Owen Allen
    The problem i've encountered is attempting to select rows from a database where 2 columns in that row align to specific pairs of data. IE selecting rows from data where id = 1 AND type = 'news'. Obviously, if it was 1 simple pair it would be easy, but the issue is we are selecting rows based on 100s of pair of data. I feel as if there must be some way to do this query without looping through the pairs and querying each individually. I'm hoping some SQL stackers can provide guidance. Here's a full code break down: Lets imagine that I have the following dataset where history_id is the primary key. I simplified the structure a bit regarding the dates for ease of reading. table: history history_id id type user_id date 1 1 news 1 5/1 2 1 news 1 5/1 3 1 photo 1 5/2 4 3 news 1 5/3 5 4 news 1 5/3 6 1 news 1 5/4 7 2 photo 1 5/4 8 2 photo 1 5/5 If the user wants to select rows from the database based on a date range we would take a subset of that data. SELECT history_id, id, type, user_id, date FROM history WHERE date BETWEEN '5/3' AND '5/5' Which returns the following dataset history_id id type user_id date 4 3 news 1 5/3 5 4 news 1 5/3 6 1 news 1 5/4 7 2 photo 1 5/4 8 2 photo 1 5/5 Now, using that subset of data I need to determine how many of those entries represent the first entry in the database for each type,id pairing. IE is row 4 the first time in the database that id: 3, type: news appears. So I use a with() min() query. In real code the two lists are programmatically generated from the result sets of our previous query, here I spelled them out for ease of reading. WITH previous AS ( SELECT history_id, id, type FROM history WHERE id IN (1,2,3,4) AND type IN ('news','photo') ) SELECT min(history_id) as history_id, id, type FROM previous GROUP BY id, type Which returns the following data set. history_id id type user_id date 1 1 news 1 5/1 2 1 news 1 5/1 3 1 photo 1 5/2 4 3 news 1 5/3 5 4 news 1 5/3 6 1 news 1 5/4 7 2 photo 1 5/4 8 2 photo 1 5/5 You'll notice it's the entire original dataset, because we are matching id and type individually in lists, rather than as a collective pairs. The result I desire is, but I can't figure out the SQL to get this result. history_id id type user_id date 1 1 news 1 5/1 4 3 news 1 5/3 5 4 news 1 5/3 7 2 photo 1 5/4 Obviously, I could go the route of looping through each pair and querying the database to determine it's first result, but that seems an inefficient solution. I figured one of the SQL gurus on this site might be able to spread some wisdom. In case I'm approaching this situation incorrectly, the gist of the whole routine is that the database stores all creations and edits in the same table. I need to track each users behavior and determine how many entries in the history table are edits or creations over a specific date range. Therefore I select all type:id pairs from the date range based on a user_id, and then for each pairing I determine if the user is responsible for the first that occurs in the database. If first, then creation else edit. Any assistance would be awesome.

    Read the article

  • Java enum pairs / "subenum" or what exactly?

    - by vemalsar
    I have an RPG-style Item class and I stored the type of the item in enum (itemType.sword). I want to store subtype too (itemSubtype.long), but I want to express the relation between two data type (sword can be long, short etc. but shield can't be long or short, only round, tower etc). I know this is wrong source code but similar what I want: enum type { sword; } //not valid code! enum swordSubtype extends type.sword { short, long } Question: How can I define this connection between two data type (or more exactly: two value of the data types), what is the most simple and standard way? Array-like data with all valid (itemType,itemSubtype) enum pairs or (itemType,itemSubtype[]) so more subtype for one type, it would be the best. OK but how can I construct this simplest way? Special enum with "subenum" set or second level enum or anything else if it does exists 2 dimensional "canBePairs" array, itemType and itemSubtype dimensions with all type and subtype and boolean elements, "true" means itemType (first dimension) and itemSubtype (second dimension) are okay, "false" means not okay Other better idea Thank you very much!

    Read the article

  • Pairs from single list

    - by Apalala
    Often enough, I've found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google: pairs = zip(t[::2], t[1::2]) I thought that was pythonic enough, but after a recent discussion involving idioms versus efficiency, I decided to do some tests: import time from itertools import islice, izip def pairs_1(t): return zip(t[::2], t[1::2]) def pairs_2(t): return izip(t[::2], t[1::2]) def pairs_3(t): return izip(islice(t,None,None,2), islice(t,1,None,2)) A = range(10000) B = xrange(len(A)) def pairs_4(t): # ignore value of t! t = B return izip(islice(t,None,None,2), islice(t,1,None,2)) for f in pairs_1, pairs_2, pairs_3, pairs_4: # time the pairing s = time.time() for i in range(1000): p = f(A) t1 = time.time() - s # time using the pairs s = time.time() for i in range(1000): p = f(A) for a, b in p: pass t2 = time.time() - s print t1, t2, t2-t1 These were the results on my computer: 1.48668909073 2.63187503815 1.14518594742 0.105381965637 1.35109519958 1.24571323395 0.00257992744446 1.46182489395 1.45924496651 0.00251388549805 1.70076990128 1.69825601578 If I'm interpreting them correctly, that should mean that the implementation of lists, list indexing, and list slicing in Python is very efficient. It's a result both comforting and unexpected. Is there another, "better" way of traversing a list in pairs? Note that if the list has an odd number of elements then the last one will not be in any of the pairs. Which would be the right way to ensure that all elements are included? I added these two suggestions from the answers to the tests: def pairwise(t): it = iter(t) return izip(it, it) def chunkwise(t, size=2): it = iter(t) return izip(*[it]*size) These are the results: 0.00159502029419 1.25745987892 1.25586485863 0.00222492218018 1.23795199394 1.23572707176 Results so far Most pythonic and very efficient: pairs = izip(t[::2], t[1::2]) Most efficient and very pythonic: pairs = izip(*[iter(t)]*2) It took me a moment to grok that the first answer uses two iterators while the second uses a single one. To deal with sequences with an odd number of elements, the suggestion has been to augment the original sequence adding one element (None) that gets paired with the previous last element, something that can be achieved with itertools.izip_longest().

    Read the article

  • How to display/define Mirror/Stripping pairs with mdadm

    - by Chris
    I want to make a standard linux software Raid10 over 4 HDD. The server has 4HDDs, 2 pairs from different vendors in order to avoid batch problems. I want to have the mirror over two different Vendors, and then the Stripe over the mirror pairs. I could do that by manually creating Raid1/0, but mdadm supports Raid level 10. I just cant figure out how the Raid10 is then handled and how the data is distributed. mdadm --detail /dev/md10 /dev/md10: Version : 1.2 Creation Time : Wed May 28 11:06:23 2014 Raid Level : raid10 Array Size : 1953260544 (1862.77 GiB 2000.14 GB) Used Dev Size : 976630272 (931.39 GiB 1000.07 GB) Raid Devices : 4 Total Devices : 4 Persistence : Superblock is persistent Update Time : Wed May 28 11:06:23 2014 State : clean, resyncing (PENDING) Active Devices : 4 Working Devices : 4 Failed Devices : 0 Spare Devices : 0 Layout : near=2 Chunk Size : 512K Name : pdwhost:10 (local to host pdwhost) UUID : a3de0ad5:9e694ee1:addc6786:c4449e40 Events : 0 Number Major Minor RaidDevice State 0 8 1 0 active sync /dev/sda1 1 8 81 1 active sync /dev/sdf1 2 8 97 2 active sync /dev/sdg1 3 8 113 3 active sync /dev/sdh1 does not really give any information about that. How it should be: Raid 1 / Mirror over /dev/sda1 /dev/sdf1 and /dev/sdg1 /dev/sdh1 Raid 0 over the two Raid 1 pairs Is it possible to do that with the built in "level=10", how can I see what pairs are mirrored? Thanks a lot for you help

    Read the article

  • Comparing Apples and Pairs

    - by Tony Davis
    A recent study, High Costs and Negative Value of Pair Programming, by Capers Jones, pulls no punches in its assessment of the costs-to- benefits ratio of pair programming, two programmers working together, at a single computer, rather than separately. He implies that pair programming is a method rushed into production on a wave of enthusiasm for Agile or Extreme Programming, without any real regard for its effectiveness. Despite admitting that his data represented a far from complete study of the economics of pair programming, his conclusions were stark: it was 2.5 times more expensive, resulted in a 15% drop in productivity, and offered no significant quality benefits. The author provides a more scientific analysis than Jon Evans’ Pair Programming Considered Harmful, but the theme is the same. In terms of upfront-coding costs, pair programming is surely more expensive. The claim of productivity loss is dubious and contested by other studies. The third claim, though, did surprise me. The author’s data suggests that if both the pair and the individual programmers employ static code analysis and testing, then there is no measurable difference in the resulting code quality, in terms of defects per function point. In other words, pair programming incurs a massive extra cost for no tangible return in investment. There were, inevitably, many criticisms of his data and his conclusions, a few of which are persuasive. Firstly, that the driver/observer model of pair programming, on which the study bases its findings, is far from the most effective. For example, many find Ping-Pong pairing, based on use of test-driven development, far more productive. Secondly, that it doesn’t distinguish between “expert” and “novice” pair programmers– that is, independently of other programming skills, how skilled was an individual at pair programming. Thirdly, that his measure of quality is too narrow. This point rings true, certainly at Red Gate, where developers don’t pair program all the time, but use the method in short bursts, while tackling a tricky problem and needing a fresh perspective on the best approach, or more in-depth knowledge in a particular domain. All of them argue that pair programming, and collective code ownership, offers significant rewards, if not in terms of immediate “bug reduction”, then in removing the likelihood of single points of failure, and improving the overall quality and longer-term adaptability/maintainability of the design. There is also a massive learning benefit for both participants. One developer told me how he once worked in the same team over consecutive summers, the first time with no pair programming and the second time pair-programming two-thirds of the time, and described the increased rate of learning the second time as “phenomenal”. There are a great many theories on how we should develop software (Scrum, XP, Lean, etc.), but woefully little scientific research in their effectiveness. For a group that spends so much time crunching other people’s data, I wonder if developers spend enough time crunching data about themselves. Capers Jones’ data may be incomplete, but should cause a pause for thought, especially for any large IT departments, supporting commerce and industry, who are considering pair programming. It certainly shouldn’t discourage teams from exploring new ways of developing software, as long as they also think about how to gather hard data to gauge their effectiveness.

    Read the article

  • How can I permute pairs across a set?

    - by sila
    I am writing a bet settling app in C# and WinForms. I have 6 selections, 4 of them have won. I know that using the following formula from Excel: =FACT(selections)/(FACT(selections-doubles))/FACT(doubles) This is coded into my app and working well: I can work out how many possible doubles (e.g., AB, AC, AD, AE, BC, BD, BE, etc.) need to be resolved. But what I can't figure out is how to do the actual calculation. How can I efficiently code it so that every combination of A, B, C, and D has been calculated? All my efforts thus far on paper have proved to be ugly and verbose: is there an elegant solution to this problem?

    Read the article

  • Creating deterministic key pairs in javascript for use in encrypting/decrypting/signing messages

    - by SlickTheNick
    So I have been searching everywhere and havn't been able to find anything with the sufficient information I need.. so Im a bit stumped on this one at the moment What I am trying to do is create a public/private key pair (like PGP) upon a users account creation, based on their passphrase and a random seed. The public key would be saved on the server, and ideally the private key would never be seen by the server whatsoever. The user could then sign in, and send a message to another user. Before the message is sent, the senders key pair would be re-generated on the fly based on their credentials (and maybe a password prompt) and used to encrypt the message. The receiver would then use their own re-generated private key to decrypt said message. The server itself should never see any plaintext passwords, private keys or readable messages. Bit unsure how on how I could go about implementing this. Iv been looking into PGP, specifically openPGP.js. The main trouble I am having is being able to regenerate the key-pair based off a specific seed. PGP seems to have a random output even if the inputs are the same. Storing the private key in a cookie or in HTML5 storage or something also isnt really an option, too unreliable. Can anyone point me in the right direction?

    Read the article

  • How to shuffle pairs

    - by Jessy
    How to shuffle the elements in the pairs? The program below, generate all possible pairs and later shuffle the pairs. e.g. possible pairs before shuffle is ab,ac,ae,af..etc shuffled to ac,ae,af,ab...etc How to make it not only shuffled in pairs but within the elements in the pair itself? e.g. instead of ab, ac, how can I make ba, ac ? String[] pictureFile = {"a.jpg","b.jpg","c.jpg","d.jpg","e.jpg","f.jpg","g.jpg"}; List <String> pic1= Arrays.asList(pictureFile); ... ListGenerator pic2= new ListGenerator(pic1); ArrayList<ArrayList<Integer>> pic2= new ArrayList<ArrayList<Integer>>(); public class ListGenerator { public ListGenerator(List<String> pic1) { int size = pic1.size(); // create a list of all possible combinations for(int i = 0 ; i < size ; i++) { for(int j = (i+1) ; j < size ; j++) { ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(i); temp.add(j); pic2.add(temp); } } Collections.shuffle(pic2); } //This method return the shuffled list public ArrayList<ArrayList<Integer>> getList() { return pic2; } }

    Read the article

  • Efficient way to get highly correlated pairs from large data set in Python or R

    - by Akavall
    I have a large data set (Let's say 10,000 variables with about 1000 elements each), we can think of it as 2D list, something like: [[variable_1], [variable_2], ............ [variable_n] ] I want to extract highly correlated variable pairs from that data. I want "highly correlated" to be a parameter that I can choose. I don't need all pairs to be extracted, and I don't necessarily want the most correlated pairs. As long as there is an efficient method that gets me highly correlated pairs I am happy. Also, it would be nice if a variable does not show up in more than one pair. Although this might not be crucial. Of course, there is a brute force way to finding such pairs, but it is too slow for me. I've googled around for a bit and found some theoretical work on this issue, but I wasn't able for find a package that could do what I am looking for. I mostly work in python, so a package in python would be most helpful, but if there exists a package in R that does what I am looking for it will be great. Does anyone know of a package that does the above in Python or R? Or any other ideas? Thank You in Advance

    Read the article

  • Multiple public/private key pairs for the same user

    - by bruceb
    First, sorry if this question has already been asked/answered - I've searched but perhaps I haven't recognised the answer.... What we have is a cluster of servers which need to access a single remote server using sftp. We are migrating from one remote server to another at the same (remote) location. We also want to refresh the public/private key pairs on the configuration as part of an ongoing security review. My question is - can we have multiple public/private key pairs for the same user between server A and server B? I want to do this to allow for cutover testing - but am concerned that the software checking keys may only try one of each type (rsa/dsa?) before rejecting the connection method and moving to the next type of key. Hope it's a straightforward question - please let me know if I need to supply more details. Thanks in advance Bruce

    Read the article

  • On counting pairs of words that differ by one letter

    - by Quintofron
    Let us consider n words, each of length k. Those words consist of letters over an alphabet (whose cardinality is n) with defined order. The task is to derive an O(nk) algorithm to count the number of pairs of words that differ by one position (no matter which one exactly, as long as it's only a single position). For instance, in the following set of words (n = 5, k = 4): abcd, abdd, adcb, adcd, aecd there are 5 such pairs: (abcd, abdd), (abcd, adcd), (abcd, aecd), (adcb, adcd), (adcd, aecd). So far I've managed to find an algorithm that solves a slightly easier problem: counting the number of pairs of words that differ by one GIVEN position (i-th). In order to do this I swap the letter at the ith position with the last letter within each word, perform a Radix sort (ignoring the last position in each word - formerly the ith position), linearly detect words whose letters at the first 1 to k-1 positions are the same, eventually count the number of occurrences of each letter at the last (originally ith) position within each set of duplicates and calculate the desired pairs (the last part is simple). However, the algorithm above doesn't seem to be applicable to the main problem (under the O(nk) constraint) - at least not without some modifications. Any idea how to solve this?

    Read the article

  • JavaScript and ASP.NET - Cookies with Key / Value Pairs

    - by user208662
    Hello, This question mixes client-side scripting with server-side parsing. In some cases, I'm writing a cookie to the user's browser using the document.cookie property. In other cases, I'm writing the same cookie to the user's browser through the ASP.NET Response object. When I'm writing the HttpCookie on the server-side, I am using the Values collection (http://msdn.microsoft.com/en-US/library/system.web.httpcookie.values%28v=VS.80%29.aspx) to store key/value pairs in the cookie. I would also like to be able to write key-value pairs to the cookie through JavaScript. How do I create cookies with Key/Value pairs via JavaScript that ASP.NET can parse? Thank you!

    Read the article

  • Set-up SSHD to handle multiple key pairs.

    - by Warlax
    Hey guys, I am trying to set up my sshd to accept users that do not have a system user account. My approach is to use DSA public/private key pairs. I generated a key pair: $ ssh-keygen -t dsa I copied id_dsa.pub to the server machine where sshd runs. I appended the line from id_dsa.pub to ~/.ssh/authorized_keys of the single existing system user account I will use for every 'external' user. I tried to ssh as the 'external' user into the machine where I set-up the authorized_keys and failed miserably. What am I missing here? Thanks.

    Read the article

  • Iterating over key/value pairs in a dict sorted by keys

    - by Helper Method
    I have the following code, which just print the key/value pairs in a dict (the pairs are sorted by keys): for word, count in sorted(count_words(filename).items()): print word, count However, calling iteritems() instead of items() produces the same output for word, count in sorted(count_words(filename).iteritems()): print word, count Now, which one should I choose in this situation? I consulted the Python tutorial but it doesn't really answer my question.

    Read the article

  • Four disks - RAID 10 or two mirrored pairs?

    - by ewwhite
    I have this discussion with developers quite often. The context is an application running in Linux that has a medium amount of disk I/O. The servers are HP ProLiant DL3x0 G6 with four disks of equal size @ 15k rpm, backed with a P410 controller and 512MB of battery or flash-based cache. There are two schools of thought here, and I wanted some feedback... 1). I'm of the mind that it makes sense to create an array containing all four disks set up in a RAID 10 (1+0) and partition as necessary. This gives the greatest headroom for growth, has the benefit of leveraging the higher spindle count and better fault-tolerance without degradation. 2). The developers think that it's better to have multiple RAID 1 pairs. One for the OS and one for the application data, citing that the spindle separation would reduce resource contention. However, this limits throughput by halving the number of drives and in this case, the OS doesn't really do much other than regular system logging. Additionally, the fact that we have the battery RAID cache and substantial RAM seems to negate the impact of disk latency... What are your thoughts?

    Read the article

  • Serializing a list of Key/Value pairs to XML

    - by Slauma
    I have a list of key/value pairs I'd like to store in and retrieve from a XML file. So this task is similar as described here. I am trying to follow the advice in the marked answer (using a KeyValuePair and a XmlSerializer) but I don't get it working. What I have so far is a "Settings" class ... public class Settings { public int simpleValue; public List<KeyValuePair<string, int>> list; } ... an instance of this class ... Settings aSettings = new Settings(); aSettings.simpleValue = 2; aSettings.list = new List<KeyValuePair<string, int>>(); aSettings.list.Add(new KeyValuePair<string, int>("m1", 1)); aSettings.list.Add(new KeyValuePair<string, int>("m2", 2)); ... and the following code to write that instance to a XML file: XmlSerializer serializer = new XmlSerializer(typeof(Settings)); TextWriter writer = new StreamWriter("c:\\testfile.xml"); serializer.Serialize(writer, aSettings); writer.Close(); The resulting file is: <?xml version="1.0" encoding="utf-8"?> <Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <simpleValue>2</simpleValue> <list> <KeyValuePairOfStringInt32 /> <KeyValuePairOfStringInt32 /> </list> </Settings> So neither key nor value of the pairs in my list are stored though the number of elements is correct. Obviously I am doing something basically wrong. My questions are: How can I store the key/value pairs of the list in the file? How can I change the default generated name "KeyValuePairOfStringInt32" of the elements in the list to some other name like "listElement" I'd like to have?

    Read the article

  • Pair programming: How should the pairs be chosen?

    - by Jon Seigel
    This topic has been covered peripherally in bits and pieces in some of the other pair-programming questions, but I want to (a) consolidate this knowledge into a separate question, and, most importantly, (b) go into much more depth on the subject. From the perspective of being an effective manager, how should pairs be arranged for pair programming to maximize both the happiness and productivity of the overall team? Some ideas to get started: Should two people never be paired (because of personalities, for example)? How much overlap in skillsets is needed? How much disconnect in skillsets is too much to overcome? (No two people will overlap 100%, and a disconnect in skills can be very beneficial to both people.) Should everyone pair with everyone else on a fixed/rotating basis? Should certain pairs be arranged to accomplish specific tasks? How important a role does HR play when growing or reorganizing the team?

    Read the article

  • Binding key/value pairs loaded from xml

    - by Hichem
    I want to load key/values configuration pairs stored in XML file. To bind a collection of data i know i need to use the ArrayList class, but the problem is that i want to be able to bind the loaded values using their corresponding keys and not by their indexes in the ArrayList object. For example i want to be able to do this : <mx:Text id="errorText" text="{Config.params['someKey']}" /> instead of : <mx:Text id="errorText" text="{Config.params[0]}" /> where Config.params is ArrayList (obviously i couldn't use ArrayList since it doesn't allow selecting a value by key) So the question is how to bind the key/value pairs loaded form XML. I don't want to go manually set variables, i want to bind them so when they are loaded the are set automatically. Did anyone had to do something like that ?

    Read the article

  • Operate on pairs of rows of a data frame

    - by lorin
    I've got a data frame in R, and I'd like to perform a calculation on all pairs of rows. Is there a simpler way to do this than using a nested for loop? To make this concrete, consider a data frame with ten rows, and I want to calculate the difference of scores between all (45) possible pairs. > data.frame(ID=1:10,Score=4*10:1) ID Score 1 1 40 2 2 36 3 3 32 4 4 28 5 5 24 6 6 20 7 7 16 8 8 12 9 9 8 10 10 4 I know I could do this calculation with a nested for loop, but is there a better (more R-ish) way to do it?

    Read the article

  • How to deal with name/value pairs of function arguments in MATLAB

    - by Richie Cotton
    I have a function that takes optional arguments as name/value pairs. function example(varargin) % Lots of set up stuff vargs = varargin; nargs = length(vargs); names = vargs(1:2:nargs); values = vargs(2:2:nargs); validnames = {'foo', 'bar', 'baz'}; for name = names validatestring(name{:}, validnames); end % Do something ... foo = strmatch('foo', names); disp(values(foo)) end example('foo', 1:10, 'bar', 'qwerty') It seems that there is a lot of effort involved in extracting the appropriate values (and it still isn't particularly robust again badly specified inputs). Is there a better way of handling these name/value pairs? Are there any helper functions that come with MATLAB to assist?

    Read the article

  • Converting non-delimited text into name/value pairs in Delphi

    - by robsoft
    I've got a text file that arrives at my application as many lines of the following form: <row amount="192.00" store="10" transaction_date="2009-10-22T12:08:49.640" comp_name="blah " comp_ref="C65551253E7A4589A54D7CCD468D8AFA" name="Accrington "/> and I'd like to turn this 'row' into a series of name/value pairs in a given TStringList (there could be dozens of these <row>s in the file, so eventually I will want to iterate through the file breaking each row into name/value pairs in turn). The problem I've got is that the data isn't obviously delimited (technically, I suppose it's space delimited). Now if it wasn't for the fact that some of the values contain leading or trailing spaces, I could probably make a few reasonable assumptions and code something to break a row up based on spaces. But as the values themselves may or may not contain spaces, I don't see an obvious way to do this. Delphi' TStringList.CommaText doesn't help, and I've tried playing around with Delimiter but I get caught-out by the spaces inside the values each time. Does anyone have a clever Delphi technique for turning the sample above into something resembling this? ; amount="192.00" store="10" transaction_date="2009-10-22T12:08:49.640" comp_name="blah " comp_ref="C65551253E7A4589A54D7CCD468D8AFA" name="Accrington " Unfortunately, as is usually the case with this kind of thing, I don't have any control over the format of the data to begin with - I can't go back and 'make' it comma delimited at source, for instance. Although I guess I could probably write some code to turn it into comma delimited - would rather find a nice way to work with what I have though. This would be in Delphi 2007, if it makes any difference.

    Read the article

  • using Python reduce over a list of pairs

    - by user248237
    I'm trying to pair together a bunch of elements in a list to create a final object, in a way that's analogous to making a sum of objects. I'm trying to use a simple variation on reduce where you consider a list of pairs rather than a flat list to do this. I want to do something along the lines of: nums = [1, 2, 3] reduce(lambda x, y: x + y, nums) except I'd like to add additional information to the sum that is specific to each element in the list of numbers nums. For example for each pair (a,b) in the list, run the sum as (a+b): nums = [(1, 0), (2, 5), (3, 10)] reduce(lambda x, y: (x[0]+x[1]) + (y[0]+y[1]), nums) This does not work: >>> reduce(lambda x, y: (x[0]+x[1]) + (y[0]+y[1]), nums) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> TypeError: 'int' object is unsubscriptable Why does it not work? I know I can encode nums as a flat list - that is not the point - I just want to be able to create a reduce operation that can iterate over a list of pairs, or over two lists of the same length simultaneously and pool information from both lists. thanks.

    Read the article

  • Divide sequence elements into pairs

    - by alex
    I have a sequence of 16 elements: 1,2,3,..., 16 ( or 2*n elements). Sequence elements always goes from 1 to length(sequence) that is sequence of 4 elements is 1,2,3,4. I want to write an algorithm which divide elements into pairs. For Example, 1-15 2-16 3-13 4-9 5-14 6-10 7-11 8-12 PS: no linq please :)

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >