hw1
.py
keyboard_arrow_up
School
University of Massachusetts, Amherst *
*We aren’t endorsed by this school
Course
325
Subject
Computer Science
Date
Apr 24, 2024
Type
py
Pages
5
Uploaded by LieutenantKnowledge1057 on coursehero.com
import matplotlib.pyplot as plt
import math
import os
import time
import operator
from collections import defaultdict
# Global class labels.
POS_LABEL = 'pos'
NEG_LABEL = 'neg'
###### DO NOT MODIFY THIS FUNCTION #####
def tokenize_doc(doc):
"""
Tokenize a document and return its bag-of-words representation.
doc - a string representing a document.
returns a dictionary mapping each word to the number of times it appears in doc.
"""
bow = defaultdict(float)
tokens = doc.split()
lowered_tokens = map(lambda t: t.lower(), tokens)
for token in lowered_tokens:
bow[token] += 1.0
return dict(bow)
###### END FUNCTION #####
def n_word_types(word_counts):
'''
return a count of all word types in the corpus
using information from word_counts
'''
## TODO: complete me!
return len(word_counts)
def n_word_tokens(word_counts):
'''
return a count of all word tokens in the corpus
using information from word_counts
'''
res = 0
## TODO: complete me!
for i in word_counts:
res += word_counts[i]
return res
class NaiveBayes:
"""A Naive Bayes model for text classification."""
def __init__(self, path_to_data, tokenizer):
# Vocabulary is a set that stores every word seen in the training data
self.vocab = set()
self.path_to_data = path_to_data
self.tokenize_doc = tokenizer
self.train_dir = os.path.join(path_to_data, "train")
self.test_dir = os.path.join(path_to_data, "test")
# class_total_doc_counts is a dictionary that maps a class (i.e., pos/neg) to
# the number of documents in the trainning set of that class
self.class_total_doc_counts = { POS_LABEL: 0.0,
NEG_LABEL: 0.0 }
# class_total_word_counts is a dictionary that maps a class (i.e., pos/neg)
to
# the number of words in the training set in documents of that class
self.class_total_word_counts = { POS_LABEL: 0.0,
NEG_LABEL: 0.0 }
# class_word_counts is a dictionary of dictionaries. It maps a class (i.e.,
# pos/neg) to a dictionary of word counts. For example:
# self.class_word_counts[POS_LABEL]['awesome']
# stores the number of times the word 'awesome' appears in documents
# of the positive class in the training documents.
self.class_word_counts = { POS_LABEL: defaultdict(float),
NEG_LABEL: defaultdict(float) }
def train_model(self):
"""
This function processes the entire training set using the global PATH
variable above. It makes use of the tokenize_doc and update_model
functions you will implement.
"""
pos_path = os.path.join(self.train_dir, POS_LABEL)
neg_path = os.path.join(self.train_dir, NEG_LABEL)
for (p, label) in [ (pos_path, POS_LABEL), (neg_path, NEG_LABEL) ]:
for f in os.listdir(p):
with open(os.path.join(p,f),'r') as doc:
content = doc.read()
self.tokenize_and_update_model(content, label)
self.report_statistics_after_training()
def report_statistics_after_training(self):
"""
Report a number of statistics after training.
"""
print ("REPORTING CORPUS STATISTICS")
print ("NUMBER OF DOCUMENTS IN POSITIVE CLASS:", self.class_total_doc_counts[POS_LABEL])
print ("NUMBER OF DOCUMENTS IN NEGATIVE CLASS:", self.class_total_doc_counts[NEG_LABEL])
print ("NUMBER OF TOKENS IN POSITIVE CLASS:", self.class_total_word_counts[POS_LABEL])
print ("NUMBER OF TOKENS IN NEGATIVE CLASS:", self.class_total_word_counts[NEG_LABEL])
print ("VOCABULARY SIZE: NUMBER OF UNIQUE WORDTYPES IN TRAINING CORPUS:", len(self.vocab))
def update_model(self, bow, label):
"""
IMPLEMENT ME!
Update internal statistics given a document represented as a bag-of-words
bow - a map from words to their counts
label - the class of the document whose bag-of-words representation was input
This function doesn't return anything but should update a number of internal
statistics. Specifically, it updates:
- the internal map the counts, per class, how many times each word was
seen (self.class_word_counts)
- the number of words seen for each label (self.class_total_word_counts)
- the vocabulary seen so far (self.vocab)
- the number of documents seen of each label (self.class_total_doc_counts)
"""
self.class_total_doc_counts[label] += 1.0
self.class_total_word_counts[label] += sum(bow.values())
for word, count in bow.items():
self.class_word_counts[label][word] += count
self.vocab.add(word)
def tokenize_and_update_model(self, doc, label):
"""
IMPLEMENT ME!
Tokenizes a document doc and updates internal count statistics.
doc - a string representing a document.
label - the sentiment of the document (either postive or negative)
Make sure when tokenizing to lower case all of the tokens!
"""
tokens = doc.lower().split()
bow = defaultdict(float)
for word in tokens:
bow[word] += 1.0
self.update_model(bow, label)
def top_n(self, label, n):
"""
Implement me!
Returns the most frequent n tokens for documents with class 'label'.
"""
word_counts = self.class_word_counts[label]
top_n_words = (sorted(word_counts.items(), key=lambda x: x[1], reverse=True))[:n]
return top_n_words
def p_word_given_label(self, word, label):
"""
Implement me!
Returns the probability of word given label
according to this NB model.
"""
word_count = self.class_word_counts[label][word]
total_word_count = self.class_total_word_counts[label]
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
Words with given shape def words_with_given_shape(words, shape):
The shape of the given word of length n is a list of n - 1 integers, each one either -1, 0 or +1 to indicate whether the next letter following the letter in that position comes later (+1), is the same (0) or comes earlier (-1) in the alphabetical order of English letters. For example, the shape of the word 'hello' is [-1, +1, 0, +1], whereas the shape of 'world' is [-1, +1, -1, -1]. Find and return a list of all words that have that particular shape, listed in alphabetical order.
Note that your function, same as all the other functions specified in this document that operate on lists of words, should not itself try to read the wordlist file words_sorted.txt, even when Python makes this possible with just a couple of lines of code. The tester script already reads in the entire wordlist and builds the list of words from there. Your function should use this given list of words without even caring which particular file it…
arrow_forward
Words with given shape
def words_with_given_shape(words, shape):
The shape of the given word of length n is a list of n - 1 integers, each one either -1, 0 or +1 to indicate whether the next letter following the letter in that position comes later (+1), is the same (0) or comes earlier (-1) in the alphabetical order of English letters. For example, the shape of the word 'hello' is [-1, +1, 0, +1], whereas the shape of 'world' is [-1, +1, -1, -1]. Find and return a list of all words that have that particular shape, listed in alphabetical order.
Note that your function, same as all the other functions speci0ied in this document that operate on lists of words, should not itself try to read the wordlist 0ile words_sorted.txt, even when Python makes this possible with just a couple of lines of code. The tester script already reads in the entire wordlist and builds the list of words from there. Your function should use this given list of words without even caring which particular 0ile it…
arrow_forward
Doctor
-signature:String
-doctorID:int
- medicine:Arraylist
+Doctor(signature:String,doctorID:int)
+PrescribeMedicine():void
+ salary ()
+checkRecords():void
Medicine
Pharmacist
-medName:String
-startTime:int
-dosage :int
-endTime:int
-date_prescribed:int
- medicine:Arraylist
+Medicine(medName:String,-dosage :int,date_prescribed:int)
+Pharmacist (startTime:int,endTime:int)
+checkForConflict():double
+confirm_prescription():String
+getStartTime():int
+getEndTime():int
+setStartTime(time:int):void
+setEndTime(time1:int).void
arrow_forward
dictionaries = []
dictionaries.append({"First":"Bob", "Last":"Jones"})
dictionaries.append({"First":"Harpreet", "Last":"Kaur"})
dictionaries.append({"First":"Mohamad", "Last":"Argani"})
for i in range(0, len(dictionaries)):
print(dictionaries[i]['First'])
*************************************************
please modity the above code to "Add an ‘if’ statement(s) to the loop in your solution in Exercise 7 to only show the full name if the first name is “Bob” or if the last name is “Kaur”.
arrow_forward
dictionaries = []
dictionaries.append({"First":"Bob", "Last":"Jones"})
dictionaries.append({"First":"Harpreet", "Last":"Kaur"})
dictionaries.append({"First":"Mohamad", "Last":"Argani"})
for i in range(0, len(dictionaries)): # Condition that's print the full name when Condition is True if(dictionaries[i]['First']=='Bob')or(dictionaries[i]['Last']=='Kaur'): print(dictionaries[i]['First']+" "+dictionaries[i]['Last'])
**********************************
please modify the code to use a while loop instead of a for loop
arrow_forward
java
Use Map data structure
Write a method that returns the frequency of each characters of a given String parameters
If the given String is null ,then return null
arrow_forward
An XHTML document that conforms to an XHTML specification is said to be valid.
+ + C D localhost8080/Form-Validation-Example/
Profile Employee
First Name David
Last Name waliams
First Name nost be between 3 nd 25 charncters
Lat Name must be between 3 and 25 characters
Sex
*Male OFemale Please select your gender
Date of burth 2107/1992
Please unput date of buth
javabycode@gmail.com Please input email
USA
Email
County
Please select your coustry
Submt.
Figure 1: Registration form
(a) Develop XHTML document for all the form controls displayed in the same sequence as shown in Figure 1.
(b) Once the applicant submit the application, your program must able to do data validation using JavaScript.
arrow_forward
A "generic" data structure cannot use a primitive type as its generic type.
O True
False
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
Bishops on a binge def safe_squares_bishops(n, bishops):
A generalized n-by-n chessboard has been taken over by some bishops, each represented as a tuple (row, column) of the row and the column of the square the bishop stands on. Same as in the earlier version of this problem with rampaging rooks, the rows and columns are numbered from 0 to n - 1. Unlike a chess rook whose moves are axis-aligned, a chess bishop covers all squares that are on the same diagonal with that bishop arbitrarily far into any of the four diagonal compass directions. Given the board size n and the list of bishops on that board, count the number of safe squares that are not covered by any bishop.
To determine whether two squares (r1, c1) and (r2, c2) are reachable from each other in one diagonal move, use abs(r1-r2) == abs(c1-c2) to check whether the horizontal distance between those squares equals their vertical distance, which is both necessary and sufficient for the squares to lie on the same diagonal. This…
arrow_forward
Computer Science
JAVASCRIPT .xlsx parser
I need to write a public class that reads an .xlsx file and returns an array of data in javascript. The array would be all of the data inside of the file.
The file itself is going to be inside of a folder(downloadedFIles) inside of my project. So the public class will need to account for that.
arrow_forward
Write the statement that declares and instantiates an array of type
double using the identifier temperatures that will hold 30 values.
Edit View Insert Format Tools Table
12pt v Paragraph v :
arrow_forward
ion C Lons
Employee
-id: int
-name String
- dob : Date
-staff : ArrayList
+setid(int): void
+getld() : int
+setName(String): void
+setDob(Date) : void
+getDob(): Date
+addStaff(Employee) : void
+getStaff() : ArrayList
arrow_forward
from typing import List, Tuple, Dict
from poetry_constants import (POEM_LINE, POEM, PHONEMES, PRONUNCIATION_DICT, POETRY_FORM_DESCRIPTION)
# ===================== Provided Helper Functions =====================
def transform_string(s: str) -> str: """Return a new string based on s in which all letters have been converted to uppercase and punctuation characters have been stripped from both ends. Inner punctuation is left untouched.
>>> transform_string('Birthday!!!') 'BIRTHDAY' >>> transform_string('"Quoted?"') 'QUOTED' >>> transform_string('To be? Or not to be?') 'TO BE? OR NOT TO BE' """
punctuation = """!"'`@$%^&_-+={}|\\/,;:.-?)([]<>*#\n\t\r""" result = s.upper().strip(punctuation) return result
def is_vowel_phoneme(phoneme: str) -> bool: """Return True if and only if phoneme is a vowel phoneme. That is, whether phoneme ends in a 0, 1, or 2.
Precondition:…
arrow_forward
Strings all_colors and updated_value are read from input. Perform the following tasks:
Split all_colors into tokens using a comma (',') as the separator and assign color_list with the result.
Replace the first element in color_list with updated_value.
arrow_forward
Programming Language: C++
I need the codes for arrayListType.h, main.cpp, myString.cpp, myString.h
arrow_forward
import Prelude hiding (lookup) data Exp = Num Int | Add Exp Exp | Sub Exp Exp | Mul Exp Exp | Div Exp Exp | Var String | Let String Exp Exp | App Exp Exp | Fnc String Exp deriving (Show) type Env = [(String, Val)] data Val = CVal Int | FnVal String Exp Env | Error String deriving (Show) {-Implement a function lookup:: Env -> String -> Val that looks up the value of a variable within a context. This function returns the value of the variable if found and returns an error otherwise. -} lookup :: Env -> String -> Val -- code here-- {- Implement a function eval:: Exp -> Env -> Val to evaluate an expression with an initial context and return a value. Errors occur in the following cases: (a) Left-hand-side of a function application is not a function. (b) Use an undefined variable (c) Arithmetic expression where operand is not a number -} eval :: Env-> Exp -> Val
-- code here --
arrow_forward
Domino cycledef domino_cycle(tiles):A single domino tile is represented as a two-tuple of its pip values, such as (2,5) or (6,6). This function should determine whether the given list of tiles forms a cycle so that each tile in the list ends with the exact same pip value that its successor tile starts with, the successor of the last tile being the first tile of the list since this is supposed to be a cycle instead of a chain. Return True if the given list of domino tiles form such a cycle, and False otherwise.
tiles
Expected result
[(3, 5), (5, 2), (2, 3)]
True
[(4, 4)]
True
[]
True
[(2, 6)]
False
[(5, 2), (2, 3), (4, 5)]
False
[(4, 3), (3, 1)]
False
arrow_forward
javascript
Define a function, myIncludes, that accepts two parameters: an array and a searchValue.
myIncludes should return true if the searchValue is an element in the array. Otherwise, myIncludes should return false.
example
myIncludes([10, 20, 30], 20); // => true myIncludes(['apples', 'bananas', 'citrus'], 'pears'); // => false
arrow_forward
Sets and Maps
A map is a container object that stores a collection of key/value pairs. It enables fast retrieval, deletion, and updating of the pair through the key. A map stores the values along with the keys. The keys are like indexes. In List, the indexes are integers. In Map, the keys can be any objects. A map cannot contain duplicate keys. Each key maps to one value. A key and its corresponding value form an entry stored in a map. There are three types of maps: HashMap, LinkedHashMap, and TreeMap. The common features of these maps are defined in the Map interface.
1.1 Using the Map interface knowledge, create a Java application in NetBeans that implements a HashMap and a LinkedHashMap. The application must do the following:
a. Add at least 5 elements to the HashMap
b. Print out all the elements in the HashMap including their keys
c. Find and print out the value of a specific index
d. Remove one of the elements from the HashMap
e. Print out the HashMap after removing the element
f.…
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
Create an application to keep track of a list of students and their grades in a data structures course using a binary search tree.• Create a class called student that contains 2 data members: name and grade and then create a binary search tree of objects of this class. Make sure you validate the grade (A through F, and ? for in-progress grades).• Create a menu that has the following options:o Add a student -- add the student if he/she is not already in the classo Remove a student -- display “Not Found” error message if the student is not in the class.o Update the grade -- display “Not Found” error message if the student is not in the class.o Display class roster
The program should use the binary tree definition.
Please list all main, cpp, and hpp files. There must be a Student class, with Student.hpp and Student.cpp files. Do not use structures.
arrow_forward
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
# define stemmer functionstemmer = SnowballStemmer('english')
# tokenise datatokeniser = TreebankWordTokenizer()tokens = tokeniser.tokenize(data)
# define lemmatiserlemmatizer = WordNetLemmatizer()
# bag of wordsdef bag_of_words_count(words, word_dict={}): """ this function takes in a list of words and returns a dictionary with each word as a key, and the value represents the number of times that word appeared""" for word in words: if word in word_dict.keys(): word_dict[word] += 1 else: word_dict[word] = 1 return word_dict
# remove stopwordstokens_less_stopwords = [word for word in tokens if word not in stopwords.words('english')]
# create bag of wordsbag_of_words = bag_of_words_count(tokens_less_stopwords)
Use the stemmer and lemmatizer functions (defined in the cells above) from the relevant library to find the stem and lemma of the nth word in the token list.
Function Specifications:
Should take a list as input and…
arrow_forward
•is Valid Phone Number(): ReturnsTrue if the provided phone number (represented as a string) is cor-rectly formatted, otherwiseFalse. To be considered correctly formatted, phone numbers must bewritten as###-###-####, where#is a digit between 0 and 9
.•validatePhoneBook(): A phone book is a list where each entry is a phone book record (represented asa dictionary; see below for more details). This function checks each phone book record in the phonebook for correctly formatted phone numbers.A phone book record is a dictionary which initially has two keys: the key"name"mapped to thecontact’s name (string) and the key"phone number"mapped to that contact’s phone number (alsoa string).validatePhoneBook()adds a new key"valid"to the record with the valueTrueif the phonenumber is formatted correctly, otherwiseFalse.
1. Write white-box and black-box tests for the function is ValidPhoneNumber(). You should do this with-out Python, either on paper, or in a simple document. Don’t worry about…
arrow_forward
Computer Science
JAVA #7 - program that reads the file named randomPeople.txt sort all the names alphabetically by last name write all the unique names to a file named namesList.txt , there should be no repeats
arrow_forward
1. Class
represents a dynamically resizable array-like data structure.
a. Stack
b. LinkedList
с. АrrayList
d. Array
2. A(n)
is a data structure with a fixed size and can be direct access its
elements.
a. Vector
b. ArrayList
c. LinkedList
d. Array
3. A(n)
is a data structure in which objects are inserted into and removed
from the same end.
a. LinkedList
b. ArrayList
c. Stack
d. Queue
4. A(n)
is a data structure in which objects are inserted into the end and
removed from the front.
a. LinkedList
b. ArrayList
c. Stack
d. Queue
arrow_forward
Create Code in C++ For String searching algorithms – Boyer-Moore and Aho-Corasick – to find the occurrences of a particular string within a large body of text. For example, you might take a webserver log file and use an appropriate data structure to track how many times each page has been accessed.
arrow_forward
Write the ternary-searchtrie (TST)thatrepresents a dictionary of the strings: “gnu”
“emacs”“gpg”“else”“gnome”“go”“eps2eps”“expr”“exec”“google”“elif” “email”“exit”“epstopdf”
arrow_forward
A tuple that contains elements is true.
True or false?
In Python.
arrow_forward
class Divisible:def div(minr, maxr, div1, div2):listdiv = []i = minrwhile i<maxr:if i%div1==0 and i%div2==0:listdiv.append(i)i+=1return listdiv
if __name__ == "__main__":min = int(input("Enter the min: "))max = int(input("Enter the max: "))div1 = int(input("Enter div1: "))div2 = int(input("Enter div2: "))d1 = Divisible.div(min,max,div1,div2)print(d1)
flowchart
arrow_forward
A c++ code that performs a search for a specific employee and returns the employee ID if found and 0 if not:
int findEmployeeById(Employee list[], int size, int myId)
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education
Related Questions
- Words with given shape def words_with_given_shape(words, shape): The shape of the given word of length n is a list of n - 1 integers, each one either -1, 0 or +1 to indicate whether the next letter following the letter in that position comes later (+1), is the same (0) or comes earlier (-1) in the alphabetical order of English letters. For example, the shape of the word 'hello' is [-1, +1, 0, +1], whereas the shape of 'world' is [-1, +1, -1, -1]. Find and return a list of all words that have that particular shape, listed in alphabetical order. Note that your function, same as all the other functions specified in this document that operate on lists of words, should not itself try to read the wordlist file words_sorted.txt, even when Python makes this possible with just a couple of lines of code. The tester script already reads in the entire wordlist and builds the list of words from there. Your function should use this given list of words without even caring which particular file it…arrow_forwardWords with given shape def words_with_given_shape(words, shape): The shape of the given word of length n is a list of n - 1 integers, each one either -1, 0 or +1 to indicate whether the next letter following the letter in that position comes later (+1), is the same (0) or comes earlier (-1) in the alphabetical order of English letters. For example, the shape of the word 'hello' is [-1, +1, 0, +1], whereas the shape of 'world' is [-1, +1, -1, -1]. Find and return a list of all words that have that particular shape, listed in alphabetical order. Note that your function, same as all the other functions speci0ied in this document that operate on lists of words, should not itself try to read the wordlist 0ile words_sorted.txt, even when Python makes this possible with just a couple of lines of code. The tester script already reads in the entire wordlist and builds the list of words from there. Your function should use this given list of words without even caring which particular 0ile it…arrow_forwardDoctor -signature:String -doctorID:int - medicine:Arraylist +Doctor(signature:String,doctorID:int) +PrescribeMedicine():void + salary () +checkRecords():void Medicine Pharmacist -medName:String -startTime:int -dosage :int -endTime:int -date_prescribed:int - medicine:Arraylist +Medicine(medName:String,-dosage :int,date_prescribed:int) +Pharmacist (startTime:int,endTime:int) +checkForConflict():double +confirm_prescription():String +getStartTime():int +getEndTime():int +setStartTime(time:int):void +setEndTime(time1:int).voidarrow_forward
- dictionaries = [] dictionaries.append({"First":"Bob", "Last":"Jones"}) dictionaries.append({"First":"Harpreet", "Last":"Kaur"}) dictionaries.append({"First":"Mohamad", "Last":"Argani"}) for i in range(0, len(dictionaries)): print(dictionaries[i]['First']) ************************************************* please modity the above code to "Add an ‘if’ statement(s) to the loop in your solution in Exercise 7 to only show the full name if the first name is “Bob” or if the last name is “Kaur”.arrow_forwarddictionaries = [] dictionaries.append({"First":"Bob", "Last":"Jones"}) dictionaries.append({"First":"Harpreet", "Last":"Kaur"}) dictionaries.append({"First":"Mohamad", "Last":"Argani"}) for i in range(0, len(dictionaries)): # Condition that's print the full name when Condition is True if(dictionaries[i]['First']=='Bob')or(dictionaries[i]['Last']=='Kaur'): print(dictionaries[i]['First']+" "+dictionaries[i]['Last']) ********************************** please modify the code to use a while loop instead of a for looparrow_forwardjava Use Map data structure Write a method that returns the frequency of each characters of a given String parameters If the given String is null ,then return nullarrow_forward
- An XHTML document that conforms to an XHTML specification is said to be valid. + + C D localhost8080/Form-Validation-Example/ Profile Employee First Name David Last Name waliams First Name nost be between 3 nd 25 charncters Lat Name must be between 3 and 25 characters Sex *Male OFemale Please select your gender Date of burth 2107/1992 Please unput date of buth javabycode@gmail.com Please input email USA Email County Please select your coustry Submt. Figure 1: Registration form (a) Develop XHTML document for all the form controls displayed in the same sequence as shown in Figure 1. (b) Once the applicant submit the application, your program must able to do data validation using JavaScript.arrow_forwardA "generic" data structure cannot use a primitive type as its generic type. O True Falsearrow_forwardclass 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
- Bishops on a binge def safe_squares_bishops(n, bishops): A generalized n-by-n chessboard has been taken over by some bishops, each represented as a tuple (row, column) of the row and the column of the square the bishop stands on. Same as in the earlier version of this problem with rampaging rooks, the rows and columns are numbered from 0 to n - 1. Unlike a chess rook whose moves are axis-aligned, a chess bishop covers all squares that are on the same diagonal with that bishop arbitrarily far into any of the four diagonal compass directions. Given the board size n and the list of bishops on that board, count the number of safe squares that are not covered by any bishop. To determine whether two squares (r1, c1) and (r2, c2) are reachable from each other in one diagonal move, use abs(r1-r2) == abs(c1-c2) to check whether the horizontal distance between those squares equals their vertical distance, which is both necessary and sufficient for the squares to lie on the same diagonal. This…arrow_forwardComputer Science JAVASCRIPT .xlsx parser I need to write a public class that reads an .xlsx file and returns an array of data in javascript. The array would be all of the data inside of the file. The file itself is going to be inside of a folder(downloadedFIles) inside of my project. So the public class will need to account for that.arrow_forwardWrite the statement that declares and instantiates an array of type double using the identifier temperatures that will hold 30 values. Edit View Insert Format Tools Table 12pt v Paragraph v :arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education