Convert to the Python Language import java.io.*; import java.net.Socket; public
ID: 668036 • Letter: C
Question
Convert to the Python Language
import java.io.*;
import java.net.Socket;
public class Client {
public static final int PORT = 12321;
public static void main(String[] args) throws IOException {
String resp1 = sendAndReceive("S8 10 -945 1689 -950 230 -25 1 1e-13");
if(resp1.charAt(0) == 'S') {
double val1 = Double.parseDouble(resp1.substring(1));
System.out.println("Value returned from bisection: " + val1 );
String resp2 = sendAndReceive("E" + val1 + " -945 1689 -950 230 -25 1");
if(resp2.charAt(0) == 'E') {
double val2 = Double.parseDouble(resp2.substring(1));
System.out.println("Value returned from eval: " + val2 );
} else {
System.out.println("Error in evaluation call: " + resp2.substring(1));
}
} else {
System.out.println("Error in bisection call: " + resp1.substring(1));
}
}
/**
* Sends a request to the server, prints it and then prints the response.
*
*/
public static String sendAndReceive(String request) throws IOException {
System.out.println("request: " + request);
Socket conn = new Socket("localhost", PORT);
OutputStream os = conn.getOutputStream();
Writer wr = new OutputStreamWriter(os, "UTF-8");
wr.write(request);
wr.flush();
conn.shutdownOutput();
InputStream is = conn.getInputStream();
Reader rdr = new InputStreamReader(is,"UTF-8");
StringBuilder sb = new StringBuilder();
int c = rdr.read();
while(c >= 0) {
sb.append((char)c);
c = rdr.read();
}
// System.out.println("response: " + sb);
conn.shutdownInput();
conn.close();
return sb.toString();
}
}
Explanation / Answer
PORT = 12321;
def main( ) :
resp1 = sendAndReceive(‘S8 10 -945 1689 -950 230 -25 1 1e-13’)
if resp1[0] ==’S’:
val1 = float(resp1[0:1])
print ‘Value returned from bisection:’,val1
resp2 = sendAndReceive(‘E’ + val1 + ‘ -945 1689 -950 230 -25 1’)
if resp2(0)== 'E') {
val2 = float(resp2[0:1])
print ‘Value returned from eval:’ ,val2
elif
print ‘Error in evaluation call:’ , resp2[0:1]
else
print ‘Error in bisection call:’, resp1.substring(1)
else
}
/**
* Sends a request to the server, prints it and then prints the response.
*
*/
def sendAndReceive(String request):
print ‘request:’ ,request
print “shutting down”
sock.close()
return str(st)
//////-----------------------------------------------------------------------
PORT = 12321;
def main();
while 1:
conn = ss.accept()
print “shutting down”
sock.close()
print ‘request:’ ,str(st)
response = ‘response was not set properly’
if req.length() == 0:
response = ‘XInvalid request syntax: first character should be the operation code’;
elif req (0) == 'E' : {
params = req[0,1].split(" ")
if params.length < 1 :
response = ‘ XInvalid request syntax: wrong number of fields in request’;
else :
try
x = float(params[0]);
poly =[ float[params.length-1]];
for i in params[i] :
poly[i-1] = float(params[i]);
response = ‘E’+ evaluate(x, poly);
except
response = "Xinvalid format numeric data";
elif req(0) == 'S')