Questions tagged [for-loop]
A for loop is a control structure used by many programming languages to iterate over a range. It is a way of repeating statements a number of times until the loop ends. Depending on the language this may be over a range of integers, iterators, etc.
70,073
questions
0
votes
0
answers
30
views
Bash for loop iteration with two variables from command substitution
I'm trying to execute a for loop in bash script where I have the requirement to pass two variables. I'm currently using the below for loop without success.
IFS=',' ;for componentId in `echo "${...
0
votes
0
answers
20
views
R for loop returns only last value
I am writing a simple for loop for R as follows, however only the last value is stored at err_cv.
code:
err_cv <- numeric(3)
k <- as.numeric(list(2, 5, 10))
for (i in length(k)){...
-1
votes
0
answers
25
views
How to use "for loop" in Python to extract year and firm name (for earning call transcripts) from a txt file
I have a txt file of this type:
Thomson Reuters StreetEvents Event Transcript
E D I T E D V E R S I O N
Q3 2003 ABM Industries Earnings Conference Call
SEPTEMBER 10, 2003 / 1:00PM GMT
=============...
0
votes
0
answers
11
views
Blending images in Python for loop and range
so I am having trouble figuring out how to blend two images with for loops and range(len). For this particular case, I need to compute the color of each pixel by setting value of each color component ...
1
vote
1
answer
20
views
How to use case_when and for loop to reorganize my tibbles in a list?
I have a list of 15 tibbles. The tibbles are in either one of 3 formats with different numbers of columns. What I am trying to do is to create a loop over all of the tibbles that will change each ...
0
votes
3
answers
38
views
Wrong value for variable is being given
so I have a problem with some variables, which are coming from an dictionary iteration:
for rank in ranked_stats:
if rank['queueType'] == "RANKED_FLEX_SR":
flex_rank_name = "...
3
votes
0
answers
39
views
How to stop current thread while another tread is updating GUI in JavaFx [closed]
So I been stuck on this problem for a while now and have not been able to come up with a solution that works without bugs. Basically I have this code:
public void startExp()
{
root.setCenter(...
0
votes
1
answer
21
views
How to make loop with features selection by features importance where deleted features with imp = 0 or below mean imp in each iteration in Python?
I have DataFrame in Python Pandas like below:
Input data:
Y - binnary target
X1...X5 - predictors
Source code of DataFrame:
import pandas as pd
import numpy as np
from xgboost import XGBClassifier
...
1
vote
1
answer
17
views
How to modify loop builing ML models and generated DataFrame with column presented variable removed in each iteration of for-loop in Python?
I have Pandas DataFrame like below:
Input data:
Y - binnary target
X1...X5 - predictors
Source code of DataFrame:
import pandas as pd
import numpy as np
from sklearn.model_selection import ...
-1
votes
1
answer
28
views
core is being dumped [duplicate]
what is the problem in this code?
string s; cin>>s;
s[0]=s[0]-32;
replace(s.begin(),s.end(),'s','$');
replace(s.begin(),s.end(),'i','!');
replace(s.begin(),s.end(),'o','(');
...
-1
votes
2
answers
41
views
Histogram for list of elements python
Does anybody know how I can make this
Input
Explanation: <2> is the first input and shows the number of next inputs lines -> if the first input is n all the input lines are n+1
2
purple 11,...
0
votes
1
answer
53
views
Python code issue with looping more dates in list
I have some problems if I use so many 'Materials' or Codes, with 50 random codes from my list, everything is fine, but if I use all lists with 461 codes I receive results like NaN.
Somewhere I make ...
0
votes
0
answers
17
views
Using nested loop, for and if
I have a DF with 16 columns, I need to work on 2 of them to generate a table, the first column is Type (has 2 type, Subscriber and one-time user, and the second is day (days of a week), following is ...
-4
votes
0
answers
61
views
Timeout C++! Beginner [closed]
#include <iostream>
using namespace std;
class aray {
public:
aray() {};
void set() //<<sets a function array
{
int input;
cin >> input;
if (...
0
votes
4
answers
36
views
Finding the square root of numbers in a range in JavaScript without using Math.sqrt() and Only For Loop
function getNumbersWithSquareRoots(max) {
const arrNum = [];
for(let i = 0; i < max; i++) {
arrNum.push(i);
}
return arrNum;
}
Can Only use JavaScript and for loops or for of or for in ...
-5
votes
3
answers
54
views
Printing numbers 1-10 in two separate lines using while and for loops [closed]
I need to figure out how to get this result:
I got this but how to put result from 2nd loop in new line?
public class Main04 {
public static void main(String[] args) {
int w = 1;
...
0
votes
1
answer
56
views
Is a loop in a loop really the best way to output nested dict items in Python?
I have a dict from a json API call that looks like this:
{
'id': '63d08d5c57abd98fdeea7985',
'pageName': 'Some Page Name',
'bodyContent':
[{
'children': [{
'alpha': 'foo foo foo'...
0
votes
1
answer
30
views
two for loop in python fileinput
cur = mysqlcon.cursor()
sql_select_query = """select name,AES_DECRYPT(passwd, 'hardpass') as passwd from fullusers WHERE id = %s"""
# set variable in query
cur.execute(...
1
vote
1
answer
25
views
Inconsistent output given by same code on different C compilers
Different compilers are giving different outputs for the same logic in my algorithm.
I wrote the following code for a C code exercise.
The code checks for the longest string in a string vector.
But ...
0
votes
2
answers
41
views
How can I use substr on json object with for loop?
Could someone help on how to loop over response while using substr to get each variable. The variables would be Amount, Type, Balance, Date.
I have the json response
[
[
"...
0
votes
1
answer
19
views
for-loop with multiple conditions
I have a database with about 5000 rows and I would like to change the data in one column in a special way, if several conditions are true. If the condition is not true, the value will remain the same.
...
-2
votes
2
answers
41
views
Issue printing the 2D array index in Java, print statement returns 0 everytime instead of index for both row & column and also does not increase
For example:
OUTPUT that I want:
Enter Row 0 & Column 0 value
OR
Enter Row & Column value 00
CODE
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
...
0
votes
1
answer
39
views
Using For Loops in Recursive Function to get every possible Combination
I want to create a funciton getCombinations that given a list of positive integers and a maximum amount, appends all the possible combinations of the given integers that sum to the given amount to a ...
-2
votes
0
answers
20
views
VBA how to devide from a single range to regular ranges with intervals between each range
I appreciate you in advance.
I wrote this code below.
And I want change the single range from Set rng = Application.Intersect(Target, Me.Range("M31:AM53"))
to 42 regular ranges with ...
0
votes
1
answer
33
views
Nested for loop to create list of urls
I am looking for a way to create a list of urls by modifying the name of the country and the date/time.
For each country, each day and each hour of the day I need to create a unique url.
import ...
0
votes
2
answers
47
views
Using switch inside for loop not working as expected
var userChosenBadges - ['Next.js', 'React']
function generateFrameworkBadges(userChosenBadges) {
var badgeUrlArray = [];
for (let i = 0; i < userChosenBadges.length; i++) {
...
0
votes
1
answer
11
views
Pandas raising ValueError when generating Timestamps using for loops
When generating a few random Timestamps using Pandas Timestamp() method I'm running into this ValueError: day is out of range for month. It seems totally illogical and this error is thrown only when ...
-4
votes
0
answers
20
views
How do I get the mirror image of my output in java [closed]
required output
I want to print this with the printf statement in java. But I'm only able to print it's mirror image
here is the code and my output. What am I doing wrong.
My output
0
votes
1
answer
25
views
How to create a few Machine Learning models through all variables and after each iteration next XGBClassifier is created with 1 less var in Python?
I have DataFrame in Python Pandas like below:
Input data:
Y - binnary target
X1...X5 - predictors
Y
X1
X2
X3
X4
X5
1
111
22
1
0
150
0
12
33
1
0
222
1
150
44
0
0
230
0
270
55
0
1
500
...
...
......
-4
votes
1
answer
58
views
How do I Loop over an array of lists in javascript? [closed]
var list=document.getElementsByTagName("li");
list[0].onclick=function(){document.getElementById("glider").style.marginLeft=marge[0];counter=0;}
list[1].onclick=function(){document....
1
vote
2
answers
26
views
add corresponding columns for every column of the spark df that assigns 1 for every notNull in the original column using case when
I have a sample dataframe:
df = spark.createDataFrame([('name1','id1',1,None,3),('name2','id2',None,2,5)],['NAME','personID','col1','col2','col3'])
My use case has 15 columns
What I would like to do ...
1
vote
1
answer
44
views
Looking to optimize a mutate(case_when( )) function in R, with the same mutations required across a list of systematically named variables
I am trying to find a vectorized, general way to accomplish a task in R for which I typically use Stata. I have a list of variables which have a common structure, and I am hoping to apply the same ...
-2
votes
1
answer
30
views
Python - New to Python and I am trying to take a section of a list that is a string and make it a integer
I'm trying to take this in stages, but I am stuck. Below is the task I am trying to complete, but I have run into a roadblock that I cannot seem to get over:
So far I have created the below for loops.
...
0
votes
1
answer
32
views
Python loop in a list returning wrong answer
I have a code that uses a request to an api :
lists = [254,255,256]
length = len(lists)
for li in range(length):
for count in range(4):
#o start dentro de url é o counter. Ou seja, ele vai ...
0
votes
0
answers
22
views
Loop and Add to a Data frame while Web Scraping with R
I was able to extract the data from 1st page of IMDB action movies with the following code:
movies <-
"https://www.imdb.com/search/title/?title_type=feature&num_votes=25000,&genres=...
1
vote
1
answer
28
views
storing output of a for loop that contains multiple columns in a list
I have the following dataframe:
data = {'id':[1,1,2,2,2,3,3,3],
'var':[10,12,8,11,13,14,15,16],
'ave':[2,2,1,4,3,5,6,8],
'age': [10,10,13,13,20,20,...
0
votes
1
answer
39
views
dynamically adding two matrices ; error in line 27 and 41
#include<stdio.h>
#include<stdlib.h>
int** addMatrix(int**, int, int, int**);
int main(void)
{
int i, j, m, n, **p, **q, **sum; //i = row, j = column
printf("Enter the size ...
0
votes
4
answers
104
views
VBA Nested Loop with Array running very slowly - Looking for Solutions
I'm running a nested loop, which I've added an array to in an attempt to speed up, but it is still running fairly slowly. When I have 100 rows and 41 columns of data in the "Active" sheet ...
0
votes
1
answer
24
views
How to read data into an array from a dynamic table AND validate data when added more rows
I am just starting to program with javascript and I ran into this difficulty:
I created a dynamic table in html and javascript. I have already created the function to add rows and delete.
But I am ...
-1
votes
2
answers
33
views
Print what is the lowest number without lists, tuples and dictionaries
I can use for loops, while and if statements. I'm struggling on how I can do that. I tried using this but is has a tuple. Canada_tax, Norway_tax, USA_tax and Denmark_tax have a value and the ...
-2
votes
1
answer
39
views
Generate XML file from pandas with python
I have a pandas dataframe that looks like this :
Date Min Max C
01.01.2003 01.01.2003 Nan NaT
02.01.2003 Nan Nan NaT
03.01.2003 ...
-1
votes
0
answers
34
views
Is there anything that I can use instead of lists or tuples? [duplicate]
This is a code that prints out the lowest tax for a project. The min_tax is a list, but can I use something else than list and tuples? Something simple not a function. There are more code above this ...
0
votes
1
answer
71
views
How to lookup for a key in a std::map and iterate backwards [closed]
I have a std::map which holds pointers to a class.
I need to lookup a key and iterate backwards until I get to the first item.
std::map::reverse_iterator does not support the std::map::find() method, ...
0
votes
0
answers
29
views
For Loop to move grobs in ggplot using editGrob only working for last element in R
Based on this question:
Customize label element position in ggplot using gtable/grob
The answer by https://stackoverflow.com/users/5193830/valentin-%c8%98tefan was fantastic and I learnt a lot from it....
1
vote
2
answers
25
views
How can i fix my loop, so that all matches are found?
My code does this. It search for the word: "KENNFELD" in my current sheet. Then it sets the variable label to the cell that is one to the right of "KENNFELD". Now i want to find ...
0
votes
2
answers
22
views
Adding suffix to variable for every iteration of for loop in python
I have searched for similarly worded questions but haven't found one that answers my question.
I have 2 dataframes showing the results on exam_1 and exam_2:
exam_1 = pd.DataFrame([['Jim', 87], ['Toby',...
2
votes
3
answers
58
views
Missing number in a list
I need a little help, a have a list of integers - the difference between the consecutive elements is constant, but the list is unsorted and one element is missing. The function takes a list as an ...
-1
votes
0
answers
23
views
Accurately check running processes and execute powershell commands accordingly [closed]
!I am very new. Help the poor noob. Have a good day :)
hello. I want to run different commands depending on the currently running process.
This is the function of powershell I am envisioning.
First, ...
0
votes
1
answer
29
views
can someone explain me the inner loop in layman terms [closed]
n = int(input("Enter the number:"))
counter = 0
for i in range (1, n):
for j in range (i+n*2):
print("Good Morning")
counter +=1
print(counter)
like for eg, if ...
-3
votes
1
answer
43
views
How does indentation affect the scope of the variable inside a for loop in Python?
I print an item twice with indentation, and it prints the values of the item
in iterated format. But when I print an item without indentation (I mean after the loop ends) it only prints the last value ...