Given the code segment:
def f1(a, b = 2):
if a :
print(1)
f1(1)
what is the result of executing the code segment?
a) Syntax error
b) Runtime error
c) No error
d) Logic error
in which scenario(s) is using a dictionary useful?
a) To store the dates of lesson that each student is absent for so that warning letters may be issued to student exceeding a limit.
b) To store the student numbers for students who sat for an exam
c) To retrieve email of students who are absent for an exam. The student numbers will be entered into the recipient field and the system should display the student email.
d) The marks should be entered into the exam system. The exam system displays rows of student number, and the marks can be entered against the student number. The grade will be computed and reflected in the student row .
which expression returns True when a number, x is not and odd number between 1 (inclusive) and 100 (inclusive), and returns False otherwise?
a) x not in range(100) and x % 2 !=0
b) x not in range(1,101) and x % 2 !=0
c) not( x in range(1,101) and x % 2 1=0
d) x not in range(1,101) or x % 2 !=0
In: Computer Science
Hi, i'm creating a c++ program with a linked list of Employees, i'm running into issues as far as displaying programmers only portion and the average salary of all the employees. Please make any changes or comments !
Employee.h file:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include
using namespace std;
enum Role {programmer, manager, director};
struct Employee
{
std::string firstName;
std::string lastName;
int SSN;
std::string department;
double salary;
Role role;
};
#endif
#ifndef NODE_H
#define NODE_H
Node.h file:
#include "Employee.h"
typedef Employee EMP;
struct Node
{
EMP e;
Node * next;
Node();
Node(EMP);
Node(EMP,Node* next);
};
Node::Node()
{
next=NULL;
}
Node::Node(EMP e_data)
{
e=e_data;
}
Node::Node(EMP e_data, Node* next)
{
e=e_data;
this->next= next;
}
#endif
Main cpp file:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Employee.h"
#include "Node.h"
using namespace std;
void setSalary (Employee& emp)
{
emp.salary= 45000+rand() %20000; // generates salary for employee
}
void setRoles(Employee& emp)
{
emp.role = static_cast(rand()%3); // gives employee job title
}
void setSSN (Employee& emp)
{
// int y = x;
emp.SSN =rand()%499999999+400000000; // sets employee SSN
}
void setFirst( Employee& emp, string* name)
{
int y = rand()%5;
emp.firstName = name[y]; //gives random first name
}
void setLast(Employee& emp, string* name)
{
int y = rand()%5;
emp.lastName = name[y]; // gives random last name
}
void setDepartment(Employee& emp, string * dep)
{
int y = rand()%3;
emp.department= dep[y]; //gives employee random department
}
int main()
{
srand(time(NULL)); // random number generator
double avgSalary; // initialize Average Salary
Node* head= NULL; // starting node
Node* prev= NULL; // node next to the last one
Employee e; // object instance
// array of names, roles(job titles), and departments
string roleType [3] = {"programmer", "manager", "director"};
string firstName[5] = {"John", "James", "Joe", "Jessica", "Juno" };
string lastName[5] = {"Smith", "Williams", "Jackson", "Jones", "Johnson" };
string department[5]= {"Accounting", "IT", "Sales" };
// Create linked list of employees
for (int i = 0; i<10; i++)
{
Employee e;
// function calls (roles, salary ...etc)
setFirst(e, firstName);
setLast(e, lastName);
setSSN(e);
setSalary(e);
setRoles(e);
setDepartment(e, department);
// creates nodes for employees
Node*temp = new Node(e);
if (i ==0)
{
head=temp;
prev= temp;
}
else
{
prev->next= temp;
prev = temp; // links the nodes together
}
}
// Display information of all Employees
cout<<"======== Employee Data======="<
prev = head; // starting at the first node
while(prev !=NULL)
{
cout<<(prev->e).firstName<< " ";
cout<<(prev->e).lastName<< " ";
cout<<(prev->e).SSN<< " ";
cout<<(prev->e).salary<< " ";
cout<<(prev->e).department<< " ";
cout
prev= prev->next;
}
cout<<" \n \n";
//
cout<<"======== Programmer Only Data======="<
prev = head; // starts at beginning of linked list
while(prev !=NULL)
{
if (prev->e.role == 0) // checks to see if role is 0 or programmer
cout<<(prev->e).firstName<< " ";
cout<<(prev->e).lastName<< " ";
cout<<(prev->e).SSN<< " ";
cout<<(prev->e).salary<< " ";
cout<<(prev->e).department<< " ";
cout
prev= prev->next; // moves on to next node
// else {
// break;
// }
}
//Computes Average Salary
prev = head; // starts at the first node
while ( prev !=NULL)
{
avgSalary += (prev->e).salary;
prev = prev->next;
}
// Display Average Salary
cout<< "Average Salary: "<< (avgSalary)/5 << "\n";
// Deallocate memory
Node* temp = head;
Node* tail;
while (temp !=NULL)
{
tail=temp->next;
delete temp;
temp = tail;
}
head=NULL;
if (head == NULL )
{
cout<<" List Deleted \n";
}
}
In: Computer Science
In: Computer Science
Please follow the instructions carefully and complete the code given below.
Language: Java
Instructions from your teacher:
(This is a version of an interview question I once saw.) In this problem, we will write a program that, given an integer k, an integer n, and a list of integers, outputs the number of pairs in in the list that add to k.
To receive full credit for design, your algorithm must have a runtime in O(n) , where n is the length of the list of integers. Hint: you can assume that the contains in a HashSet is O(1). Your program should take as input a number k on its own line, followed by a number n on its own line, followed by a space-separated list of n integers. It should then output the number of pairs in the list that add to k. Order does not matter when considering a pair (in other words, in the list [2,1] there is one distinct pair that sums to 3, not two). You may assume that all numbers in the input are distinct. For example, if our file input.txt is:
1
6
1 2 3 4 -2 -3
then we should print 2 since there are two pairs that sum to 1: 3 + (-2) and 4 + (-3).
As another example, if input.txt is:
3
4
1 2 3 4
then we should print 1since there is one pair that sums to 1: 1+2.
The problem PairFinder provides starter code for reading and printing; your task is to fill in thefindPairs()method.
.......................................................................................................................
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read in the value of k
int k = Integer.parseInt(sc.nextLine());
// Read in the value of n
int n = Integer.parseInt(sc.nextLine());
// Read in the list of numbers
int[] numbers = new int[n];
String input = sc.nextLine();
if (input.equals("")) {
numbers = new int[0];
} else {
String[] numberStrings = input.split(" ");
for (int i = 0; i < n; i++) {
numbers[i] = Integer.parseInt(numberStrings[i]);
}
}
System.out.println(findPairs(numbers, k));
}
private static int findPairs(int[] numbers, int k) {
// TODO fill in this function
throw new UnsupportedOperationException();
}
}
In: Computer Science
1.Sage 50 is an integrated system give examples?
2. Enumerate the capacities of sage 50.
In: Computer Science
I have to modify the following code to:
1. Use the unique algorithm to reduce the array to unique values
2. Use the copy algorithm to display the unique results.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
//creating an array of 20 integers
int array[20];
//creating an empty vector
vector<int> vec;
//input from end user to get 20 ints and a for loop to interate through 20
cout << "Enter 20 integers:" << endl;
for (int i = 0; i < 20; i++) {
cin >> array[i];
}
//sorting them
sort(array, array + 20);
//using unique_copy algorithm and a back_inserter, copying and adding each
//unique value from the array to vector
unique_copy(array, array + 20, back_inserter(vec));
//displaying the unique values.
cout << "The unique values are: " << endl;
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;
return 0;
In: Computer Science
Do the problems found week 4 - Programs 1,2,3,4,5,6 and 7.
* Be sure to add your name as a cout in the first lines of each program - else 0 credit.
* Add constructors - a default and parameterized constructor to each.
* Write an .h interface and a .cpp implementation for each class
* Write an Drive/Test file that tests the constructors and functions
* Write a UML class diagram for each class\!!!!!!
Program 6
#include<iostream>
using namespace std;
class Box
{
public:
Box() {
Length = 0;
Width = 0;
Height = 0;
}
double Length;
double Width;
double Height;
double Volume();
double SurfaceArea();
void setWidth ( double n ) {Width = n;}
void setDepth ( double n ) {Length = n;}
void setHeight ( double n ) {Height = n;}
double getWidth () {return Width;}
double getHeight () {return Height;}
double getDepth () {return Length;}
double calcArea () {return 2*(Length*(Width+Height)+Width*Height);}
double calcVolume () {return Length*Width*Height;}
};
int main() {
cout<<"-------- ";
Box B1;
B1.setWidth(2);
B1.setDepth(4);
B1.setHeight(9);
cout << "Height = " << B1.getHeight() << endl;
cout << "Area = " << B1.calcArea() << endl;
cout << "Volume = " << B1.calcVolume() << endl;
Box B2;
B2.setWidth(3);
B2.setDepth(5);
B2.setHeight(10);
cout << "Height = " << B1.getHeight() << endl;
cout << "Area = " << B1. calcArea() << endl;
cout << "Volume = " << B1.calcVolume() << endl;
}
program 7
#include <iostream>
using namespace std;
int main() {
/*
* Circumference = π × diameter = 2 × π × radius
* Area : π r²
* Diameter : 2r
*/
cout<< "Name: "<< endl;
double radius = 0;
cout << "Enter radius of circle: ";
cin >> radius;
if (radius <= 0) {
cout << "Please Enter radius greater than zero" << endl;
return 0;
}
double pie = 22/7.0;
double circumference = 2 * pie * radius;
double area = pie * radius * radius;
double diameter = 2 * radius;
cout << "Circumference of Circle:" << circumference << endl;
cout << "Area of Circle:" << area << endl;
cout << "Diameter of Circle:" << diameter << endl;
cout << "Radius of Circle:" << radius << endl;
return 0;
}
program 2
#include <iostream>
#include <string>
using namespace std;
class myClass{
public:
void setName(string x){
name = x ;
}
string getName(){
return name;
}
private:
string name;
};
int main()
{
cout<<"----";
myClass to;
to.setName("stuff are cool ");
cout << to.getName();
return 0;
}
In: Computer Science
Write a code on C++ to find prime number series.
In: Computer Science
1. What is a Python script?
2. Explain what goes on behind the scenes when your computer runs a Python program.
In: Computer Science
Pi Calculation implementation.
Pi = 4 * (1/1 – 1/3 + 1/5 – 1/7 + 1/9 … (alternating + -) (1/n))
First, Pi should be a double to allow many decimals. Notice that the numerator is always 1 or -1. If you started the numerator at -1, then multiply each term by -1. So if started the numerator at -1 and multiplied it by -1, the first numerator will be 1, then the next the numerator will be -1, alternating + and -.
Then notice that the denominator goes from 1,3,5,7,9 etc. So this is counting by 2s starting at one. For loops are good when you know how many times it will go through the loop. So a for loop might be something like:
for (long denom=1; denom <n;
denom=denom+2)
where denom(inator) is the term that changes by 2 starting at 1
(not zero). We use a long to allow very large numbers
We are using longs, so we can have very long numbers. Likewise, PI should be a double (not a float) to have a very large decimal accuracy
Write a c++ program to calculate the approximate value of pi using this series. The program takes an input denom that determines the number of values we are going to use in this series. Then output the approximation of the value of pi. The more values in the series, the more accurate the data. Note 5 terms isn’t nearly enough to give you an accurate estimation of PI. You will try it with numbers read in from a file. to see the accuracy increase. Use a while loop to read in number of values from a file. Then inside that loop, use a for loop for the calculation.
In: Computer Science
1) given the 8-bit binary number of 10111110 (two)
a)what is the hex representation of this number/
b) what is the decimal value if this number which is an 8-bit number as a two complement signed number. all steps included
c)what is the decimal value of this number as an 8-bit unsigned number, please write all steps
2) given the decimal number (-0.875) or (-7/8) convert it to single-precision floating-point. please show the easiest way to get to this,.
In: Computer Science
In JAVA PLEASE
With the mathematics you have studied so far in your education you have worked with polynomials. Polynomials are used to describe curves of various types; people use them in the real world to graph curves. For example, roller coaster designers may use polynomials to describe the curves in their rides. Polynomials appear in many areas of mathematics and science. Write a program which finds an approximate solution to an equation f(x) = 0 for some function f. Use the bisection method. To solve the problem using this method first find two values of x, A and B, such that when evaluated in the function f(x) they give opposites signs for the y value. If f(x) is continuous between these two values then we know that there is at least one x which evaluates to a 0 y value, which is between these two values A and B. Treat the positive value as an upper bound and the negative value as a lower bound. Divide the space between A and B in half and evaluate the function at that new point. If the value is positive than it replaces the existing upper-bound and if it is negative it replaces the existing lower-bound. Continue dividing the space between the upper-bound and lower-bound in half and evaluating this new value and generating new upper and lower bounds as the case may be. Continue the evaluation process until the x value that you are plugging into the function evaluates to a y value that is zero plus or minus .0000001.
Consider the possibility of finding all the real roots of any given function up to and including x raised to the fifth power. Input should consist of reading the coefficients one at a time to the powers of x up to 5 and some constant. Do a desk check with calculator on y = X2 -2 and identify the variables associated with that problem. Write the code that follows your algorithm. Then test your program on other polynomials such as 2x5 -15x4 + 35x3 -15x2-37x + 30 (roots are -1, 1, 2, 2.5, 3) and 3x5 -17x4 + 25x3 + 5x2 -28x + 12 (roots are -1,1, 2/3, 2, 3). Use at lest 3 methods. One to read the 5 coefficients, one to calculate the value of the polynomial and one to do the binary bisection search. Use the following for loop to work through the X values:for(double x = -5.0000001; x < 5.0000001; x = x + .1)
OUTPUT SHOULD BE LIKE THIS
---------------------------
Please enter the number of coefficients : 5
PLEASE ENTER 5TH COEFFICIENT
2
PLEASE ENTER 4TH COEFFICIENT
-15
PLEASE ENTER 3RD COEFFICIENT
35
PLEASE ENTER 2ND COEFFICIENT
-15
PLEASE ENTER 1ST COEFFICIENT
-37
PLEASE ENTER ZERO COEFFICIENT
30
root is -0.99999999999947171
root is 1.0000000004308118
root is 2.0000000019209287
root is 2.500000000019
root is 2.999999999989406
-------------------------------
JUST LIKE THAT, DO IT WITHOUT ENTERING ANY BRAKETING NUMERS. NO BRAKETING NUMERS, PLEASE.
Do what way you want, as Long As You got the Output like that.
THANK YOU SO MUCH
In: Computer Science
I cant get this to compile in java idk if im making the wrong file or what but this si the code I was given I would like stsep by step java instuctions and which compiler to use to execute this code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
// We are going to create a Game of 15 Puzzle with Java 8 and
Swing
// If you have some questions, feel free to ue comments ;)
public class GameOfFifteen extends JPanel { // our grid will be
drawn in a dedicated Panel
// Size of our Game of Fifteen instance
private int size;
// Number of tiles
private int nbTiles;
// Grid UI Dimension
private int dimension;
// Foreground Color
private static final Color FOREGROUND_COLOR = new Color(239, 83,
80); // we use arbitrary color
// Random object to shuffle tiles
private static final Random RANDOM = new Random();
// Storing the tiles in a 1D Array of integers
private int[] tiles;
// Size of tile on UI
private int tileSize;
// Position of the blank tile
private int blankPos;
// Margin for the grid on the frame
private int margin;
// Grid UI Size
private int gridSize;
private boolean gameOver; // true if game over, false
otherwise
public GameOfFifteen(int size, int dim, int mar) {
this.size = size;
dimension = dim;
margin = mar;
// init tiles
nbTiles = size * size - 1; // -1 because we don't count blank
tile
tiles = new int[size * size];
// calculate grid size and tile size
gridSize = (dim - 2 * margin);
tileSize = gridSize / size;
setPreferredSize(new Dimension(dimension, dimension +
margin));
setBackground(Color.WHITE);
setForeground(FOREGROUND_COLOR);
setFont(new Font("SansSerif", Font.BOLD, 60));
gameOver = true;
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
// used to let users to interact on the grid by clicking
// it's time to implement interaction with users to move tiles to
solve the game !
if (gameOver) {
newGame();
} else {
// get position of the click
int ex = e.getX() - margin;
int ey = e.getY() - margin;
// click in the grid ?
if (ex < 0 || ex > gridSize || ey < 0 || ey >
gridSize)
return;
// get position in the grid
int c1 = ex / tileSize;
int r1 = ey / tileSize;
// get position of the blank cell
int c2 = blankPos % size;
int r2 = blankPos / size;
// we convert in the 1D coord
int clickPos = r1 * size + c1;
int dir = 0;
// we search direction for multiple tile moves at once
if (c1 == c2 && Math.abs(r1 - r2) > 0)
dir = (r1 - r2) > 0 ? size : -size;
else if (r1 == r2 && Math.abs(c1 - c2) > 0)
dir = (c1 - c2) > 0 ? 1 : -1;
if (dir != 0) {
// we move tiles in the direction
do {
int newBlankPos = blankPos + dir;
tiles[blankPos] = tiles[newBlankPos];
blankPos = newBlankPos;
} while(blankPos != clickPos);
tiles[blankPos] = 0;
}
// we check if game is solved
gameOver = isSolved();
}
// we repaint panel
repaint();
}
});
newGame();
}
private void newGame() {
do {
reset(); // reset in intial state
shuffle(); // shuffle
} while(!isSolvable()); // make it until grid be solvable
gameOver = false;
}
private void reset() {
for (int i = 0; i < tiles.length; i++) {
tiles[i] = (i + 1) % tiles.length;
}
// we set blank cell at the last
blankPos = tiles.length - 1;
}
private void shuffle() {
// don't include the blank tile in the shuffle, leave in the solved
position
int n = nbTiles;
while (n > 1) {
int r = RANDOM.nextInt(n--);
int tmp = tiles[r];
tiles[r] = tiles[n];
tiles[n] = tmp;
}
}
// Only half permutations o the puzzle are solvable
// Whenever a tile is preceded by a tile with higher value it
counts
// as an inversion. In our case, with the blank tile in the solved
position,
// the number of inversions must be even for the puzzle to be
solvable
private boolean isSolvable() {
int countInversions = 0;
for (int i = 0; i < nbTiles; i++) {
for (int j = 0; j < i; j++) {
if (tiles[j] > tiles[i])
countInversions++;
}
}
return countInversions % 2 == 0;
}
private boolean isSolved() {
if (tiles[tiles.length - 1] != 0) // if blank tile is not in the
solved position ==> not solved
return false;
for (int i = nbTiles - 1; i >= 0; i--) {
if (tiles[i] != i + 1)
return false;
}
return true;
}
private void drawGrid(Graphics2D g) {
for (int i = 0; i < tiles.length; i++) {
// we convert 1D coords to 2D coords given the size of the 2D
Array
int r = i / size;
int c = i % size;
// we convert in coords on the UI
int x = margin + c * tileSize;
int y = margin + r * tileSize;
// check special case for blank tile
if(tiles[i] == 0) {
if (gameOver) {
g.setColor(FOREGROUND_COLOR);
drawCenteredString(g, "\u2713", x, y);
}
continue;
}
// for other tiles
g.setColor(getForeground());
g.fillRoundRect(x, y, tileSize, tileSize, 25, 25);
g.setColor(Color.BLACK);
g.drawRoundRect(x, y, tileSize, tileSize, 25, 25);
g.setColor(Color.WHITE);
drawCenteredString(g, String.valueOf(tiles[i]), x , y);
}
}
private void drawStartMessage(Graphics2D g) {
if (gameOver) {
g.setFont(getFont().deriveFont(Font.BOLD, 18));
g.setColor(FOREGROUND_COLOR);
String s = "Click to start new game";
g.drawString(s, (getWidth() - g.getFontMetrics().stringWidth(s)) /
2,
getHeight() - margin);
}
}
private void drawCenteredString(Graphics2D g, String s, int x, int
y) {
// center string s for the given tile (x,y)
FontMetrics fm = g.getFontMetrics();
int asc = fm.getAscent();
int desc = fm.getDescent();
g.drawString(s, x + (tileSize - fm.stringWidth(s)) / 2,
y + (asc + (tileSize - (asc + desc)) / 2));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g2D);
drawStartMessage(g2D);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Game of Fifteen");
frame.setResizable(false);
frame.add(new GameOfFifteen(4, 550, 30),
BorderLayout.CENTER);
frame.pack();
// center on the screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
In: Computer Science
In: Computer Science
In: Computer Science