Questions tagged [for-loop]

14500 questions
1

votes
3

answer
1.1k

Views

Navigating multidimensional arrays with nested for-loops in Kotlin

Quite often I am navigating a two-dimensional image matrix of pixels or a three-dimensional volumetric data set. Typically the underlying data structure is a one-dimensional array of some primitive type like Double or Int. The multi-dimensional nature is navigated through by nested for-loops as il...
J.E.Tkaczyk
1

votes
2

answer
49

Views

If user skips rows to input a numeric value, force user to type in data in the following available row

I have a sheet and the user input Starts in A7 and calculations are inserted with a macro to B7 all the way through I. I got all that worked out but what i need is: the user is going down typing in data in Column A, lets say they input data Starting from A7, through A11, then skip A12 and type int...
1

votes
1

answer
34

Views

Optimize an existing for-loop over three arrays

I have three lists/arrays: one is a list of boolean values, the other two are arrays with certain values. My goal is to loop through the boolean list and if the value is true take the j-th value of the first array and safe it in the solution array, and if the value is false take the j-th value of th...
zeniapy
1

votes
2

answer
51

Views

Assign values with for loops to pandas DataFrame columns

I am a Python beginner and have a problem with a for loop. I want to assign a list of numbers to different DataFrame columns. Manually, I can assign my values with the correct code, but copy and paste isn't a good style for programming. The correct manual code looks like this: df = pd.DataFrame(colu...
Tom
1

votes
2

answer
50

Views

Unable to loop through ggplot histogram

I'm trying to loop through every column of the iris data set and plot a histogram in ggplot. So I'm expecting 5 different histograms to appear. However, my for loop below returns nothing. How can I fix this? library(ggplot2) for (i in colnames(iris)){ ggplot(iris, aes(x = i))+ geom_histogram() }
spidermarn
1

votes
1

answer
44

Views

variable not available after for-loop inside Promise.then()

I'm using a for-loop containing an if statement inside of a Promise.then() (it's an api call). A variable initialized before the for-loop is available within the for-loop, but not after. I've console.logged the variable before the for-loop, just inside the for-loop, inside the if statement, after th...
skillit zimberg
1

votes
1

answer
58

Views

Go to specific element C

I want to use a for loop to iterate through vector and when a certain condition is met, I want to go back to a certain element of vector and restart the loop from there. For example, let's say that my vector is 1,2,3,4,5,6,7,8,9; and when the first element that is bigger than 5 is met, I want to res...
Xyz
1

votes
1

answer
46

Views

Write a program that adds together all the numbers between 0 and 100. Print the result

I want to write a program that adds all the numbers between 0 and 100 but my code does not add everything correctly. How do I add the next number to the number and then print the sum? This is the code I have: for(int i = 0; i
Ahum
1

votes
3

answer
41

Views

Check for duplicated objects in an array populated dynamically

I'm trying to build a data structure where all elements would be grouped based on an object key. Everything works fine except that I can't check if the new array has the data duplicated, as it's outside the for..of loop. I'm looking for a way to prevent pushing a further object if the new array alre...
Rico Letterman
1

votes
2

answer
54

Views

why do the assignment statement in cycle only executes once in python

I think it is different from C language habits in mine. I want to excute assignment statement every times, so how to do it? input a = [0,1,2,3,4,5] for i in range(6): b = a print(len(b)) c = b.pop(i) output 6 5 4 3 Exception has occurred: IndexError pop index out of range It seems like b = a only ex...
Zhengfang Xin
1

votes
3

answer
23

Views

Python - Returning only first value from a for loop statement

I know this is basic but I have not been able to break this. I have a for loop that I am trying to execute that returns back 10 rows. How do I limit the loop to only return back first row and not the entire output. for i in range(10): print(i) I cannot change the range value from 10. Current output...
scott martin
1

votes
2

answer
27

Views

R For loop with if statement to Apply format

Say I have a for loop that looks like this. person
mrsquid
0

votes
0

answer
14

Views

code explanation about the “Combination Sum of Coins ” solution

The question is: Given many coins of 3 different face values, print the combination sums of the coins up to 1000. Must be printed in order. eg: coins(10, 15, 55) print: 10 15 20 25 30 . . . 1000 And the solution is: public static void coins(int c1, int c2, int c3) { Set sums = new HashSet...
Daniel K
-1

votes
1

answer
11

Views

Increment Array Key in for loop [duplicate]

This question already has an answer here: What is the difference between ' and ' in PHP? [duplicate] 6 answers What is the difference between single-quoted and double-quoted strings in PHP? 10 answers What is the difference between double and single quotes in PHP? [duplicate] 3 answers Background...
Denoteone
0

votes
4

answer
31

Views

Turn an Array of Numbers Into a String and Back Into an Array of Numbers With JavaScript

Essentially I'm trying to turn an array of numbers into a string, and then back into an array of numbers (exactly like the original array that was passed in). I know that this will turn an array of numbers into a string: function arrayToStringAndBack (array) { return array.join(' '); } console.log(...
HappyHands31
1

votes
2

answer
27

Views

Replace the values of a dataframe with for loop

The question is: 1) If there is a data frame with 5 rows as follow: x = c(0,1,3,4,8) y = c(3,4,6,8,9) z = c(5,7,3,6,10) xyz = data.frame(rbind(x,y,z)) x 0 1 3 4 8 y 3 4 6 8 9 z 5 7 3 6 10 I want to replace the numbers with 0 if they are smaller than the mean of every row using for loop...
WU BO
2

votes
4

answer
56

Views

in a for loop, does the variable used in the condition get checked at every iteration, or only the first?

I want to run a loop on a std::vector array to delete desired elements. I'm using for (i = 0; i < array.size(); i++) is it safe to invoke array.erase() from within the loop? In my head I assume for checks array.size() at every iteration, but maybe it only does it once at initiation. If it did, for (...
aName
0

votes
0

answer
3

Views

How to use flatMap inside for-loop

I am iterating a for-loop which is inside a flatMap, in this loop, I am calling WebClient to get data from URL and processing that data using flatMap. Problem is that flatMap inside for-loop is not executing and I am able to get data from WebClient. I am not sure what I am doing wrong or what is the...
Varshal Davda
1

votes
2

answer
1.4k

Views

Why doesn't my bouncy ball program stop after the 5th bounce?

I nested a for loop inside a while to keep track of the time. And the while loop keeps track of the bounces if a certain condition is met. As long as that condition is met the for loop will keep counting. But once the condition is met the loop is suppose to stop. However, it continues regardless of...
Alcamech
-1

votes
1

answer
14

Views

How can I delete the feature within a feature class with the largest area using cursor and arcpy?

I am trying to delete the feature within a polygon shapefile that has the largest area. I have a column in the attribute table with the areas, and can generate a variable with the max area. But I am not able to pass this variable into a loop to delete the feature using cursor. When I insert the act...
chickadee1310
-3

votes
2

answer
52

Views

Python 3 - Not understanding single line double loop

I am looking at the following function: # Initialize a network def initialize_network(n_inputs, n_hidden, n_outputs): network = list() hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)] network.append(hidden_layer) output_layer = [{'weights':[random() for i...
Jerry M.
1

votes
3

answer
13.5k

Views

Android Studio for loop

I Have the following code and want to find out if there is any way i can put the following code into a for loop so that it is not so long as i am doing it a few times in my code if (Q1o1.equals('null')){ button1.setVisibility(View.INVISIBLE); }else{ button1.setVisibility(View.VISIBLE); button1.set...
Jacques Celliers
0

votes
1

answer
17

Views

JQuery/Javascript: New RegExp() stops loop

I'm making a translation function, and I want to easily add translations inside an object and then change each globally inside the $('body').html(), problem is, when I use new RegExp() inside my for loop it cuts the loop after first iteration. if(window.location.href.indexOf('sv') > -1) { //CUSTOM T...
Carl Papworth
1

votes
1

answer
60

Views

How to make python loop remember each value? [duplicate]

This question already has an answer here: Creating functions in a loop 2 answers Whenever I dynamically create buttons in tkinter through a loop, to call a function with a value assigned to them through the loop, like so: from tkinter import * root=Tk() def add(text): print(text) for i in ('a', 'b...
Artemis Fowl
1

votes
2

answer
66

Views

Converting 1D array to 2D array regarding FOR loops Processing

I am working on a tic-tac-toe game in my computer science class using processing. In my program, I am coding a 3 in a row checker and I am trying to code this using a 2D array code since my array was initialized as a 2D array when coding the X / O. As well as, my teacher gave us an example of doing...
Mayer
1

votes
4

answer
78

Views

Java programming: How do I make this for loop program that accepts user input subtract the input properly?

I am making a program that accepts user input to subtract all the numbers desired by the user I first made the program ask how many numbers the user wants to subtract, and initialized the value in int inputNum, which is then passed on to the for loop for (int Count=1; Count
Cookie_Dev
1

votes
2

answer
24

Views

Mapping item in a list to a list of lists

I'm thinking of an efficient way to map names in a list to grouped index items in a list of lists. Let's say I have this grouping: g = [[0,1],[2]] I also have this list: names = ['canine', 'dog', 'feline'] I want to return the mapped names to the grouping according to index: result = [['canine','dog...
djennacs
1

votes
2

answer
32

Views

How to create a for loop to open, mutate and save .csv files using R?

I have a several .csv files that have to be reformatted and saved again using an R script. The function that is needed to do the changes and the reformating of the files, is already established and works perfectly fine. But as there are always lots of documents to change, I would like to have a for...
Hotshot
1

votes
3

answer
64

Views

How to check if a value matches a txt file

Im currently trying to solve a solution where I have a value and a text file (.txt) where I want to check if the value in the code is somewhere inside the text file. What I have done currently is that I have a text file that looks like: 999486 1117978 990583 1128062 1120618 and a code that looks lik...
Hellosiroverthere
1

votes
2

answer
55

Views

How do I store the values entered into a for loop by a user?

I have the following code for (int i = 0; i < courses; i++) { cout > grade1; cout > weight1; } Now, lets say the loop runs 3 times and the values entered by the user for grade1 and weight1 are different each time. I want to store these different values so I can do some calculations with them. Ho...
idkmath28
1

votes
2

answer
49

Views

Iterating DataFrame Rows to Create New Column Using Numpy

I'm trying to reshape a dataframe to get it into a more usable structure for graphing and right now what I've been doing is reshaping the df using iterrows or itertuples, following What is the most efficient way to loop through dataframes with pandas? Below is a overly simplified dataset, but the r...
imstuck
1

votes
3

answer
52

Views

Python don't modify values while iterating over a list with zip(), but does it while with enumerate()

Why Python works differently when iterating using index numbers? For example with the zip function (that don't has indexes when used in the for loop) a value isn't stored in a variable. While with the enumerate() function (that allow me to have an 'index' in the foor loop) it happens normally. A s...
Gabz
1

votes
3

answer
59

Views

Codility CyclicRotation Javascript Solution: Empty array returns an error

I am trying to solve this problem in codility. My solution passed all the tests except for one with empty array and rotation of 1 as arguments. I'm someway lost of how to even approach for solving this issue. Could someone please nudge me in the right direction? Other than writing a specific if clau...
Nika Bo
1

votes
3

answer
32

Views

Scrape a table iterating over pages of a website: how to define the last page?

I have the following code that works OK: import requests from bs4 import BeautifulSoup import pandas as pd df_list = [] for i in range(1, 13): url = 'https://www.uzse.uz/trade_results?date=25.01.2019&mkt_id=ALL&page=%d' %i df_list.append(pd.read_html(url)[0]) df = pd.concat(df_list) df But for this...
AK88
1

votes
3

answer
74

Views

Output 1, 0.5, or 0 depending if a matrix elements are prime, 1, or neither

I am sending a matrix to my function modifikuj, where I want to replace the elements of the matrix with: 1 if element is a prime number 0 if element is a composite number 0.5 if element is 1 I dont understand why it is not working. I just started with MATLAB, and I created this function: function B...
yusano
1

votes
1

answer
58

Views

javascript reduce function sum of all array values

for (var j = 0; j < l; j++) { aa = (j*5)/12/100; const arr = [ { x: aa } ]; const result = arr.reduce( ( sum, { x } ) => sum + x , 0); console.log( result ); } I have tried to sum of all output numbers using javascript reduce. But, counldn't able to achieve the desired output. This aa variable retur...
Karuppiah RK
1

votes
3

answer
60

Views

Confusing Output of C Program

Why compiler shows the value of x as 0 if I define int x; inside of for loop. But when removing int x from for loop gives the value of x as 10. #include int main() { int x = 0, i; for(i = 1; i
Âftãb Bãlôçh
1

votes
2

answer
55

Views

C language isMagicsquare function: What logic error is in my function code?

Although the output with the my current examples is correct, my code seems to have a logic error that doesn't give the right output for other cases. I have previously addressed this issue: 'What would happen in your code if there are no repeated numbers, all numbers are used, your last column sum i...
Vinxent
1

votes
1

answer
54

Views

Maximum times without seeing an observation in R

I have a vector basically with 100,000 entries consisting on a number from 1 to 6 (I mean, entry one = 4, entry two = 2 and so on). Basically, a 100,000 times sample of a vector containing 1, 2, 3, 4, 5 and 6. I want to compute the maximum amount of consecutive entries without a value (for example,...
1

votes
3

answer
71

Views

How to find or count the duplicate in multidimensional array in c# [closed]

I am creating a 2d (3 * 3) array in c# which has to count or find the duplicate value int[,] arr = new int[3, 3] { {1, 2, 6}, {4, 1, 5}, {6, 1, 8} }; I expected the output has 1 and 6 are the duplicate values For beginners only with for loop
Arun Kumar

View additional questions