Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am coding in COBOL, and after adding the if statement listed below, I kept getting
"
In paragraph '000-main':
Error: syntax error, unexpected IF"
Identification Division.
Program-ID. Lab2.
*This program will generate a statement for a single investment
*that compounds interest monthly.
* It will prompt use for 3 inputs, calculate total interest
* earned, final balance, & entire account balance schedule.
* It will then display all output to the console.
Environment Division.
Data Division.
Working-Storage Section.
01 invest-amt pic S9(9)V99.
01 invest-error-msg pic x(40) value "Investment "
& "Amount must be positive".
01 int-rate pic S9(2)V99.
01 int-rate-error-msg pic x(40) value "Annual Interest "
& "Rate must be positive".
01 int-rate-final pic 9V99999.
01 num-months pic S9(3).
01 num-months-error-msg pic x(40) value "Number of Months "
& "must be positive".
01 multiply-rate pic 9V99999.
01 blank-line pic x value " ".
01 month-counter pic 99 value 1.
01 balance-month pic 9(9)V99.
01 interest-month pic 9(9)V99.
01 total-interest pic 9(9)V99.
01 final-balance pic 9(9)V99.
01 additional-value pic S9(9)V99.
01 add-value-error-msg pic x(40) value "Additional Value "
& "must be positive".
01 Q pic 9(3).
01 R pic 9(3).
01 months-in-year pic 9(2) Value 12.
Procedure Division.
000-main.
perform 100-initialize
perform until invest-amt >=0
display invest-error-msg
perform 200-input
end-perform
perform 210-input-rate
perform until int-rate >=0
display int-rate-error-msg
perform 210-input-rate
end-perform
perform 220-input-month
perform until num-months >=0
display num-months-error-msg
perform 220-input-month
end-perform
perform 230-input-additional-value
perform until additional-value >=0
display add-value-error-msg
perform 230-input-additional-value
end-perform
perform 300-print-words
perform 400-process-interest
perform 310-print-values
display blank-line
perform until month-counter = num-months
add 1 to month-counter
Divide month-counter By months-in-year Giving Q Remainder R
Everything was compiling fine up until I added the if statement below.
if ( (num-months> months-in-year) & (R=0))
Add additional-value to balance-month
multiply month-counter by months-in-year
add interest-month to balance-month rounded
perform 400-process-interest
perform 310-print-values
display blank-line
end-perform
My compiler complained of a missing end-if and didn't like &. I fixed the & problems in the obvious way.
Inserting end-if after Add additional-value to balance-month seemed to produce a clean compile. Naturally, the final end-perform needed a full stop
end-perform.
I suspect your compiler is producing that message because your if statement is malformed.
I did not compile your code.
You are missing the END-IF for your IF statement.
You should also put a "STOP RUN." in your program.
For example...
perform until month-counter = num-months
add 1 to month-counter
Divide month-counter By months-in-year Giving Q Remainder R
if ( (num-months> months-in-year) & (R=0))
Add additional-value to balance-month
end-if ******* <- YOU NEED THIS
multiply month-counter by months-in-year
add interest-month to balance-month rounded
perform 400-process-interest
perform 310-print-values
display blank-line
end-perform
STOP RUN. *** <- THIS WOULD BE NICE AS WELL.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 2 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Why does Unix give the result 0 when I execute the following command?
echo "7%2" | bc -l
And give result 1 when I execute the following command?
echo "7%2" | bc
why does Unix gives result 0 when I execute the command: echo "7%2" | bc -l
From the bc manual:
If bc is invoked with the -l option, a math library is preloaded and the default scale is set to 20.
And
expr % expr
The result of the expression is the "remainder" and it
is computed in the following way. To compute a%b,
first a/b is
computed to scale digits. That result is used to compute a-(a/b)*b
to the scale of the maximum of scale+scale(b) and scale(a). If
scale is set to zero and both expressions are integers this
expression is the integer remainder function.
So:
a=7 b=2
a/b = 7 / 2 = 3.50000000000000000000000000000000000000000000000000
7%2 = a-(a/b)*b =
= 7 - (7/2)*2 =
= 7 - (3.50000000000000000000000000000000000000000000000000) * 2 =
= 7 - 7 =
= 0
and gives result 1 when I execute the command: echo "7%2" | bc
From the bc manual:
scale defines how some operations use digits after the decimal point. The default value of scale is 0.
In that case:
a=7 b=2
a/b = 7 / 2 = 3 # scale is 0, rounds down
a%b = a-(a/b)*b =
= 7 - (7/2)*2 =
= 7 - 3 * 2 =
= 7 - 6 =
= 1
Because the 7/2 is computed with different scale, the resulting expression differs.
Today I come across unexpected behavior or lack of knowledge with ColdFusion 9,10,11 Round function here is my scenario
Round(28.5) ---> result is 29 expected
Round(0.285*100) ---> result is 28 not expected
Round(precisionEvaluate(0.285*100)) ---> result is 29 using precisionEvaluate!
Round(Evaluate(0.285*100)) ---> result is 29 using Evaluate!
This is not big decimal, why I would need to use precisionEvaluate or Evaluate on a number?
On farther research I found more interesting behavior
Round(0.285*100) result is 28 --WHY? I'm expecting 29-- !
Round(0.295*100) result is 30 ---- Correct !
Round(0.275*100) result is 28 ---- Correct !
Round(0.185*100) result is 19 ---- Correct !
Round(0.385*100) result is 39 ---- Correct !
What is is big deal with 0.285*100?
It's not the precision of the decimal numbers, it's how the underlying floats are stored in Java. This demonstrates:
<cfoutput>
<cfloop array="#[0.275,0.285,0.295]#" index="s">
#s.getClass().getName()#
<cfset f1 = s + 0>
#f1.getClass().getName()#
#f1.toString()#
<cfset f2 = f1*100>
#f2.toString()#
#round(f2)#<br>
</cfloop>
</cfoutput>
Output:
java.lang.String java.lang.Double 0.275 27.500000000000004 28
java.lang.String java.lang.Double 0.285 28.499999999999996 28
java.lang.String java.lang.Double 0.295 29.5 30
I can only assume under the hood CF uses better precision when converting from a string to a float when performing <cfset f1 = s + 0> as there's no dodgy rounding there. However having performed the multiplication step we're getting an accuracy error bleeding in. 28.5 ends up being just shy of 28.5, so rounds to 28 not 29. It's just a binary fraction arithmetic issue.
BTW, there's nothing special about 0.285. A lot of numbers are similarly effected (have a look at the range from 0.005 to 5.05). You just happened to pick a bunch that aren't (other than 0.285).
I am running an optimization problem using pyomo's ipopt solver. My problem is sort of complicated, and it is declared infeasible by IPOPT. I will not post the entire problem unless needed. But, one thing to note is, I am providing a warm start for the problem, which I thought would help prevent infeasibility from rearing its ugly head.
Here's the output from pyomo and ipopt when I set tee=True inside of the solver:
Ipopt 3.12.4:
******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
Ipopt is released as open source code under the Eclipse Public License (EPL).
For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************
This is Ipopt version 3.12.4, running with linear solver mumps.
NOTE: Other linear solvers might be more efficient (see Ipopt documentation).
Number of nonzeros in equality constraint Jacobian...: 104
Number of nonzeros in inequality constraint Jacobian.: 0
Number of nonzeros in Lagrangian Hessian.............: 57
Total number of variables............................: 31
variables with only lower bounds: 0
variables with lower and upper bounds: 0
variables with only upper bounds: 0
Total number of equality constraints.................: 29
Total number of inequality constraints...............: 0
inequality constraints with only lower bounds: 0
inequality constraints with lower and upper bounds: 0
inequality constraints with only upper bounds: 0
iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls
0 0.0000000e+00 1.00e+01 1.00e+02 -1.0 0.00e+00 - 0.00e+00 0.00e+00 0
WARNING: Problem in step computation; switching to emergency mode.
1r 0.0000000e+00 1.00e+01 9.99e+02 1.0 0.00e+00 20.0 0.00e+00 0.00e+00R 1
WARNING: Problem in step computation; switching to emergency mode.
Restoration phase is called at point that is almost feasible,
with constraint violation 0.000000e+00. Abort.
Restoration phase in the restoration phase failed.
Number of Iterations....: 1
(scaled) (unscaled)
Objective...............: 0.0000000000000000e+00 0.0000000000000000e+00
Dual infeasibility......: 9.9999999999999986e+01 6.0938999999999976e+02
Constraint violation....: 1.0000000000000000e+01 1.0000000000000000e+01
Complementarity.........: 0.0000000000000000e+00 0.0000000000000000e+00
Overall NLP error.......: 9.9999999999999986e+01 6.0938999999999976e+02
Number of objective function evaluations = 2
Number of objective gradient evaluations = 2
Number of equality constraint evaluations = 2
Number of inequality constraint evaluations = 0
Number of equality constraint Jacobian evaluations = 2
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations = 2
Total CPU secs in IPOPT (w/o function evaluations) = 0.008
Total CPU secs in NLP function evaluations = 0.000
EXIT: Restoration Failed!
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
model, tee=True)
4
/Library/<path to solvers.pyc> in solve(self, *args, **kwds)
616 result,
617 select=self._select_index,
--> 618 default_variable_value=self._default_variable_value)
619 result._smap_id = None
620 result.solution.clear()
/Library/Frameworks<path to>/PyomoModel.pyc in load_from(self, results, allow_consistent_values_for_fixed_vars, comparison_tolerance_for_fixed_vars, ignore_invalid_labels, id, delete_symbol_map, clear, default_variable_value, select, ignore_fixed_vars)
239 else:
240 raise ValueError("Cannot load a SolverResults object "
--> 241 "with bad status: %s" % str(results.solver.status))
242 if clear:
243 #
ValueError: Cannot load a SolverResults object with bad status: error
You can actually see from the log outputted above, that there were only 2 constraint evaluates from this line:
Number of equality constraint evaluations = 2
So, it actually was declared infeasible pretty quickly, so I imagine it won't be difficult to figure out which constraint was violated.
How do I find out which constraint was violated? Or which constraint is making it infeasible?
Here is a different question, but one that still is informative about IPOPT: IPOPT options for reducing constraint violation after fewer iterations
Running Ipopt with option print_level set to 8
gives me output like
DenseVector "modified d_L scaled" with 1 elements:
modified d_L scaled[ 1]= 2.4999999750000001e+01
DenseVector "modified d_U scaled" with 0 elements:
...
DenseVector "curr_c" with 1 elements:
curr_c[ 1]= 7.1997853012817359e-08
DenseVector "curr_d" with 1 elements:
curr_d[ 1]= 2.4999999473733212e+01
DenseVector "curr_d - curr_s" with 1 elements:
curr_d - curr_s[ 1]=-2.8774855209690031e-07
curr_c are the activity of equality constraints (seen as c(x)=0 internally for Ipopt), curr_d are the activites of inequality constraints (seen as d_L <= d(x) <= d_U internally).
So absolute values of curr_c are violations of equality constraints and max(d_L-curr_d,curr_d-d_U,0) are violations of inequality constraints.
The last iterate including constraint activites is also returned by Ipopt and may be passed back to Pyomo, so you can just compare these values with the left- and right-hand-side of your constraints.
I am working on a relatively new challenge in CodeEval called 'Football.' The description is listed in the following link:
https://www.codeeval.com/open_challenges/230/
Inputs are lines of a file read by Python, and within each line there are lists separated by '|', with each list representing a country: the first being country "1", second being country "2", and so on.
1 2 3 4 | 3 1 | 4 1
19 11 | 19 21 23 | 31 39 29
Outputs are also lines in response to each line read from the file.
1:1,2,3; 2:1; 3:1,2; 4:1,3;
11:1; 19:1,2; 21:2; 23:2; 29:3; 31:3; 39:3;
so country 1 supports team 1, 2, and 3 as shown in the first line of output: 1:1,2,3.
Below is my solution, and since I have no clue why the solution only works for the two sample cases lited in the description link, I'd like to ask anyone for comments and hints on how to correct my code. Thank you very much for your time and assistance ahead of time.
import sys
def football(string):
countries = map(str.split, string.split('|'))
teams = sorted(list(set([i[j] for i in countries for j in range(len(i))])))
results = []
for i in range(len(teams)):
results.append([teams[i]+':'])
for j in range(len(countries)):
if teams[i] in countries[j]:
results[i].append(str(j+1))
for i in range(len(results)):
results[i] = results[i][0]+','.join(results[i][1:])
return '; '.join(results) + '; '
if __name__ == '__main__':
lines = [line.rstrip() for line in open(sys.argv[1])]
for line in lines:
print football(line)
After deliberately failing an attempt to checkout the complete test input and my output, I found the problem. The line:
teams = sorted(list(set([i[j] for i in countries for j in range(len(i))])))
will make the output problematic in terms of sorting. For example here's a sample input:
10 20 | 43 23 | 27 | 25 | 11 1 12 43 | 33 18 3 43 41 | 31 3 45 4 36 | 25 29 | 1 19 39 | 39 12 16 28 30 37 | 32 | 11 10 7
and it produces the output:
1:5,9; 10:1,12; 11:5,12; 12:5,10; 16:10; 18:6; 19:9; 20:1; 23:2; 25:4,8; 27:3; 28:10; 29:8; 3:6,7; 30:10; 31:7; 32:11; 33:6; 36:7; 37:10; 39:9,10; 4:7; 41:6; 43:2,5,6; 45:7; 7:12;
But the challenge expects the output teams to be sorted by numbers in ascending order, which is not achieved by the above-mentioned code as the numbers are in string format, not integer format. Therefore the solution is simply adding a key to sort the teams list by ascending order for integer:
teams = sorted(list(set([i[j] for i in countries for j in range(len(i))])), key=lambda x:int(x))
With a small change in this line, the code passes through the tests. A sample output looks like:
1:5,9; 3:6,7; 4:7; 7:12; 10:1,12; 11:5,12; 12:5,10; 16:10; 18:6; 19:9; 20:1; 23:2; 25:4,8; 27:3; 28:10; 29:8; 30:10; 31:7; 32:11; 33:6; 36:7; 37:10; 39:9,10; 41:6; 43:2,5,6; 45:7;
Please let me know if you have a better and more efficient solution to the challenge. I'd love to read better codes or great suggestions on improving my programming skills.
Here's how I solved it:
import sys
with open(sys.argv[1]) as test_cases:
for test in test_cases:
if test:
team_supporters = {}
for nation, nation_teams in enumerate(test.strip().split("|"), start=1):
for team in map(int, nation_teams.split()):
team_supporters.setdefault(team, []).append(nation)
print(*("{}:{};".format(team, ",".join(map(str, sorted(nations))))
for team, nations in sorted(team_supporters.items())))
The problem is not very complicated. We're given a mapping from nation (implicitly numbered by their order in the input) to a list of teams. We need to reverse that to create an output that maps from a team to a list of nations.
It seems natural to use a dictionary that maps in the same way as the desired output. We can use enumerate to give numbers to the nations as we iterate over them. The setdefault method of the dict adds empty lists to the dictionary as they are needed (using a collections.defaultdict instead of a regular dictionary would be another way to deal with this). We don't need to care about the order of the input, nor the order things are stored in the dictionary's inner lists.
The output we build using str.format calls and the default space separator of the print function. If the final semicolon wasn't desired, I'd have used print("; ".join("{}:{}.format(...))) instead. Since the output needs to be sorted by team at the top level, and by nation in the inner lists, we make some sorted calls where necessary.
Sorting the inner lists is probably not even be necessary, since the nations were processed in order, with their numbers derived from the order they had in the input line. Fortunately, Python's Timsort algorithm is very fast on already-sorted input, so even with a bit of unnecessary sorting, our code is still fast enough.
I have a program asking user for answers to some riddles and I'd like to implement of stopwatch of sorts. Is it possible to count from 0 to 30, but to make seconds update "over each other", so that it doesn't display:
01
02
03
...
or
01 02 03 ...
but overwrites the same two digits every time. I hope I'm making myself clear.
Here is what I have so far:
start = time.time()
elapsed = 0
while elapsed < 30:
elapsed = time.time() - start
print "%02d" % elapsed
time.sleep(1)
But this prints the seconds in a column. I'd like to display it as I've described above so that prompt "Your answer: " is always in the same place.
If this program output in the command line it won't be possible to overwrite the digits. Command line output is not set up to be dynamic.
Right now you seem to be inputing and printing variables through the command line. Once you are comfortable with python, you might want to look into using a framework ( What is a Framework?) such as Django for your python projects. Instead of having the user interface of your program limited to the command line, you will be able to create an application which could have the timer updating in one location.
If your user interface does not happen to be the command line, you should move your print statement outside of the while loop and implement the print somewhere else.