FAQ Database Discussion Community


Making Sub Lists Based on Lengths of Items

python,list,iteration
I want to split a list I have of 48 different lengths into a new list for each length of the item. I could do something like for item in list: if len(item) == 1: len1list.append(item) if len(item) == 2: len2list.append(item) etc etc but that would require 48 if statements,...

Endless JavaScript ELSE IF statement 650 Need shortening

javascript,if-statement,switch-statement,iteration,control-structure
I need to modify some script that runs in a program I use. The script ONLY plots horizontal lines at specific prices on a chart that has an X & Y axis. Whenever I switch to a new chart, the script will run through all the statements until it gets...

proper simple declatation to iterate prepared struct array c without knowing number of elements

c,arrays,loops,struct,iteration
I have been looking through questions on how to iterate an array of structs containing mixed types of data fields, only to come with complicated answers. I'm looking for something rather simple. My program retrieves IP addresses from linux IPtables along with status as to whether they are accepted or...

Python - iterating beginning with the middle of the list and then checking either side

python,iteration
Really not sure where this fits. Say, I have a list: >>>a = [1, 2, 3, 4, 5, 6, 7] How can I iterate it in such a way, that it will check 4 first, then 5, then 3, then 6, and then 2(and so on for bigger lists)? I...

Get an element of a list inside a command in SHELL script

list,shell,iteration
I would like to run a Java application with specified parameter settings, and some of the parameters will come from an iteration of a list. This could be the proper way? Many Thanks! outs="/home/user/this.vcf /home/user/that.vcf /home/user/simulation/control.vcf" arr=($outs) ending=3 for ((i=1;i<=ending;i++)); do java -Xmx32g -jar /home/user/something.jar \ -o $arr[i] \ done...

link_to delete, deleting wrong record

ruby-on-rails,rest,iteration,haml,link-to
I'm having the strangest problem! In my RoR app, I have an .each loop. Each iteration has a link_to "Delete" for that specific iteration: - @evints.each do |e| .inteventimg = link_to e.event.name, e.event = e.id %br - if e.event.images.exists? = image_tag(e.event.images.find_by(:prime => true).location.full.url) %br - if current_user = link_to "Delete...

Iterative jQuery formatting JSON incorrectly

javascript,jquery,json,iteration
I have a JSON file with many nested objects which is structured similar to this: [ { "name" : "Fruits", "subNav" : [ { "name" : "Apples", "subNav" : [ { "name" : "Type 1" }, { "name" : "Type 2" }, { "name" : "Type 3" "subNav" : [...

Iterating over a Python 2D list to find the value

python,list,loops,iteration
I am trying to iterate over a Python 2D list. As the algorithm iterates over the list, it will add the key to a new list until a new value is detected. An operation is then applied to the list and then the list is emptied so that it can...

How to perform Zip operation with null array

c#,arrays,linq,loops,iteration
I'm experimenting with Zip operations in C#, like described here. Considering this code snippet: int[] numbers = new[] { 1, 2, 3, 4 }; string[] words = new string[] { "one", "two", "three", "four" }; var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w...

Multiple recursion to iteration

java,algorithm,recursion,iteration
I'm learning Java and for an exercise I have to implement a recursive and an iterative method that return the following for a positive integer. L(0) = 1 L(1) = 1 L(n) = L(n - 1) + L(n - 2) + 1 if n > 1 The recursive method was...

Prolog-iterating through list

list,prolog,iteration,head
Let's say i have list Xs = [a,b,c]. Now i want to iterate through all elements and call another function for this elements. My question is: how to do this using head and tail? I would be grateful for help.

Python making list

python,arrays,list,for-loop,iteration
I'm a super n00b in python. I have been struggling with finding proper solution. Here is the list, L = [0, 0, 0, 3, 4, 5, 6, 0, 0, 0, 0, 11, 12, 13, 14, 0, 0, 0, 18, 19, 20], and each of the items refers to location in...

Python: Skip 'for' loop interation

python,loops,for-loop,iteration,skip
I couldn't find a question that matches this specific issue; I'm writing an automatic code-minifier in Python, but I can't seem to find out how to skip the current iteration of the 'for' loop. Can you help? Here's the script: import os import sys try: file_path = sys.argv[1] except IndexError:...

Python: Iterating over .txt file line by line multiple times [duplicate]

python,file,object,iteration
This question already has an answer here: Why can't I call read() twice on an open file? 7 answers I have a class which reads a .txt file and performs some various functions to it. I have provided an example of my code below. class Example(object): def __init__(self,fileName): self.file...

How does `each_with_object(Hash.new([]))` work? [duplicate]

ruby,arrays,iteration,hashes
This question already has an answer here: Strange ruby behavior when using Hash default value, e.g. Hash.new([]) 4 answers I wrote this code to make a hash where the keys are categories (fruit or veg) and the values an array of items in that category. food = ["fruit:orange", "fruit:apple",...

Find all the combination of substrings that add up to the given string

java,string,algorithm,recursion,iteration
I'm trying to create a data structure that holds all the possible substring combinations that add up to the original string. For example, if the string is "java" the valid results would be "j", "ava", "ja", "v", "a", an invalid result would be "ja", "a" or "a", "jav" I had...

Run Batch Command on Iterative Text Files

windows,batch-file,iteration
I have a set of text files (log0.txt, log1.txt, etc) which I want to convert to a different format. However, the last line of each file is incomplete, so I want to write a Batch command which will delete the last line of each file. The general command I got...

Iterate through a specific directory tree and store all the .ttf files into an array in PHP

php,loops,iterator,directory,iteration
Lets say I have a lot of files, some of those are in these paths: root/fonts/folder1/font1.ttf root/fonts/folder1/font2.ttf root/fonts/folder2/font1.ttf root/fonts/folder2/font2.ttf root/scripts/file.php Remember that there are also other types of files in those folders. How can my "/scripts/file.php" iterate through the "../fonts/" directory tree and store all the TrueType font (.ttf) files...

How to get the input field value through Javascript?

javascript,jquery,iteration,input-field
I have a dynamic table which has the input field in each row. I would like to get the value entered by the user through Javascript. I am able to get the HTML code for the input field 'quantity' but not the value. Here is the part of the javascript...

while loop is not breaking even if the condition is satisfied

c,loops,while-loop,iteration
I have created a program to print armstrong number, but the inner while loop is not breaking, it should break when the value is 0, but it is going into continuous loop. Can anyone tell me what's wrong in my program. Is this the correct behaviour of compiler. #include<stdio.h> int...

for-loop add columns using SQL in MS Access

sql,ms-access,table,for-loop,iteration
I am trying to add n columns to a table, like in this example of code where n = 10: Sub toto() Dim db As Database, i As Integer Set db = CurrentDb() For i = 1 To i = 10 db.Execute " ALTER TABLE time_series " _ & "ADD...

iteration (for-loop) ms Access with past value

vba,for-loop,access-vba,iteration,recordset
I tried to translate a code from VBA excel to access. My data is a column of prices and I want to compute the returns. This is the original VBA code in excel: DerCol = Cells(T.Row, Columns.Count).End(xlToLeft).Column Cells(T.Row, DerCol + 1) = "Returns" For i = T.Row + 2 To...

Encapsulation and generalization function def mult_tasks(str_numbers) in python

python,iteration,encapsulation,generalization
The Question: Without altering mult_tasks, write a definition for mult_tasks_line so that the doctests pass. So: print mult_tasks("3469") will produce: (3*3) (3*4) (3*6) (3*9) (4*3) (4*4) (4*6) (4*9) (6*3) (6*4) (6*6) (6*9) (9*3) (9*4) (9*6) (9*8) def mult_tasks_line(first_num, str_numbers): """ >>> mult_tasks_line("4", "3469") '(4*3) (4*4) (4*6) (4*9) ' """ #Add...

Turning multiple-recursion method into iteration

java,recursion,iteration,stack-overflow
I know that a similar answer has been asked many times, but my case isn't that simple. I have a recursive method which can call itself 4 times ("Worst case"). I'm trying hard to avoid recursion since it leads to a StackOverFlowException but I cannot find a way to replace...

Python: Check whether list is sequential or not

python,list,hex,iteration,sequence
Want a function / statement, to check whether all the values of mylist are sequential or not, which is hexadecimal list. For example: def checkmylist(mylist): #code returns True or False mylist1 = ['03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c','0d', '0e', '0f'] mylist2 = ['03', '05', '06', '07',...

Replacing recursion with iteration

algorithm,recursion,iteration
I have a recursive function which I need to convert to an iterative function but I am quite stuck. Can anyone help or point me in the right direction? f :: Int -> Int f(0) = 5 f(1) = 8 f(2) = 3 f(n) = (f(n-3)) * (f(n-1)) Cheers...

Action only occuring on last iteration of object

javascript,jquery,arrays,object,iteration
I have a function that performs an iteration through a dataset returned by an ajax request which in turn iterates through an array of dataKeys, so that it only returns them keys from the JSON. With each iteration of a dataKey I also iterate through a dataLink object which tests...

Recurrence relation: iteration solving

algorithm,iteration,time-complexity,recurrence,upperbound
There is a recurrence relation as following: T(n) = 2 T(n-1) + O(1) for n > 1 otherwise, its T(n) = O(1) By iteration , so far I got like, T(n) = 2(2T(n-2) + 1) + 1 --- 1 T(n) = 2(2(2T(n-3) + 1) + 1) + 1 ---- 2...

Trying to iterate through queue of object pointers in c++

c++,iterator,iteration,deque
I am trying to iterate through a deque of objects of class Node and call the function get_State from each one. The code is as follows: #include <deque> #include <queue> #include <stdlib.h> #include <stdio.h> #include <inttypes.h> #include <assert.h> #include <sys/time.h> #define MAX_LINE_LENGTH 999 class Node { private: state_t base_state, new_state;...

Iteration over dynamically added nested controls

c#,winforms,iteration,control
I have a GroupBox on an WinForm. Another GroupBox is added in run time within the first GroupBox. Few PictureBox controls are added within the second GroupBox. Now I would like to iterate the PictureBoxes. Currently my code is: foreach (Control gbFirst in this.Controls) { GroupBox firstGroupBox = gbFirst as...

How to interate through command line arguments saved in a variable?

bash,iteration,command-line-arguments
At some point in my script I need to save value of all command line arguments in a variable (after some shifting), it looks like this: foo="$@" Now I need to interate through the arguments from foo variable, but it seems to be quite hard to do it properly if...

Continuously add digits to a string

string,c#-4.0,collections,selenium-webdriver,iteration
Just a quick one, I want to continuously add digits to a string. The first thing I did is to remove the last character of the string, now digits starting from 1 should be continuously added to it. The snippet is below: using System; using System.Collections.Generic; namespace ConsoleApplication3 { class...

Dictionary value in Dictionary list created from tuple doesn't update correctly

python,python-3.x,dictionary,iteration,tuples
When I create a new dictionary value on a dictionary in a list (which was created from a tuple), the dictionary value updates all similar dictionary entries, rather than the single one i wanted: import itertools import random seq = [{'Item': 'A'}, {'Item': 'B'}, {'Item': 'C'}, {'Item': 'D'}] # Create...

Python: iteration problems

python,text,iteration
I am performing text processing on a text file and have been trying to iterate into a for loop. fields = [1, 2, 3, 4, 5] i = 0 with open('file path', 'r') as f: for line in f: # while i is smaller than the number of fields (=5)...

Iterate over an ArrayList appending values based on user input

java,list,arraylist,iteration
I am trying to write a method for changing the values of all Objects in an ArrayList one at a time, based on user input. Users input a value via dialog box, this is then converted to an integer and assigned to a value. The list is called studentList and...

Filling empty python dataframe using loops

python,pandas,iteration
Lets say I want to create and fill an empty dataframe with values from a loop. import pandas as pd import numpy as np years = [2013, 2014, 2015] dn=pd.DataFrame() for year in years: df1 = pd.DataFrame({'Incidents': [ 'C', 'B','A'], year: [1, 1, 1 ], }).set_index('Incidents') print (df1) dn=dn.append(df1, ignore_index...

Explanation of matrix iteration optimization

c,loops,optimization,matrix,iteration
I'm studying for my final exam and I'm going over some optimization techniques. For some reason, there's not a lot of information on this particular example and I don't understand it, so maybe I can get some help. In the Powerpoint slides, there is this example of strength reduction. c1...

Creating correct for-loop/iteration for a unique list

list,python-2.7,for-loop,iteration
I have a list of the numbers 1,2,3 and 4. I wish to print them out in the following manner: 1 2 3 4 11 12 13 14 21 22 23 24 31 ..and so on. How is it possible to do? Thanks...

maxi and min times to calculate the Fibonacci numbers for six seperate runs at n [closed]

c++,recursion,iteration,fibonacci,timing
The wording for this problem has me completely confused. I know how to get "timing" using GetTickCount() but I have to repeat the calculation 6 times for each N and I have to have 6 different N and the results have to be reported in one table as max an...

Comparing list of unique objects with custom function

python,iteration
I need to compare hundreds of objects stored in a unique list to find duplicates: object_list = {Object_01, Object_02, Object_03, Object_04, Object_05, ...} I've written a custom function, which returns True, if the objects are equal and False if not: object_01.compare(object_02) >>> True Compare method works well, but takes a...

Rotate color hue when iterating through a loop using stylus

css,loops,iteration,preprocessor,stylus
How can I spin the color hue for each item in a loop. If I have: items = { item1: 'item1', item2: 'item2', item3: 'item3' } For each item in this list I want to change it's hue by 30% Something like this: for name, item in items .{name} color:...

Android MongoDB Document iteration not consistent, confused

java,android,mongodb,iteration,mongolab
I'm trying to iterate through all my documents and parse the values and add them to their own lists. The thing is when I try to parse and add to the list it stops early half way through to be exact. But when I don't add all the extra code...

Trouble deleting iterations in array

c++,arrays,iteration
In this code, I'm trying to remove all occurrences of a specified value from an array. Function should take three arguments, the array, the array length and the value being searched for. Each time the value is found, the array should be shifted to remove that value. This is what...

Recursive function until done value is true and merge each response into a big one

php,arrays,json,iteration
I have this function: public function syncTerritoriesSOQLQuery($veevaToken, $instanceUrl, $tokenUrl) { $soqlQuery2 = "SELECT Id,Name,LastModifiedDate FROM Territory"; $soqlUrl2 = $instanceUrl.'/services/data/v28.0/query/?q='.urlencode($soqlQuery2); $curl = curl_init($soqlUrl2); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $veevaToken")); $jsonResponse = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);...

Python iterative loop

python,loops,syntax,iteration
I'm trying to iterate through a search list, I've written it like I would in C but I want to re-write this more pythonic. I've been trying with enumerate but I can't seem to get it to work, It is searching lines of data for key-words which are saved in...

Add key and value to dictionary

python,python-2.7,dictionary,iteration
I am trying to add a new key/value pair to an (empty) dictionary. I have a text file with a string in it (years) and the script should count the appearances of the year. with open ("results/results_%s.txt" % bla, "r") as myfile: for line in myfile: line = line.translate(None, ''.join(chars_to_remove))...

Multiple iterations of quadratic regression in R

r,datetime,iteration,non-linear-regression
I am analyzing meteorological data that is collected on a long term basis at regular intervals (every 15 to 60 minutes for most of the data). Temperature and other measures of the effect of solar radiation have daily cycles. I am trying to describe average exposure to solar radiation for...

Calling Drools Agenda after completion of iteration of Arraylist in DRL file

iteration,drools
I am iterating a list in the DRL file. I need to call the new Agenda after completion of the loop. But the following code calls the Agenda "B to C" for all iterations rule "Difference in offsets" dialect "java" lock-on-active when $notification : NotificationVO() wtOffset:Integer() from $notification.getWeightOffset(); then System.out.println("Hello...

R data.table group by and iterate by two columns

r,group-by,iteration
I am new to R and trying to solve the following problem: There is a table with two columns books and readers of these books, where books and readers are book and reader IDs, respectively : > books = c (1,2,3,1,1,2) > readers = c(30, 10, 20, 20, 10, 30)...

Regarding loop structure in Matlab for an iterative procedure

matlab,for-loop,iteration
I'm trying to code a loop in Matlab that iteratively solves for an optimal vector s of zeros and ones. This is my code N = 150; s = ones(N,1); for i = 1:N if s(i) == 0 i = i + 1; else i = i; end select =...

Implementation from MATLAB to Python without iterations

python,arrays,matlab,numpy,iteration
Suppose you have the following code in MATLAB: [xi yi imv] = find(imagee+0.1); imv = imv - 0.1; wv = abs(imv*ones(1,length(imv)) - ones(length(imv),1)*imv'); And you want to implement this code in Python. Imagee is a predefined, synthetic image represented by a 10x10 array with values 0,1,2. What would be the...

How to insert key and value to map that is inside another map in cpp?

c++,insert,mapping,iteration
I have this map : std::map<std::string, std::map<std::string, std::string> > objects; As far as I know, when I write objects[key] it will replace the value of the key already exists, but here I want it to add to the second map if the pair doesn't exist. Example: Current MAP :("key1",map(<"key_a","value_a">,<"key_c","value_d">)) input:...

Python xlrd iteration over excel spreadsheet leaves out cell values

python,iteration,xlrd,xlutils
Need some help here guys, this is my code: import xlutils import xlrd import os import sys datafile = r'C:\\someexcelfileediting.xlsx' workbook = xlrd.open_workbook(datafile) stone = workbook.sheet_by_name(input('What is the name of the sheet you are trying to reference? ').upper()) paper = workbook.sheet_by_name(input('what sheet would you like to check? ').upper()) def check_Base():...

How “break” in iterative Python loop works

python,loops,iteration,break
Newbie here, so bear with me...I've tried researching this on Python.org and Google, it's still not clear to me what's happening here. The basic questions are: What is break doing in the following iterative loops? Why do both if statements work, even though one uses the ">=" and the other...

How to get the next tree elements of a list

java,for-loop,iteration
This question is more about best practice than about fetching elements from a list. I have an ArrayList which I am itaration though by using a simple for-loop. In case a certain keyword shows up, I need to compare the next tree elements to a certain pattern. private static boolean...

Excel 2013 vba refresh chart content after each iteration of For Loop

excel,vba,loops,iteration,refresh
Problem: Refresh graphical representaion of Series in ChartObject after each iteration of for loop Ex. y=m*Cos(x) y - Values m - parameter I have some data counted from formula with parameter. I want to visualise what influence has the change of parameter on XYgraph. I want to do it in...

How to iterate over a a predictable progression of single characters in Python?

python,range,iteration
I have a series of websites I want to look at. The name of the each page is like this: book_page = ("http://target.com/books/char/X/") where X is a single letter of the alphabet. So the range will be mylist = ['A','B','C'] etc. First, is there an expression to create that list...

Python - How to generate permutations of size greater than the number of list elements

python,list,iteration,permutation
Sorry if that title made no sense. What I mean is this: I have a list [A, B, C] and I want all possible permutations of those elements that will fill a list of length 10. [A, B, C] => [A, A, A, A, A, A, A, A, A, A]...

Python - How to join elements in a list that are separated by a certain value

python,list,iteration
Suppose I have a list that looks like this: ['1', '+', '2', '+', '3', 'C', '4', 'C', '5', '-', '6', '+', '7', 'C', '8'] I want to modify it in such a way that all elements separated by a 'C' are concatenated together. The result should look like this: ['1',...

Iterate with last element repeated as first in next iteration

python,list,nested,iteration
I have some list with objects looks like: oldList=[a,b,c,d,e,f,g,h,i,j,...] what I need is to create a new list with nested list items which will look like this: newList=[[a,b,c,d],[d,e,f,g],[g,h,i,j]...] or simply spoken - last element from previous nested is first element in next new nested list. ...

Javascript object property 'null' when iterating through an array of objects

javascript,jquery,ajax,iteration
I have an array of objects. Somehow, one of the properties goes missing within my each loop. I have tried many different types of loops and nothing resolves this issue. someFunction(someArrayOfObjects) { console.log(someArrayOfObjects); // logs objects as I expect them to be $.each(someArrayOfObjects, function(index, someObject) { console.log(someObject); // one of...

Change radio button value on click of a div in jquery/javascript

javascript,jquery,html,html5,iteration
I am currently trying to create a multiple choice activity in which users select one of several answers with radio buttons next to them. I have been able to get the radio buttons to change by explicitly writing out the code like so: $("#choice0").on('click', function(){ $("input[name=radioAwnser][value=0]").attr("checked","checked"); console.log("clicked a"); }); $("#choice1").on('click',...

Efficiently Iterating over dictionary list values by skipping missing values Python 3

python,dictionary,iteration
I have a pandas dataframe import pandas as pd df=pd.DataFrame({'Location': [ 'NY', 'SF', 'NY', 'NY', 'SF', 'SF', 'TX', 'TX', 'TX', 'DC'], 'Class': ['H','L','H','L','L','H', 'H','L','L','M'], 'Address': ['12 Silver','10 Fak','12 Silver','1 North','10 Fak','2 Fake', '1 Red','1 Dog','2 Fake','1 White'], 'Score':['4','5','3','2','1','5','4','3','2','1',]}) And I want to add 2 tags which I stored in dictionaries....

editing the iteration value in a foreach loop

c#,loops,iteration
Situation I'm trying to design a simple remove method that deletes an object if the incoming ID parameter matches an ID on record: For instance, if a Race had an ID "123" then it would find the race that had the ID "123" and set it to null, thus removing...

How can I retrieve a list of specific person names from DBPedia by using SPARQL query in R

r,iteration,sparql,dbpedia
I am currently using the SPARQL package in R to query DBPedia and get the information for a list of specific person names. But I only know how to query one person or the "person category", such as query= "SELECT *{ dbpedia:Veit_Dietrich ?p ?o }" qd=SPARQL(endpoint,query) df=qd$results Is there anyway...

Writing value just once to file in for loop

python,iteration,file-writing
I have this iteration: with open("myFile.txt", "r") as landuse: next(landuse) for j in landuse: landuseList = j.split(";") clcKlasse = landuseList[2].strip() landusePlz = landuseList[3].strip("\"") landuseArea = landuseList[6].strip() landuseAreaFloat = float(landuseArea.replace("," , ".")) if landusePlz in dictPlz: areaPlz = dictPlz.get(landusePlz) relativeShare = (landuseAreaFloat * 100) / areaPlz nf.write(str(clcKlasse) + "\t" + str(relativeShare)...

iterate over a vector using multiple threads (no data sharing, or vector modification)

c++,multithreading,iteration
I have a large vector of objects and I just need to iterate over the vector using multiple threads and read the objects (no modification to data or the vector). What is the most efficient method to do this? Could it be done in a lock free fashion, maybe using...

Iterating through Twitch Json

json,vb.net,iteration,twitch
I'm not very good at this yet, not sure if my subject even accurately describes what I need. I know it's probably been answered, I'm having a hard time understanding the answers since they don't directly apply to my data. I am trying to figure out how I can iterate...

Short for 'for i in range(1,len(a)):' in python

python,for-loop,range,iteration,enumerate
In python, is there a short way of writing for i in range(len(l)):? I know I can use for i,_ in enumerate(l):, but I want to know if there's another way (without the _). Please don't say for v in l because I need the indices (for example to compare...

Object of type int is not iterable

python,int,iteration
Here is my code: NUM = 3 A = [1,5,6,2,8,4,3,2,5] B = [] m = [] check = False summ=0 n = len(A) / NUM while check == False: for i in A: if A.index(i) >= n: B.append(m) m = [] n *= 2 m.append(i) B.append(m) for j in B:...

Is there a way to condense this code?

r,iteration
Is there a way to condense code like this? In this case B is just a column vector and A is just a scalar value. I feel as if the line Q1 <- A*(1+B[1]) will have to stay like that and then rest of the code can probably be written...

Iterate over dates range (the scala way)

scala,datetime,iteration,nscala-time
Given a start and an end date I would like to iterate on it by day using a foreach, map or similar function. Something like (DateTime.now to DateTime.now + 5.day by 1.day).foreach(println) I am using https://github.com/nscala-time/nscala-time, but I get returned a joda Interval object if I use the syntax above,...

how to catch the server error JS

javascript,jquery,json,callback,iteration
I'm learning JavaScript, through trial and error and there are times when the server does not respond, and internally generates an Internal Server Error (500), and as the errors accumulate, you begin to lag the page. Maybe I assemble the code in the wrong way? or am I doing a...

How to iterate through a list in a dictionary in python

python,list,dictionary,iteration
sampleDict={ “A1”:[“234-234-2234”, [“Brown”, “Bill”] ], “B2”:[“654-564-5564”,[“Jones”,”Jennifer”]] } I have to check to see it "john" is in the dictionary and print the first and last name of everyone whose phone number begins with "654" and my code is: for i in sampleDict.keys(): for key in sampleDict[i]: print(key) and how do...

Split an array into new arrays (each with a unique name) [duplicate]

ruby,arrays,iteration,slice
This question already has an answer here: How to dynamically create a local variable? 1 answer I'm trying to slice an array into equal sizes (rounded down) and save each section to respective variables. The method each_slice has worked to grab n-sized blocks. However I can't think of a...

Print out keys and values of a map

java,maps,iteration
Ive created a map with keys of type integer and values are Sets of Strings. I have populated the map with some test data, and now need to write a method that prints out the contents of the map like "key: value, value, value" Im assuming iterating through the map,...

how to loop or iterate html code for the same components

javascript,html,css,loops,iteration
The html code below is written to display a container with 4 text-area,3 images and 3 labels : HTML <div class="row"> <div class="col-md-2"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <div class="alert alert-info alert-dismissable"> <textarea class="form-control3" rows="3" placeholder="Clue 1"></textarea> <textarea class="form-control4" rows="3" placeholder="Answer"></textarea> <input type="text" class="form-control1"...

How to iterate through two lists in parallel with one list randomized

list,python-2.7,iteration,tuples
This thread explained how to iterate through two parallel lists. When I apply that lesson to a shuffled list, however, I get the following error: "zip argument #2 does not support iteration." Why does a shuffled list not support iteration? How else can I randomize the order of answer choices?...

Modify a string in a text file

python,for-loop,text,file-io,iteration
In a file I have a names of planets: sun moon jupiter saturn uranus neptune venus I would like to say "replace saturn with sun". I have tried to write it as a list. I've tried different modes (write, append etc.) I think I am struggling to understand the concept...

Get next item in array using iterator using flags

javascript,jquery,loops,iterator,iteration
I am trying to obtain the next object in an object of objects (is you get my drift). I'm looking through the a list of songs, and trying to determine the next song to play. I use the flag playing to check if the song is being played, then i...

is there an equivalent of the ruby any method in javascript?

javascript,arrays,ruby,iteration
Is there an equivalent of ruby's any method for arrays but in javascript? I'm looking for something like this: arr = ['foo','bar','fizz', 'buzz'] arr.any? { |w| w.include? 'z' } #=> true I can get a similar effect with javascript's forEach method but it requires iterating through the entire array rather...

Problems computing the score of a pairwise list in an iterative way?

python,list,python-2.7,iteration,itertools
Let's suppose that I have the following lists (actually they have a lot of sublists): list_1 = [['Hi my name is anon'], ['Hi I like #hokey']] list_2 = [['Hi my name is anon_2'], ['Hi I like #Basketball']] I would like to compute the distance of all the possible pairwises with...

Iterating multiple txt files in folder to read them in C#

c#,file,stream,iteration,streamreader
Problem: I need to iterate through multiple files in a folder and read them. They are .txt files. While reading I need to note what words occured in each file. For example: File 1 text: "John is my friend friend" -> words: John, is, my, friend File 2 text: "John...

How to iterate over multiline text in text box in php?

php,html,loops,iteration
What I am trying to do is I want to write a little helper application for myself, which will convert list of coordinates into list of coordinates in bb code, like so: This is what user will input: 123|456 And the output will be: 1. [coord]123|456[/coord] So basically I need...

How do I nested Iterator?

java,iterator,iteration
while (inFile.hasNextLine()) { SortedArrayList<Fruit> fruitList = new SortedArrayList<Fruit>(); String marketName = inFile.next(); while (inFile.hasNexLine()) { String line = inFile.nextLine(); if(line.isEmpty()) break; else { Sting fruitName = inFile.next(); int price = inFile.nextInt(); int stock = inFile.nextInt(); fruit = new Fruit(fruitName, price, stock); fruitList.insert(fruit); } } market = new Market(marketName, fruitList); marketList.insert(market);...

How to use multiple threads in Java to iterate over a Collection where no two threads ever iterate over the same part of the Collection?

java,multithreading,collections,iteration
I need to iterate over a large ArrayList (~50,000 entries) and I need to use multiple threads to do this fairly quickly. But I need each thread to start at a unique index so that no two threads ever iterate over the same part of the list. There will be...

How do I select a given number of rows for one table for each parent primary key in another table in sql server 2012?

sql,sql-server,sql-server-2012,iteration
I have two tables in sql. One is a table of test cases and the other is a table of test runs with a foreign key that links back to a test case. I want to get the most recent 10 test runs for each test case. I don't want...

Counting Iterations in recursion

python,function,recursion,iteration
I'm trying to keep track of iterations through this recursion, but 'iter' always returns 1. def compute_root(poly, x_0, epsilon): ##Using Newton's method iter = 0 try: if abs(evalpoly(poly,x_0)) < epsilon: return '%s is the root. Took %s iterations.'%(x_0,iter) else: iter += 1 x_1 = x_0 - (evalpoly(poly,x_0)/evalderiv(poly,x_0)) return compute_root(poly, x_1,...

NSIndexSet.enumerateIndexesUsingBlock using Swift Closure

osx,swift,cocoa,iteration,nsindexset
I'm writing a method to copy data from a table view to the paste board but if any rows are selected it should specifically only copy the data from the selected rows so I need to iterate over the index set ... func createExportText(fromArrayController:NSArrayController) -> String { var indexSet =...

Python: How to combine the results of for loop into one output?

python,for-loop,iteration,output
numbers = [1, 2, 3] for number in numbers: number = number * 2 #For the output I will get: 2 4 6 How do I modify my code so the results can be combined (eg. [2, 4, 6]) without using the print statement? ...

What is the Pythonic way to iterate over set intersection and exclusions?

python,dictionary,set,iteration,set-intersection
set_of_A_key and set_of_B_keyare two set of keys of dictionary dict_A and dict_B. I want operate over the dictionary values for the keys in the following three sets: (set_of_A_key & set_of_B_key), (set_of_A_key - set_of_B_key) and (set_of_B_key - set_of_A_key) What is the pythonic way to do this? This one is elegant with...

python iterate over and select values from list of zipped arrays

python,arrays,numpy,multidimensional-array,iteration
I have several multidimensional arrays that have been zipped into a single list and am trying to remove values from the list according to a selection criteria applied to a single array. Specifically I have the 4 arrays, all of which have the same shape, that have all been zipped...

C: Make generic iteration function?

c,arrays,struct,iteration
I have an struct which defines an array of structs, each of which contain a couple more arrays. These inner arrays define my 'datasets'. In numerous places, I wish to iterate over all the datasets. To avoid 3 nested loops, I loop over the total number of datasets and have...

Python and XML (LandXML) [closed]

python,xml,tree,iteration
Ok, I have some XML file looks like this, actually it is LandXML file, but works like any other XML. I need to parse it with python (currently I'm using ElementTree lib) in that way to cycle through sub-element <CoordGeom></CoordGeom> and make lists dependent on child - it can be...

Solve Gurobi model repeatedly in Python

python,optimization,iteration,gurobi
I need to solve a gurobi model repeatedly (with different variable values each iteration). Rather than rebuild the model each iteration, I have tried setting up the model, then looping through repeated optimizations, but the variable values do not update. Here is a simple example. n = Model("Test") a =...

Python - Nested Lists

python,list,nested,iteration
I'm trying to cross check two nested list values, and if I get a match, append the values from list1 into list2. For example; list1 = [[ip, hostname], [ip, hostname], [ip, hostname]] list2 = [[ip, ip_upper, type, hostname, location], [ip, ip_upper, type, hostname, location], [ip, ip_upper, type, hostname, location]] I...

Why doesn't this OpenCV masking function iterate?

python,opencv,if-statement,image-processing,iteration
I wrote an algorithm in Python OpenCV to find certain targets, but sometimes these targets are hard to find so I made this if-else statement to just output 'target not found' when it fails to find the target. I'm iterating over 1000 images and calling the algo on them, but...

I'm getting a recursive error [RuntimeError: maximum recursion depth exceeded while calling a Python object] - but my code is iterative — or is it?

python,loops,selenium,recursion,iteration
I'm getting a recursive error: RuntimeError: maximum recursion depth exceeded while calling a Python object But my code is iterative...or is it? I thought it was, based on documentation (here, for example: http://www.pythonlearn.com/html-008/cfbook006.html). I've been reading on how to change an algorithm/code from recursive to iterative (e.g., http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html) but I...

How to stop a decreasing iteration after xth element?

php,for-loop,iteration
So I have a for loop that is decreasing... for ($i=count($array); i>0; $i--;) { if(condition) {DO SOMETHING like print the element in a decreasing manner} if(enter ending iteration condition here after xth element) break; } that pretty much sums up my question. How do I formulate the ending iteration -...

what would be a better approach loop or recursion for a simple processing? [closed]

c#,loops,recursion,iteration
i am trying to reduce a number to a desired range of values, say x until it is less than 100. What I am doing is dividing the number with 10 until it is less than 100. what would be a better approach a recursive one or iterative one.