Search Results

Search found 355 results on 15 pages for 'tuple'.

Page 8/15 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • How to give points for each indices of list

    - by Eric Jung
    def voting_borda(rank_ballots): '''(list of list of str) -> tuple of (str, list of int) The parameter is a list of 4-element lists that represent rank ballots for a single riding. The Borda Count is determined by assigning points according to ranking. A party gets 3 points for each first-choice ranking, 2 points for each second-choice ranking and 1 point for each third-choice ranking. (No points are awarded for being ranked fourth.) For example, the rank ballot shown above would contribute 3 points to the Liberal count, 2 points to the Green count and 1 point to the CPC count. The party that receives the most points wins the seat. Return a tuple where the first element is the name of the winning party according to Borda Count and the second element is a four-element list that contains the total number of points for each party. The order of the list elements corresponds to the order of the parties in PARTY_INDICES.''' #>>> voting_borda([['GREEN','NDP', 'LIBERAL', 'CPC'], ['GREEN','CPC','LIBERAL','NDP'], ['LIBERAL','NDP', 'CPC', 'GREEN']]) #('GREEN',[4, 6, 5, 3]) list_of_party_order = [] for sublist in rank_ballots: for party in sublist[0]: if party == 'GREEN': GREEN_COUNT += 3 elif party == 'NDP': NDP_COUNT += 3 elif party == 'LIBERAL': LIBERAL_COUNT += 3 elif party == 'CPC': CPC_COUNT += 3 for party in sublist[1]: if party == 'GREEN': GREEN_COUNT += 2 elif party == 'NDP': NDP_COUNT += 2 elif party == 'LIBERAL': LIBERAL_COUNT += 2 elif party == 'CPC': CPC_COUNT += 2 for party in sublist[2]: if party == 'GREEN': GREEN_COUNT += 1 elif party == 'NDP': NDP_COUNT += 1 elif party == 'LIBERAL': LIBERAL_COUNT += 1 elif party == 'CPC': CPC_COUNT += 1 I don't know how I would give points for each indices of the list MORE SIMPLY. Can someone please help me? Without being too complicated. Thank you!

    Read the article

  • How create new array which subtracts values from 2 double arrays in C#?

    - by Tomek eM
    Helou it's my problem, I have 2 array which have double values: (this is function which get back values(latitude) from richTextBox) private Tuple<double>[] szerokosc(string[] lines) { return Array.ConvertAll(lines, line => { string[] elems = line.Split(','); double we = 0.01 * double.Parse(elems[3], EnglishCulture); int stopnie = (int)we; double minuty = ((we - stopnie) * 100) / 60; double szerokosc_dziesietna = stopnie + minuty; return new Tuple<double>(Math.Round(szerokosc_dziesietna, (int)numericUpDown2.Value)); }); ; } (this part of code call function) var data1 = szerokosc(szerdlugeo_diag_gps.Lines); var data2 = szerokosc(szerdlugeo_diag_gpsglonass.Lines); What should I do, to get something like this: for example: var data3 = data1 - data2; My values in this data looks like (f.e.) data1 = (x11, x12, ... x1(n) ): 53.11818160073043, 53.11816348903661, 53.11814874695463, ... data2 = (x21, x22, ... x(2n) ): 53.11814200771546, 53.118131477652156, 53.11812263239697, 53.11811884157276, 53.11811631435644, .... I would like back data3 = (x31=x11-x21, x32=x12=x22, ... x(3n)=x(1n)-x(2n) ) It would be good if it included the following condition: if data1 = ( 1, 5, 6, 8) data2 = (1.5, 3.3) data3 = (-0.5, 1.7) not data3 = (-0.5, 1.7, 6, 8) Please help.

    Read the article

  • Good functions and techniques for dealing with haskell tuples?

    - by toofarsideways
    I've been doing a lot of work with tuples and lists of tuples recently and I've been wondering if I'm being sensible. Things feel awkward and clunky which for me signals that I'm doing something wrong. For example I've written three convenience functions for getting the first, second and third value in a tuple of 3 values. Is there a better way I'm missing? Are there more general functions that allow you to compose and manipulate tuple data? Here are some things I am trying to do that feel should be generalisable. Extracting values: Do I need to create a version of fst,snd,etc... for tuples of size two, three, four and five, etc...? fst3(x,_,_) = x fst4(x,_,_,_) = x Manipulating values: Can you increment the last value in a list of pairs and then use that same function to increment the last value in a list of triples? Zipping and Unzipping values: There is a zip and a zip3. Do I also need a zip4? or is there some way of creating a general zip function? Sorry if this seems subjective, I honestly don't know if this is even possible or if I'm wasting my time writing 3 extra functions every time I need a general solution. Thank you for any help you can give!

    Read the article

  • Dynamic programming Approach- Knapsack Puzzle

    - by idalsin
    I'm trying to solve the Knapsack problem with the dynamical programming(DP) approach, with Python 3.x. My TA pointed us towards this code for a head start. I've tried to implement it, as below: def take_input(infile): f_open = open(infile, 'r') lines = [] for line in f_open: lines.append(line.strip()) f_open.close() return lines def create_list(jewel_lines): #turns the jewels into a list of lists jewels_list = [] for x in jewel_lines: weight = x.split()[0] value = x.split()[1] jewels_list.append((int(value), int(weight))) jewels_list = sorted(jewels_list, key = lambda x : (-x[0], x[1])) return jewels_list def dynamic_grab(items, max_weight): table = [[0 for weight in range(max_weight+1)] for j in range(len(items)+1)] for j in range(1,len(items)+1): val= items[j-1][0] wt= items[j-1][1] for weight in range(1, max_weight+1): if wt > weight: table[j][weight] = table[j-1][weight] else: table[j][weight] = max(table[j-1][weight],table[j-1][weight-wt] + val) result = [] weight = max_weight for j in range(len(items),0,-1): was_added = table[j][weight] != table[j-1][weight] if was_added: val = items[j-1][0] wt = items[j-1][1] result.append(items[j-1]) weight -= wt return result def totalvalue(comb): #total of a combo of items totwt = totval = 0 for val, wt in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= max_weight else (0,0) #required setup of variables infile = "JT_test1.txt" given_input = take_input(infile) max_weight = int(given_input[0]) given_input.pop(0) jewels_list = create_list(given_input) #test lines print(jewels_list) print(greedy_grab(jewels_list, max_weight)) bagged = dynamic_grab(jewels_list, max_weight) print(totalvalue(bagged)) The sample case is below. It is in the format line[0] = bag_max, line[1:] is in form(weight, value): 575 125 3000 50 100 500 6000 25 30 I'm confused as to the logic of this code in that it returns me a tuple and I'm not sure what the output tuple represents. I've been looking at this for a while and just don't understand what the code is pointing me at. Any help would be appreciated.

    Read the article

  • creating a color coded time chart using colorbar and colormaps in python

    - by Rusty
    I'm trying to make a time tracking chart based on a daily time tracking file that I used. I wrote code that crawls through my files and generates a few lists. endTimes is a list of times that a particular activity ends in minutes going from 0 at midnight the first day of the month to however many minutes are in a month. labels is a list of labels for the times listed in endTimes. It is one shorter than endtimes since the trackers don't have any data about before 0 minute. Most labels are repeats. categories contains every unique value of labels in order of how well I regard that time. I want to create a colorbar or a stack of colorbars (1 for eachday) that will depict how I spend my time for a month and put a color associated with each label. Each value in categories will have a color associated. More blue for more good. More red for more bad. It is already in order for the jet colormap to be right, but I need to get desecrate color values evenly spaced out for each value in categories. Then I figure the next step would be to convert that to a listed colormap to use for the colorbar based on how the labels associated with the categories. I think this is the right way to do it, but I am not sure. I am not sure how to associate the labels with color values. Here is the last part of my code so far. I found one function to make a discrete colormaps. It does, but it isn't what I am looking for and I am not sure what is happening. Thanks for the help! # now I need to develop the graph import numpy as np from matplotlib import pyplot,mpl import matplotlib from scipy import interpolate from scipy import * def contains(thelist,name): # checks if the current list of categories contains the one just read for val in thelist: if val == name: return True return False def getCategories(lastFile): ''' must determine the colors to use I would like to make a gradient so that the better the task, the closer to blue bad labels will recieve colors closer to blue read the last file given for the information on how I feel the order should be then just keep them in the order of how good they are in the tracker use a color range and develop discrete values for each category by evenly spacing them out any time not found should assume to be sleep sleep should be white ''' tracker = open(lastFile+'.txt') # open the last file # find all the categories categories = [] for line in tracker: pos = line.find(':') # does it have a : or a ? if pos==-1: pos=line.find('?') if pos != -1: # ignore if no : or ? name = line[0:pos].strip() # split at the : or ? if contains(categories,name)==False: # if the category is new categories.append(name) # make a new one return categories # find good values in order of last day newlabels=[] for val in getCategories(lastDay): if contains(labels,val): newlabels.append(val) categories=newlabels # convert discrete colormap to listed colormap python for ii,val in enumerate(labels): if contains(categories,val)==False: labels[ii]='sleep' # create a figure fig = pyplot.figure() axes = [] for x in range(endTimes[-1]%(24*60)): ax = fig.add_axes([0.05, 0.65, 0.9, 0.15]) axes.append(ax) # figure out the colors to use # stole this function to make a discrete colormap # http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations def cmap_discretize(cmap, N): """Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: Number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ cdict = cmap._segmentdata.copy() # N colors colors_i = np.linspace(0,1.,N) # N+1 indices indices = np.linspace(0,1.,N+1) for key in ('red','green','blue'): # Find the N colors D = np.array(cdict[key]) I = interpolate.interp1d(D[:,0], D[:,1]) colors = I(colors_i) # Place these colors at the correct indices. A = zeros((N+1,3), float) A[:,0] = indices A[1:,1] = colors A[:-1,2] = colors # Create a tuple for the dictionary. L = [] for l in A: L.append(tuple(l)) cdict[key] = tuple(L) # Return colormap object. return matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024) # jet colormap goes from blue to red (good to bad) cmap = cmap_discretize(mpl.cm.jet, len(categories)) cmap.set_over('0.25') cmap.set_under('0.75') #norm = mpl.colors.Normalize(endTimes,cmap.N) print endTimes print labels # make a color list by matching labels to a picture #norm = mpl.colors.ListedColormap(colorList) cb1 = mpl.colorbar.ColorbarBase(axes[0],cmap=cmap ,orientation='horizontal' ,boundaries=endTimes ,ticks=endTimes ,spacing='proportional') pyplot.show()

    Read the article

  • Compound assignment operators in Python's Numpy library

    - by Leonard
    The "vectorizing" of fancy indexing by Python's numpy library sometimes gives unexpected results. For example: import numpy a = numpy.zeros((1000,4), dtype='uint32') b = numpy.zeros((1000,4), dtype='uint32') i = numpy.random.random_integers(0,999,1000) j = numpy.random.random_integers(0,3,1000) a[i,j] += 1 for k in xrange(1000): b[i[k],j[k]] += 1 Gives different results in the arrays 'a' and 'b' (i.e. the appearance of tuple (i,j) appears as 1 in 'a' regardless of repeats, whereas repeats are counted in 'b'). This is easily verified as follows: numpy.sum(a) 883 numpy.sum(b) 1000 It is also notable that the fancy indexing version is almost two orders of magnitude faster than the for loop. My question is: "Is there an efficient way for numpy to compute the repeat counts as implemented using the for loop in the provided example?"

    Read the article

  • Optimistic work sharing on sparsely distributed systems

    - by Asti
    What would a system like BOINC look like if it were written today? At the time BOINC was written, databases were the primary choice for maintaining a shared state and concurrency among nodes. Since then, many approaches have been developed for tasking with optimistic concurrency (OT, partial synchronization primitives, shared iterators etc.) Is there an optimal paradigm for optimistically distributing units of work on sparsely distributing systems which communicate through message passing? Sorry if this is a bit vague. P.S. The concept of Tuple-spaces is great, but locking is inherent to its definition. Edit: I already have a federation system which works very well. I have a reactive OT system is implemented on top of it. I'm looking to extend it to get clients to do units of work.

    Read the article

  • Fair 2-combinations

    - by Tometzky
    I need to fairly assign 2 experts from x experts (x is rather small - less than 50) for every n applications, so that: each expert has the same number of applications (+-1); each pair of experts (2-combination of x) has the same number of applications (+-1); It is simple to generate all 2-combinations: for (i=0; i<n; i++) { for (j=i+1; j<n; j++) { combinations.append(tuple(i,j)); } } But to assign experts fairly I need to assign a combination to an application i correct order, for example: experts: 0 1 2 3 4 fair combinations: counts 01234 01 11000 23 11110 04 21111 12 22211 34 22222 02 32322 13 33332 14 34333 03 44343 24 44444 I'm unable to come up with a good algorithm for this (the best I came up with is rather complicated and with O(x4) complexity). Could you help me?

    Read the article

  • How to convert strings into integers in python?

    - by elfuego1
    Hello there, I have a tuple of tuples from MySQL query like this: T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) I'd like to convert all the string elements into integers and put it back nicely to list of lists this time: T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] I tried to achieve it with "eval" but didn't get any decent result yet.

    Read the article

  • Python: How to read huge text file into memory

    - by asmaier
    I'm using Python 2.6 on a Mac Mini with 1GB RAM. I want to read in a huge text file $ ls -l links.csv; file links.csv; tail links.csv -rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv links.csv: ASCII text, with CRLF line terminators 4757187,59883 4757187,99822 4757187,66546 4757187,638452 4757187,4627959 4757187,312826 4757187,6143 4757187,6141 4757187,3081726 4757187,58197 So each line in the file consists of a tuple of two comma separated integer values. I want to read in the whole file and sort it according to the second column. I know, that I could do the sorting without reading the whole file into memory. But I thought for a file of 500MB I should still be able to do it in memory since I have 1GB available. However when I try to read in the file, Python seems to allocate a lot more memory than is needed by the file on disk. So even with 1GB of RAM I'm not able to read in the 500MB file into memory. My Python code for reading the file and printing some information about the memory consumption is: #!/usr/bin/python # -*- coding: utf-8 -*- import sys infile=open("links.csv", "r") edges=[] count=0 #count the total number of lines in the file for line in infile: count=count+1 total=count print "Total number of lines: ",total infile.seek(0) count=0 for line in infile: edge=tuple(map(int,line.strip().split(","))) edges.append(edge) count=count+1 # for every million lines print memory consumption if count%1000000==0: print "Position: ", edge print "Read ",float(count)/float(total)*100,"%." mem=sys.getsizeof(edges) for edge in edges: mem=mem+sys.getsizeof(edge) for node in edge: mem=mem+sys.getsizeof(node) print "Memory (Bytes): ", mem The output I got was: Total number of lines: 30609720 Position: (9745, 2994) Read 3.26693612356 %. Memory (Bytes): 64348736 Position: (38857, 103574) Read 6.53387224712 %. Memory (Bytes): 128816320 Position: (83609, 63498) Read 9.80080837067 %. Memory (Bytes): 192553000 Position: (139692, 1078610) Read 13.0677444942 %. Memory (Bytes): 257873392 Position: (205067, 153705) Read 16.3346806178 %. Memory (Bytes): 320107588 Position: (283371, 253064) Read 19.6016167413 %. Memory (Bytes): 385448716 Position: (354601, 377328) Read 22.8685528649 %. Memory (Bytes): 448629828 Position: (441109, 3024112) Read 26.1354889885 %. Memory (Bytes): 512208580 Already after reading only 25% of the 500MB file, Python consumes 500MB. So it seem that storing the content of the file as a list of tuples of ints is not very memory efficient. Is there a better way to do it, so that I can read in my 500MB file into my 1GB of memory?

    Read the article

  • Variadic templates in Scala

    - by Thomas Jung
    Suppose you want to have something like variadic templates (the ability to define n type parameters for a generic class) in Scala. For example you do not want to define Tuple2[+T1, +T2] and Tuple3[+T1, +T2, +T3] but Tuple[T*]. Are there other options than HLists?

    Read the article

  • F# Tacit Programming. Please help)

    - by Bubba88
    It's not a practically important issue, but could you please provide me with an example of tacit programming in F# where my `pointless' functions can have multiple arguments (not in form of list or tuple); And secondly, where those functions can manipulate a complex data structure. I'm trying to manage it in FSharp interactive, but have no success yet. Huh.. I've managed to construct something: (fun _ - (fun _ - (+))) 333 222 111 555 Is that right way?

    Read the article

  • In UDP, destination

    - by ert
    In UDP, destination IP and destination port number are used to demultiplex the packets, but in TCP destination IP, source IP, destination port number and source port numbers (4-tuple) all needed to distinguish between the connections why reasoning for this usage.

    Read the article

  • XML security in world wide web

    - by nikky
    Hi, Im a newbie in XML and i have some questions Can XML be used in stead of normal database (store data in a tuple and column) in website? XML is built to share information easier (from my understanding) such as can share cross platform and in different language used so Is it secure to store secure data in XML? thank you so much

    Read the article

  • How to turn a list of tuples into a string?

    - by matt
    I have a list of tuples that I'm trying to incorporate into a SQL query but I can't figure out how to join them together without adding slashes. My like this: list = [('val', 'val'), ('val', 'val'), ('val', 'val')] If I turn each tuple into a string and try to join them with a a comma I'll get something like ' (\'val\, \'val\'), ... ' What's the right way to do this, so I can get the list (without brackets) as a string?

    Read the article

  • MySQL SELECT Statment issue

    - by mouthpiec
    Hi, I have the following query which returns 2 tuples SELECT bar_id, bar_name, town_name, bar_telephone, subscription_type_id, type FROM towns, subscriptiontype, regions, bar LEFT JOIN barpictures bp ON bar.bar_id = bp.bar_id_fk WHERE town_id = town_id_fk AND bar.test_field = 0 AND subscription_type_id = subscription_type_id_fk AND region_id = region_id_fk AND (type like 'logo%' OR type IS NULL) The main difference between the tuples is that one has 'type' = logo and the other tuple has 'type' = logo_large. I need that instead of having two tuples, I need that I have 2 type attributes, one holding the "logo" and the other the "logo_large" eg bar_id, bar_name, town_name, bar_telephone, subscription_type_id, type1, type2 is this possible

    Read the article

  • how to create a dynamic sql statement w/ python and mysqldb

    - by Elias Bachaalany
    I have the following code: def sql_exec(self, sql_stmt, args = tuple()): """ Executes an SQL statement and returns a cursor. An SQL exception might be raised on error @return: SQL cursor object """ cursor = self.conn.cursor() if self.__debug_sql: try: print "sql_exec: " % (sql_stmt % args) except: print "sql_exec: " % sql_stmt cursor.execute(sql_stmt, args) return cursor def test(self, limit = 0): result = sql_exec(""" SELECT * FROM table """ + ("LIMIT %s" if limit else ""), (limit, )) while True: row = result.fetchone() if not row: break print row result.close() How can I nicely write test() so it works with or without 'limit' without having to write two queries?

    Read the article

  • Preserving the dimensions of a slice from a Numpy 3d array

    - by Brendan
    I have a 3d array, a, of shape say a.shape = (10, 10, 10) When slicing, the dimensions are squeezed automatically i.e. a[:,:,5].shape = (10, 10) I'd like to preserve the number of dimensions but also ensure that the dimension that was squeezed is the one that shows 1 i.e. a[:,:,5].shape = (10, 10, 1) I have thought of re-casting the array and passing ndmin but that just adds the extra dimensions to the start of the shape tuple regardless of where the slice came from in the array a.

    Read the article

  • what would be a frozen dict ?

    - by dugres
    A frozen set is a frozenset. A frozen list could be a tuple. What would be a frozen dict ? An immutable, hashable dict. I guess it could be something like collections.namedtuple, but namedtuple is more like a frozenkeys dict (an half-frozen dict). No ?

    Read the article

  • overwrite existing entity via bulkloader.Loader

    - by Ray Yun
    I was going to CSV based export/import for large data with app engine. My idea was just simple. First column of CSV would be key of entity. If it's not empty, that row means existing entity and should overwrite old one. Else, that row is new entity and should create new one. I could export key of entity by adding key property. class FrontExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'Front', [ ('__key__', str, None), ('name', str, None), ]) But when I was trying to upload CSV, it had failed because bulkloader.Loader.generate_key() was just for "key_name" not "key" itself. That means all exported entities in CSV should have unique 'key_name' if I want to modify-and-reupload them. class FrontLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Front', [ ('_UNUSED', lambda x: None), ('name', lambda x: x.decode('utf-8')), ]) def generate_key(self,i,values): # first column is key keystr = values[0] if len(keystr)==0: return None return keystr I also tried to load key directly without using generate_key(), but both failed. class FrontLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'Front', [ ('Key', db.Key), # not working. just create new one. ('__key__', db.Key), # same... So, how can I overwrite existing entity which has no 'key_name'? It would be horrible if I should give unique name to all entities..... From the first answer, I could handle this problem. :) def create_entity(self, values, key_name=None, parent=None): # if key_name is None: # print 'key_name is None' # else: # print 'key_name=<',key_name,'> : length=',len(key_name) Validate(values, (list, tuple)) assert len(values) == len(self._Loader__properties), ( 'Expected %d columns, found %d.' % (len(self._Loader__properties), len(values))) model_class = GetImplementationClass(self.kind) properties = { 'key_name': key_name, 'parent': parent, } for (name, converter), val in zip(self._Loader__properties, values): if converter is bool and val.lower() in ('0', 'false', 'no'): val = False properties[name] = converter(val) if key_name is None: entity = model_class(**properties) #print 'create new one' else: entity = model_class.get(key_name) for key, value in properties.items(): setattr(entity, key, value) #print 'overwrite old one' entities = self.handle_entity(entity) if entities: if not isinstance(entities, (list, tuple)): entities = [entities] for entity in entities: if not isinstance(entity, db.Model): raise TypeError('Expected a db.Model, received %s (a %s).' % (entity, entity.__class__)) return entities def generate_key(self,i,values): # first column is key if values[0] is None or values[0] in ('',' ','-','.'): return None return values[0]

    Read the article

  • Tuples vs. Anonymous Types vs. Expando object. (in regards to LINQ queries)

    - by punkouter
    I am a beginner who finally started understanding anonymous types. (see old post http://stackoverflow.com/questions/3010147/what-is-the-return-type-for-a-anonymous-linq-query-select-what-is-the-best-way-t) So in LINQ queries you form the type of return value you want within the linq query right? It seems the way to do this is anonymous type right? Can someone explain to me if and when I could use a Tuple/Expando object instead? They all seem very simliar?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >