How to Print Only the Last Value in a for Loop

How do I print only the last value in a for loop?

Just de-denting your print() will work:

def square(x):
guess = int(x/2)
for i in range(1,10):
nextguess = (guess + x/guess)/2
guess=nextguess
print(nextguess)

After the loop, nextguess still has the value form the last cycle.
In Python, a loop does not create a new scope. So, everything you create or change in the loop is still available after the loop.

Java print only the last loop value

Move the System.out.println call to outside the loop. Inside the loop do the calculation of the amount. Outside the loop print the final result, namely:

  public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
int amount = scanner.nextInt();
for (int x = 1; x < 6; x = x + 1) {
amount = (amount * 9) / 10;
}
System.out.println(amount);
}

For loop only printing out last element in Python

You need to join the entries in the list with , and then join the result with newlines.

def formatting(data):
result = []
for entry in data:
result.append(', '.join(entry))
return '\n'.join(result)

Using a generator you can write this in one line.

def formatting(data):
return '\n'.join(', '.join(entry) for entry in data)

Using an index to access every element of a list in a for loop is an anti-pattern in Python. That's why I replaced it and iterate over the elements themselves.

Python for loop storing only the last value

You are overwriting the existing csv on each iteration.

To fix it, simply indicate that you want to append instead of write by

all_dfs.to_csv('final_data.csv', encoding='utf-8', mode='a')

it can only print the first and last value when using for loop to read an array in Bash

Storing state can be complicated in bash. Just parse the stream as it goes.

start_time='now -2 hour'
stop_time='now -1 hour'

# convert to seconds since epoch
start_time=$(date --date="$start_time" +%s)
stop_time=$(date --date="$stop_time" +%s)

# get list of files
( cd /var/log/app/ && find . -type f -name 'h323server.log.*.gz' ;) |
# extract the number
sed 's/\.\([0-9]*\).gz$/& \1/' |
# compare and print the filename
awk -v start_time="$start_time" -v stop_time="$stop_time" \
'start_time < $2 && $2 < (stop_time + 20 * 60) { print $1 }'
# I guess maybe also `(start_time - 20 * 60)` to fetch the previous one

Notes:

  • Nice script!
  • Use for ((i = 0; i < ${#array[@]}; ++i)) to iterate over array indexes. Or just for i in ${!array[@]}.
  • I prefer arithmetic expansion, instead of if [[ ${filetime[${index}]} -ge ${timesys_s} ]] I would if (( ${filetime[${index}]} >= ${timesys_s} )).

Or for example get the file before and after the match:

find . -type f -name 'h323server.log.*.gz' |
# extract the number
sed 's/\.\([0-9]*\).gz$/& \1/' |
# sort on numbers
sort -n -k2 |
# important - the input is sorted
# compare and print the filename
awk -v start_time="$start_time" -v stop_time="$stop_time" '
# Because i dont want to write stop_time > $2 && $2 > start_time everrywhere, I cache it in cond variable
# clear cond variable
{ cond=0 }
stop_time > $2 && $2 > start_time {
cond_was_true=1; # remember that at least once the condition was met
cond=1; # if the condition is met, set cond variable
}
# so, if the condition is met
cond {
# output the previous line before the match if any
# if we did not output the previous line yet (oncelast)
# and the previous line length is not empty
if (!oncelast && length(last) != 0) {
# remember that we ouputted the previous line and output it
oncelast=1
print last;
}
# output the current line
print $1;
# there is nothing interesting below
next;
}
# remember the previous line
# the !cond could be just removed, it want be executed because next above
!cond { last=$1; }
# print one more line after the condition is true
# if the condition was true before
# but is no longer true
# then only once output the next line after the condition was met
cond_was_true && !cond && !once { once=1; print $1; }
'

If you seem to want to print the content of resulting files, add | xargs -d$'\n' zcat on the end of the scripts.

After the sort -n -k2 the input is sorted using the timestamps. So we have a condition stop_time > $2 && $2 > start_time and I am interested in the one line before and one after the range the condition is met for the input.

Above I used cond variable to just not write stop_time > $2 && $2 > start_time over and over again. I guess I'll try to rewrite a simpler version, but untested:

awk -v start_time="$start_time" -v stop_time="$stop_time" '

    stop_time > $2 && $2 > start_time {
# if the condition wasnt true, output the previous line
if (!cond_was_true &&
# and the previous_line is not empty
length(previous_line) != 0) {
print last;
}
# remember that the condition was true
cond_was_true = 1;
# output the current line
print $1;
}

# remember the previous line
{ previous_line = $1; }

# if the condition was true
# but is no longer met
# output the next line
# but output it only once
cond_was_true &&
!(stop_time > $2 && $2 > start_time) &&
!output_next_line_once {
output_next_line_once = 1;
print $1;
}
'

How to just display last value in a for loop? C#

Here's a version that only computes the exponent once per iteration:

int a = 8, b = 10;
int x = a * b;

int result = 0;
for (int i = 0, temp = 0; temp < x; temp = (int)Math.Pow(i,2))
{
i++;
result = temp;
}
Console.WriteLine(result);

The important things are moving the line to output the result to after the loop, and keeping a value for the previous result that will still be in scope.

Fiddle with it

Another option that's much more direct:

int a = 8, b = 10;
int x = a * b;

int y = (int)Math.Floor(Math.Sqrt(x));
Console.WriteLine(y * y);

No loop required. Not even Math.Pow(). But it will get the right result, and in O(1) time (depending on your interpretation of Math.Sqrt()).

Fiddle with it

Or as a one-liner:

Console.WriteLine((int)Math.Pow(Math.Floor(Math.Sqrt(x)), 2));


Related Topics



Leave a reply



Submit