Python Codes
.pdf
keyboard_arrow_up
School
Harvard University *
*We aren’t endorsed by this school
Course
228
Subject
Computer Science
Date
Feb 20, 2024
Type
Pages
5
Uploaded by LieutenantDragon138
Rock paper scissors
# Rock paper scissor game
# 10/25/2021
import random
player_score = 0
computer_score = 0
def rockPaperScissors():
global player_score
global computer_score
user_action = input("Enter a choice (rock[r], paper[p], scissors[s]): ")
possible_actions = ["r", "p", "s"]
computer_action = random.choice(possible_actions)
if user_action not in possible_actions:
print("Invalid input, try again")
else:
print(f"\nUser: {user_action}\nComputer: {computer_action}\n")
if user_action == computer_action:
print(f"Both players selected: {user_action}\nIt's a tie!")
elif user_action == "r":
if computer_action == "s":
player_score += 1
print("Rock smashes scissors! You win!")
else:
computer_score += 1
print("Paper covers rock! You lose.")
elif user_action == "p":
if computer_action == "r":
player_score += 1
print("Paper covers rock! You win!")
else:
computer_score += 1
print("Scissors cuts paper! You lose.")
elif user_action == "s":
if computer_action == "p":
player_score += 1
print("Scissors cuts paper! You win!")
else:
computer_score += 1
print("Rock smashes scissors! You lose.")
print ("\nYour score:", str(player_score)+ ", Computer score:", str(computer_score))
while True:
rockPaperScissors()
Prime numbers displayer
# Prime number displayer
def is_prime(integer):
if (integer==1):
return False
elif (integer==2):
return True
else:
for x in range(2,integer):
if (integer % x == 0):
return False
return True
for i in range(1,101):
if is_prime(i):
if i==97:
print(i)
else:
print(i)
Prime number checker
# Prime number indicator
def is_prime(integer):
if (integer==1):
return False
elif (integer==2):
return True
else:
for x in range(2,integer):
if (integer % x == 0):
return False
return True
Monthly tax sales
# Monthly tax calculator
def tax(sales):
stateTax=(sales*.05)
countyTax=(sales*.025)
totalSales=(sales-(stateTax+countyTax))
print(f"State sales tax is: ${stateTax:.2f}")
print(f"County sales tax is: ${countyTax:.2f}")
print(f"Your total monthly sales after tax: ${totalSales:.2f}")
Merge sort algorithm
# Merge sort algorithm
def mergeSort(myList):
if len(myList) > 1:
mid = len(myList) // 2
left = myList[:mid]
right = myList[mid:]
# Recursive call on each half
mergeSort(left)
mergeSort(right)
# Two iterators for traversing the two halves
i = j = k = 0
# K is Iterator for the main list
while i < len(left) and j < len(right):
if left[i] <= right[j]:
# The value from the left half has been used
myList[k] = left[i]
# Move the iterator forward
i += 1
else:
myList[k] = right[j]
j += 1
# Move to the next slot
k += 1
# For all the remaining values
while i < len(left):
myList[k] = left[i]
i += 1
k += 1
while j < len(right):
myList[k]=right[j]
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
C++
A robot is initially located at position (0; 0) in a grid [?5; 5] [?5; 5]. The robot can move randomly in any of the directions: up, down, left, right. The robot can only move one step at a time. For each move, print the direction of the move and the current position of the robot. If the robot makes a circle, which means it moves back to the original place, print "Back to the origin!" to the console and stop the program. If it reaches the boundary of the grid, print \Hit the boundary!" to the console and stop the program.
A successful run of your code may look like:Down (0,-1)Down (0,-2)Up (0,-1)Left (-1,-1)Left (-2,-1)Up (-2,0)Left (-3,0)Left (-4,0)Left (-5,0)Hit the boundary!
or
Left (-1,0)Down (-1,-1)Right (0,-1)Up (0,0)Back to the origin!
About: This program is to give you practice using the control ow, the random number generator, and output formatting. You may use <iomanip> to format your output. You may NOT use #include "stdafx.h".
arrow_forward
PLEASE HELP ME! ?
Maximize and use alternative method to this code!
package com.btech.pf101;
import java.io.bufferedreader;
import java.io.inputstreamreader;
import java.util.calendar;
import java.util.date;
public class pawnshopcode {
private static final bufferedreader br = new bufferedreader(new inputstreamreader(system.in));
private static string name;
private static int age;
private static string address;
private static string contactno;
private static int itemtype;
private static string itemtypename;
private static final int itemtype_gagdet = 1;
private static final int itemtype_jewelry = 2;
private static final int itemtype_musicinstrument = 3;
private static final int itemtype_homeequipment = 4;
private static final int itemtype_landtitle = 5;
private static string itemdescription;
private static int periodtype;
private static string periodtypename;
private static final int periodtype_days = 1;
private…
arrow_forward
function loginValidate () {
var id = document.getElementById ('myid').value;
var pass = document.getElementById('mypassword').value;
if ((id == null : id
alert ("ID and Pasword both must be filled out") :
"") && (pass == null , pass ==
")){
==
return false:
else if (id == null || id ==
"") {
alert ("ID must be filled out ");
return false;
else if (pass == null || pass ==
"") {
alert ("Password must be filled out ");
return false;
arrow_forward
class TicTacToePlayer:
# Player for a game of Tic Tac Toe
def __init__(self, symbol, name):
self.symbol = symbol
self.name = name
def move(self, board):
move = int(input(self.name + " make your move 1-9:"))
move -= 1
y = move % 3
x = move // 3
board[x][y] = self.symbol
def is_symbol(self, symbol):
if symbol == self.symbol:
return True
class TicTacToe:
# Game of TicTacToe in a class!
def __init__(
self, p1_symbol="X", p2_symbol="O", p1_name="Player1", p2_name="Player2"
):
self.p1 = TicTacToePlayer(p1_symbol, p1_name)
self.p2 = TicTacToePlayer(p2_symbol, p2_name)
self.board = [[" " for x in range(3)] for x in range(3)]
def play_game(self):
turn = 0
winner_symbol = False
while not winner_symbol:
self._print_board()
if turn % 2:
self.p2.move(self.board) # replace this line with a call…
arrow_forward
Integer userValue is read from input. Assume userValue is greater than 1000 and less than 99999. Assign tensDigit with
userValue's tens place value.
Ex: If the input is 15876, then the output is:
The value in the tens place is: 7
2
3 public class ValueFinder {
4
5
6
7
8
9
10
11
12
13
GHE
14
15
16}
public static void main(String[] args) {
new Scanner(System.in);
}
Scanner scnr
int userValue;
int tensDigit;
int tempVal;
userValue = scnr.nextInt();
Your code goes here */
11
System.out.println("The value in the tens place is: + tensDigit);
arrow_forward
What need to notepad ++ total cod3.
Var adventurersName = ["George", " Tim", " Sarah", " Mike", " Edward"];var adventurersKilled = 3;var survivors;var leader = "Captain Thomas King";var numberOfAdventurers = adventurersName.length;
survivors = numberOfAdventurers - adventurersKilled;
console.log("Welcome to The God Among Us\n");console.log("A group of adventurers began their search for the mystical god said to live among us. In charge of the squad was " + leader + " who was famous for his past exploits. Along the way, the group of comrades were attacked by the god's loyal followers. The adventurers fought with bravado and strength under the tutelage of "+ leader + " the followers were defeated but they still suffered great losses. After a headcount of the remaining squad, "+ adventurersKilled +" were found to be dead which left only " + survivors + " remaining survivors.\n");
console.log("Current Statistics :\n");console.log("Total Adventurers = " +…
arrow_forward
Python
Data =
{
"logs": [
{
"logType": “xxxxx”
},
{
"logType": “43435”
},
{
"logType": “count”
},
{
"logType": “4452”
},
{
"logType": “count”
},
{
"logType": “count”
},
{
"logType": “43435”
},
{
"logType": "count"
},
{
"logType": "count"
}
]
}
So, please count the total of "logType": “count”
My desired output:
{
"count”: 5
}
arrow_forward
function myChoice(items) {if (!this.value && !this.items) {this.items = items[0];} else if (!this.value || (params.length > 0 && params[0] == "rechoose")) {let index = Math.floor(Math.random() * (this.items.length - 0)) + 0;this.value = this.items[index];return this.value;}return this.value;}
var a = myChoice([1, "a", 3, false]);console.log(myChoice(3, 12));console.log(myChoice(51, -2));console.log(myChoice("happy", false));console.log(myChoice([1, 2, 3]));console.log(myChoice("rechoose"));console.log(myChoice(a, a));
these are directions and examples
myChoice( items )
This function accepts a list of items as input and creates a function that returns a randomly-chosen item. After choosing a random item, that same item will be always be returned, regardless of the functions input, with one exception. If the first input is the string 'rechoose', then a new random item will be chosen and therafter returned. this is KEYYYY!!
Examples
var a = myChoice( [1, "a", 3, false]…
arrow_forward
class Pt:
def init_(self, x, y):
self.x X
P(3,4)
self.y = y
def _str__(self):
x, y = self.x, self.y
return f'P({x},{y})'
True
18
# add coordinate-wise
def add_(self, other):
nx =
13
14
ny =
15
16
return
17
Pt(1, 1)
b = Pt (2, 3)
с %3D а + b
d = b + Pt(5, 6)
print (c)
print ( isinstance (d, Pt))
print (d)
%3D
arrow_forward
CodeWorkout
Gym
Course
Q Search
kola shreya@ columbusstate.edu
Search exercises...
X274: Recursion Programming Exercise: Cannonballs
X274: Recursion Programming Exercise:
Cannonballs
Spherical objects, such as cannonballs, can be stacked to form a pyramid with one cannonball at the top,
sitting on top of a square composed of four cannonballs, sitting on top of a square composed of nine.
cannonballs, and so forth.
Given the following recursive function signature, write a recursive function that takes as its argument the
height of a pyramid of cannonballs and returns the number of cannonballs it contains.
Examples:
cannonball(2) -> 5
Your Answwer:
1 public int cannonball(int height) {
3.
4}
Check my answer!
Reset
Next exercise
Feedback
arrow_forward
getRandomLib.h:
// This library provides a few helpful functions to return random values// * getRandomInt() - returns a random integer between min and max values// * getRandomFraction() - returns a random float between 0 and 1// * getRandomFloat() - returns a random float between min and max values// * getRandomDouble() - returns a random double between min and max values// * getRandomBool() - returns a random bool value (true or false)// * getRandomUpper() - returns a random char between 'A' and 'Z', or between min/max values// * getRandomLower() - returns a random char between 'a' and 'z', or between min/max values// * getRandomAlpha() - returns a random char between 'A' and 'Z' or 'a' and 'z'// * getRandomDigit() - returns a random char between '0' and '9', or between min/max values// * getRandomChar() - returns a random printable char//// Trey Herschede, 7/31/2019
#ifndef GET_RANDOM_LIB_H#define GET_RANDOM_LIB_H
#include <cstdlib>#include <random>#include…
arrow_forward
$marks = array( "Sara" => array( "Programming" => 95, "DataBase" => 85, "Web" => 74, ), "Diana" => array( "Programming" => 78, "DataBase" => 98, "Web" => 66, ), "Amy" => array( "Programming" => 88, "DataBase" => 76, "Web" => 99, ), );
1 : sort the array by the name of student from A-Z;
2 : search if Ram is exist :if exiset print the value; else : student does not exist
3 : calculate the avg of each student and print it as :the avg for Sara is : 84.66
arrow_forward
Staff
# name: String
# id: int
PartTimer
+ Staff()
+ Staff(name: String,
id: int)
skillLevel: int
+ getName (): String
+ getId (): int
+ calculatePay () : double
+ toString (): String
hoursWorked: int
+ Part Timer (name: String,
id: int,
skillLevel: int,
hoursWorked: int)
+ getskillLevel(): int
+ getHours Worked () : int
+ tostring () : String
java.lang.Comparable
compareTo (o: Object): int
Figure 1: The relationship between staff, PartTimer and Comparable
Skill Level / Tahap Kemahiran
Pay Rate Per Hour/ Kadar Bayaran Per Jam
0 ( Basic / Asas)
RM50.00
1 (Moderate / Sederhana)
RM100.00
RM150.00
2 (Expert / Mahir)
Table 1: Skill level and the pay rate per hour
Write a complete Java program to create PartTimer class and test class based on the Figure 1, Table 1
and the following requirements: Partimer class is derived from staff and implements Comparable
Interface. The calculate Pay()method from the staff class will be implemented in the subclass to
calculate the employee's pay. The pay…
arrow_forward
Assignment: Enhancing Dice Roll Stats Calculator Program
Introduction:
The project involves creating a program to roll pairs of dice, gathering statistics on the outcomes. Probability differs in the roll of two dice compared to a single die due to varied combinations.
Dice Roll Series:
User greeted with "Welcome to the Dice Roll Stats Calculator!" and prompted to specify rolls.
Java classes: DiceRoller, Indicator, Validator.
DiceRoller:
Arrays: rollSeries (captures results), statIndicators (stores statistical indicators).
Constructor rolls dice as per user request.
Methods collect stats and print the report.
Indicator class:
Contains dicePairTotal and dicePairCount.
Displaying Results:
Sort statIndicators array before display.
Indicator objects sortable by dicePairCount (implements Comparable).
Example output:-----------------------dicepair rolltotal count percent---- ------ --------7 5 50%10 2 20%4 2 20%2 1 10%
Tasks:…
arrow_forward
In C# language using Microsoft Visual Studio in Windows Forms App (.NET Framework)
A slot machine is a gambling device that the user inserts money into and then pulls a lever (or presses a button). The slot machine then displays a set of random images. If two or more of the images match, the user wins an amount of money, which the slot machine dispenses back to the user. Design a program that simulates a slot machine. When the program runs, it should do the following: Ask the user to enter the amount of money he or she wants to insert into the slot machine.
Create an application that simulates a slot machine.
The application should let the user enter into a TextBox the amount of money he or she is inserting into the machine. When the user clicks the Spin button, the application should display three randomly selected symbols. (Slot machines traditionally display fruit symbols.
arrow_forward
python
Geography Grades 3Make a copy of your program for the problem Geography Grades 2 and change thecode in such a way that your program can process multiple groups.These groups are on the input separated by ’=\n’. Every group starts with a first line that contains the name of thegroup and the lines after contain the information about the students in the same way as is specified for the problem Geography Grades 1.With the input1bErik Eriksen__________4.3 4.9 6.7Frans Franssen________5.8 6.9 8.0=2bAnne Adema____________6.5 5.5 4.5Bea de Bruin__________6.7 7.2 7.7Chris Cohen___________6.8 7.8 7.3Dirk Dirksen__________1.0 5.0 7.7The output should be:Report for group 1bErik Eriksen has a final grade of 6.0Frans Franssen has a final grade of 7.0End of reportReport for group 2bAnne Adema has a final grade of 6.0Bea de Bruin has a final grade of 7.0Chris Cohen has a final grade of 7.5Dirk Dirksen has a final grade of 4.5End of report"""import sysgroups = sys.stdin.read().split("=\n")for…
arrow_forward
What will this code print?
def fun_a():
print("aa")
def fun_b():
print("bb")
def fun_c():
print("cc")
def main():
fun_c()
fun_a()
fun_b()
fun_c()
main()
arrow_forward
12.6 LAB 12 - Part 1: Exception handling to detect input string vs.
integer
The given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. The
program fails and throws an exception if the second input on a line is a string rather than an integer. At FIXME in the code, add try and
except blocks to catch the ValueError exception and output 0 for the age.
Ex: If the input is:
Lee 18
Lua 21
Mary Beth 19.
Stu 33
-1
then the output is:
Lee 19.
Lua 22
Mary 0
Stu 34
arrow_forward
class BinaryImage:
def __init__(self):
pass
def compute_histogram(self, image):
"""Computes the histogram of the input image
takes as input:
image: a grey scale image
returns a histogram as a list"""
hist = [0]*256
return hist
def find_otsu_threshold(self, hist):
"""analyses a histogram it to find the otsu's threshold assuming that the input hstogram is bimodal histogram
takes as input
hist: a bimodal histogram
returns: an optimal threshold value (otsu's threshold)"""
threshold = 0
return threshold
def binarize(self, image):
"""Comptues the binary image of the the input image based on histogram analysis and thresholding
take as input
image: an grey scale image
returns: a binary image"""
bin_img = image.copy()
return…
arrow_forward
interface IResit {
int row = 5;
int col = 3;
int upperBound = 10;
public int[][] initTable(); // initialize 5x3 table with random (upper bound is:10) integer
// numbers. “table” is class variable
public int[] convertTwoToOne(int[][] a); // convert a two dimensional array into one dimensional
// array
/*
* for example:
* a= 1 3 5
* 6 9 -6
* 2 7 4
*
* Your method should return:
* 4 7 2 -6 9 6 5 3 1
*
*/
public double averageOfOddElements(int[] a);
public double averageOfEvenElements(int[][] a);
}// end of the interface
/*
Write a class that implements the given interface above.
1. Your class should have two constructors:
1. Default constructor: In this case, row, column and upper bound are same as the data that defined in the
interface.
2. Overloaded constructor: in this case it should get three parameters, row, column, upper bound respectively.
2. Your constructor parameters are…
arrow_forward
please code in python
You place a pawn at the top left corner of an n-by-n chess board, labeled (0,0). For each move, you have a choice: move the pawn down a single space, or move the pawn down one space and right one space. That is, if the pawn is at position (i,j), you can move the pawn to (i+1,j) or (i+1, j+1).
Ask the user for the size of a chessboard, n (integer). Find the number of different paths starting from (0,0) that the pawn could take to reach each position on the chess board. For example, there are two different paths the pawn can take to reach (2,1). Look at the diagrams below to convince yourself of this. You can see the four paths that you can take by move 2.
Start -> Move 1 -> Move 2
(0,0) -> (1,0) -> (2,1)
(0,0) -> (1,0) -> (2,0)
(0,0) -> (1,1) -> (2,1)
(0,0) -> (1,1) -> (2,2)
Print the board with the number of ways to reach each square labeled as shown below.
For example:
Enter a board size: 4
1 0 0 0
1 1 0 0
1 2 1 0
1 3 3 1
arrow_forward
C++
arrow_forward
The Spider Game
Introduction:
In this assignment you will be implementing a game that simulates a spider hunting for food using python.
The game is played on a varying size grid board.
The player controls a spider. The spider, being a fast creature, moves in the pattern that emulates a knight from the game of chess.
There is also an ant that slowly moves across the board, taking steps of one square in one of the eight directions.
The spider's goal is to eat the ant by entering the square it currently occupies, at which point another ant begins moving across the board from a random starting location.
Game Definition:
The above Figure illustrates the game.
The yellow box shows the location of the spider.
The green box is the current location of the ant.
The blue boxes are the possible moves the spider could make.
The red arrow shows the direction that the ant is moving - which, in this case, is the horizontal X-direction. When the ant is eaten, a new ant is randomly placed on one of the…
arrow_forward
dictionaries = []dictionaries.append({"First":"Bob", "Last":"Jones", "Color":"red"})dictionaries.append({"First":"Harpreet", "Last":"Kaur", "Color":"green"})dictionaries.append({"First":"Mohamad", "Last":"Argani", "Color":"blue"})for i in range(0, -1,len(dictionaries)):print(dictionaries[i]['First'])
********************
Please modify the code, so the result will show first, last names and colour separated by a single space
arrow_forward
Java Program
Fleet class- reading from a file called deltafleet.txt-Using file and Scanner
Will be creating a file called newfleet.txt
Instance Variables:o An array that stores Aircraft that represents Delta Airlines entire fleeto A variable that represents the count for the number of aircraft in the fleet• Methods:o Constructor- One constructor that instantiates the array and sets the count to zeroo readFile()- This method accepts a string that represents the name of the file to beread. It will then read the file. Once the data is read, it should create an aircraft andthen pass the vehicle to the addAircraft method. It should not allow any duplicationof records. Be sure to handle all exceptions.o writeFile()- This method accepts a string that represents the name of the file to bewritten to and then writes the contents of the array to a file. This method shouldcall a sort method to sort the array before writing to it.o sortArray()- This method returns a sorted array. The array is…
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781305480537
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Microsoft Visual C#
Computer Science
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,
Related Questions
- C++ A robot is initially located at position (0; 0) in a grid [?5; 5] [?5; 5]. The robot can move randomly in any of the directions: up, down, left, right. The robot can only move one step at a time. For each move, print the direction of the move and the current position of the robot. If the robot makes a circle, which means it moves back to the original place, print "Back to the origin!" to the console and stop the program. If it reaches the boundary of the grid, print \Hit the boundary!" to the console and stop the program. A successful run of your code may look like:Down (0,-1)Down (0,-2)Up (0,-1)Left (-1,-1)Left (-2,-1)Up (-2,0)Left (-3,0)Left (-4,0)Left (-5,0)Hit the boundary! or Left (-1,0)Down (-1,-1)Right (0,-1)Up (0,0)Back to the origin! About: This program is to give you practice using the control ow, the random number generator, and output formatting. You may use <iomanip> to format your output. You may NOT use #include "stdafx.h".arrow_forwardPLEASE HELP ME! ? Maximize and use alternative method to this code! package com.btech.pf101; import java.io.bufferedreader; import java.io.inputstreamreader; import java.util.calendar; import java.util.date; public class pawnshopcode { private static final bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); private static string name; private static int age; private static string address; private static string contactno; private static int itemtype; private static string itemtypename; private static final int itemtype_gagdet = 1; private static final int itemtype_jewelry = 2; private static final int itemtype_musicinstrument = 3; private static final int itemtype_homeequipment = 4; private static final int itemtype_landtitle = 5; private static string itemdescription; private static int periodtype; private static string periodtypename; private static final int periodtype_days = 1; private…arrow_forwardfunction loginValidate () { var id = document.getElementById ('myid').value; var pass = document.getElementById('mypassword').value; if ((id == null : id alert ("ID and Pasword both must be filled out") : "") && (pass == null , pass == ")){ == return false: else if (id == null || id == "") { alert ("ID must be filled out "); return false; else if (pass == null || pass == "") { alert ("Password must be filled out "); return false;arrow_forward
- class TicTacToePlayer: # Player for a game of Tic Tac Toe def __init__(self, symbol, name): self.symbol = symbol self.name = name def move(self, board): move = int(input(self.name + " make your move 1-9:")) move -= 1 y = move % 3 x = move // 3 board[x][y] = self.symbol def is_symbol(self, symbol): if symbol == self.symbol: return True class TicTacToe: # Game of TicTacToe in a class! def __init__( self, p1_symbol="X", p2_symbol="O", p1_name="Player1", p2_name="Player2" ): self.p1 = TicTacToePlayer(p1_symbol, p1_name) self.p2 = TicTacToePlayer(p2_symbol, p2_name) self.board = [[" " for x in range(3)] for x in range(3)] def play_game(self): turn = 0 winner_symbol = False while not winner_symbol: self._print_board() if turn % 2: self.p2.move(self.board) # replace this line with a call…arrow_forwardInteger userValue is read from input. Assume userValue is greater than 1000 and less than 99999. Assign tensDigit with userValue's tens place value. Ex: If the input is 15876, then the output is: The value in the tens place is: 7 2 3 public class ValueFinder { 4 5 6 7 8 9 10 11 12 13 GHE 14 15 16} public static void main(String[] args) { new Scanner(System.in); } Scanner scnr int userValue; int tensDigit; int tempVal; userValue = scnr.nextInt(); Your code goes here */ 11 System.out.println("The value in the tens place is: + tensDigit);arrow_forwardWhat need to notepad ++ total cod3. Var adventurersName = ["George", " Tim", " Sarah", " Mike", " Edward"];var adventurersKilled = 3;var survivors;var leader = "Captain Thomas King";var numberOfAdventurers = adventurersName.length; survivors = numberOfAdventurers - adventurersKilled; console.log("Welcome to The God Among Us\n");console.log("A group of adventurers began their search for the mystical god said to live among us. In charge of the squad was " + leader + " who was famous for his past exploits. Along the way, the group of comrades were attacked by the god's loyal followers. The adventurers fought with bravado and strength under the tutelage of "+ leader + " the followers were defeated but they still suffered great losses. After a headcount of the remaining squad, "+ adventurersKilled +" were found to be dead which left only " + survivors + " remaining survivors.\n"); console.log("Current Statistics :\n");console.log("Total Adventurers = " +…arrow_forward
- Python Data = { "logs": [ { "logType": “xxxxx” }, { "logType": “43435” }, { "logType": “count” }, { "logType": “4452” }, { "logType": “count” }, { "logType": “count” }, { "logType": “43435” }, { "logType": "count" }, { "logType": "count" } ] } So, please count the total of "logType": “count” My desired output: { "count”: 5 }arrow_forwardfunction myChoice(items) {if (!this.value && !this.items) {this.items = items[0];} else if (!this.value || (params.length > 0 && params[0] == "rechoose")) {let index = Math.floor(Math.random() * (this.items.length - 0)) + 0;this.value = this.items[index];return this.value;}return this.value;} var a = myChoice([1, "a", 3, false]);console.log(myChoice(3, 12));console.log(myChoice(51, -2));console.log(myChoice("happy", false));console.log(myChoice([1, 2, 3]));console.log(myChoice("rechoose"));console.log(myChoice(a, a)); these are directions and examples myChoice( items ) This function accepts a list of items as input and creates a function that returns a randomly-chosen item. After choosing a random item, that same item will be always be returned, regardless of the functions input, with one exception. If the first input is the string 'rechoose', then a new random item will be chosen and therafter returned. this is KEYYYY!! Examples var a = myChoice( [1, "a", 3, false]…arrow_forwardclass Pt: def init_(self, x, y): self.x X P(3,4) self.y = y def _str__(self): x, y = self.x, self.y return f'P({x},{y})' True 18 # add coordinate-wise def add_(self, other): nx = 13 14 ny = 15 16 return 17 Pt(1, 1) b = Pt (2, 3) с %3D а + b d = b + Pt(5, 6) print (c) print ( isinstance (d, Pt)) print (d) %3Darrow_forward
- CodeWorkout Gym Course Q Search kola shreya@ columbusstate.edu Search exercises... X274: Recursion Programming Exercise: Cannonballs X274: Recursion Programming Exercise: Cannonballs Spherical objects, such as cannonballs, can be stacked to form a pyramid with one cannonball at the top, sitting on top of a square composed of four cannonballs, sitting on top of a square composed of nine. cannonballs, and so forth. Given the following recursive function signature, write a recursive function that takes as its argument the height of a pyramid of cannonballs and returns the number of cannonballs it contains. Examples: cannonball(2) -> 5 Your Answwer: 1 public int cannonball(int height) { 3. 4} Check my answer! Reset Next exercise Feedbackarrow_forwardgetRandomLib.h: // This library provides a few helpful functions to return random values// * getRandomInt() - returns a random integer between min and max values// * getRandomFraction() - returns a random float between 0 and 1// * getRandomFloat() - returns a random float between min and max values// * getRandomDouble() - returns a random double between min and max values// * getRandomBool() - returns a random bool value (true or false)// * getRandomUpper() - returns a random char between 'A' and 'Z', or between min/max values// * getRandomLower() - returns a random char between 'a' and 'z', or between min/max values// * getRandomAlpha() - returns a random char between 'A' and 'Z' or 'a' and 'z'// * getRandomDigit() - returns a random char between '0' and '9', or between min/max values// * getRandomChar() - returns a random printable char//// Trey Herschede, 7/31/2019 #ifndef GET_RANDOM_LIB_H#define GET_RANDOM_LIB_H #include <cstdlib>#include <random>#include…arrow_forward$marks = array( "Sara" => array( "Programming" => 95, "DataBase" => 85, "Web" => 74, ), "Diana" => array( "Programming" => 78, "DataBase" => 98, "Web" => 66, ), "Amy" => array( "Programming" => 88, "DataBase" => 76, "Web" => 99, ), ); 1 : sort the array by the name of student from A-Z; 2 : search if Ram is exist :if exiset print the value; else : student does not exist 3 : calculate the avg of each student and print it as :the avg for Sara is : 84.66arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTEBK JAVA PROGRAMMINGComputer ScienceISBN:9781305480537Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTMicrosoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781305480537
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Microsoft Visual C#
Computer Science
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,