cs cribsheet 1
.docx
keyboard_arrow_up
School
University Of Georgia *
*We aren’t endorsed by this school
Course
2610
Subject
Computer Science
Date
Jul 3, 2024
Type
docx
Pages
3
Uploaded by MagistrateDolphinMaster1135
Beautiful Soup
with open(file) as f:
soup= BeautifulSoup(f, “html.parser)
soup.find(“tag”) : Returns a tag object of the first
instance soup.find_all(“tag”): Returns a list of tag objects of all
instances soup.find_all(“td”, {“class” : “J”}) : list of tag objects with specific tag methods:
tag.text: returns a string of the text displayed by a tag
tag[“attrib”] : access the tags attribute <tag attribute= “attribute value”>
zip(): pairs items of each iterable, creates tuple, new= list(zip(list1,list2)): [(1,’one’), (2,’two’)]
f-strings: print(f"{2} plus {3} equals {2 + 3}")
response = requests.get("https://someurl.com"): Sends a
request to the website - returns a response object .find(“the”) returns starting index of where the is found
NumPy
dtype="int32" -> makes int
array: a n-dimensional, fixed-size object that holds homogeneous data types
np.array([1,2,3], dtype = None)
np.zeros((row, column)) : array([[0., 0., 0.], [0., 0., 0.]])
np.ones(3)
array([1., 1., 1.])
np.full(shape, fill value) : np.full((3,3), 8) array([[8, 8, 8], [8, 8, 8], [8, 8, 8]])
np.arrange(start, stop(exclusive), step)
np.arange(4, 16, 3) -> array([4, 7, 10, 13])
np.linspace(start, stop, num=50, endpoint=True, dtype=float) , stop is inclusive when true np.linspace(0, 10, 5) array([ 0. , 2.5, 5. , 7.5, 10. ])
np.random.random((rows, columns)) , random floats in range [0, 1)
np.random.randint(low, high = None, size = None, dtype = int), gives one integer Index/Slice
arr = np.array([1,2,3,4,5]) -> arr[-3] -> 3
arr = np.array([[1, 2, 3],[4, 5, 6]]) > arr[1,2] > 6
arr[:,2:] all the rows, third column Vector Operations do not change original array arr = np.array([1, 2, 3]) > arr * 2 > array([2, 4, 6])
arr <= 2 array([True, True, False])
Masking arr[arr % 2 == 0] returns array of only even nums Bitwise &, |, ~
np.sum((arr % 2 == 0) & (arr < 13))
NaN
np.isnan()
gives T or F arr = np.array([-2, 1.5, np.nan, 2, -5], dtype = float)
arr[~np.isnan(arr)] -> array([-2., 1.5, 2., -5.])
Properties
.dtype
- returns the data type of the elements within an array
.ndim - returns the number of dimensions of an array
.size - returns the number of elements in an array
.shape - returns the shape in the order (rows, columns) of an array
.copy()
- returns a copy of an array that can be assigned to another variable. .fill(value)
- replaces all elements of an array with the specified value but does not return it
.reshape(rows, columns)
- returns an array with the new shape but does not change it
np.where
(condition, arr if true, arr if false) - returns a new array
.fill(value)
- replaces all elements of an array with the specified value but does not return it
.resize(rows,
columns)
- changes the shape of an array but does not return the array
.sort(axis = 0)
- Sorts in-place the array in ascending order np.concatenate
([arr1, arr2], axis =0)
Aggregate Methods:
.max() .mean() .sum() .min()
np.savetxt() np.loadtxt()
Pandas
: 2D size mutable s = aSeries(data, index=index)
selecting data:
by label s.loc[], by index s.iloc[] or s[]
masking s[s<3]
changing data: use loc or iloc
append new values use s.loc[“x”] =4
sort: s.sort_values(ascending = True)
ascending: small to large, abc order
delete: s.drop[“index”]
Data Frame
df= pd.DataFrame(data, index=, columns=)
selecting one column: df[“column”] returns series
selecting rows: use .loc or .iloc
df.loc[“row”].loc[“column”]
df.loc[“row”, “column”]
df.set_index("Course", inplace = True) -> don’t count course column as 1
st
column anymore masking: df[df[“avg GPA”] < 3]
Add/Replace Row Values
if the index doesn’t exist, it adds it df.loc[row, col] = 850 -> changes to 850
df.iloc[-1, :] = [100,3] last row, all col
add row df.loc[“isye20”]=[150,3.1]
Add/Replace Column
df.loc[:, “new”] = df[“new”] = df[“column”] >= 2
adds new col with T/F values Sorting : df.sort_values(by = "col", ascending = False, inplace = False)
Removing : df.drop(["col"], axis = 1) columns df.drop
(["CS2316", "CS1331"], axis = 0) rows
df.drop_duplicates
(subset = [“Course”]) , drops duplicates in column course df.nunique
(axis = 0) counts # of distinct elements in each column Reading/Writing x= pd.read_csv(“<path>file.csv”, index_col=0)
x.to_csv(“<path>fileout.csv”, index=True)
Missing Data
df.loc[“CS2603”] = [50, np.nan, 0]
CS2603 50.0 NaN 0.0
df.dropna()
: remove all rows that contain NaN
df.fillna(0): fill NaN with value
pd.isna(df) check is a value is NaN, gives T or F
Aggregates .mean() .sum() .min() .max() .count()
add column by taking mean of each row:
df[“new col”] = df.mean(axis=1).round(2)
add row for mean of each column
df.loc[“new row”]= df.mean(axis=0)
str method
df[“col”].str.contains(“A”, na= False)
Groupby
total= df.groupby(“country”)[“medals”].count()
counts # medals for each country country is the index, medals is the only column group by more than 1 column df.groupby([“country”, “gender”])[“medal”].count()
.agg() = when applying more than 1 aggregate on more than 1 column after groupby()
Concatenate
pd.concat(dfs, axis = 0) , joins them vertically
horizontal axis = 1
Plotting
line: series.plot(x=series.index, y=series.values)
series.plot(x=series.index, y=series.values, kind=
“bar”) kind = barh, hist, box
precent=series.value_counts()10*100
precent.plot(kind= “pie”)
Plotly: px.bar px.pie px.histogram px.box
fig= px.scatter(data, x = 'date', y = 'new_deaths', color = 'location') x= “column title”
fig = px.line(cases, x = 'date', y = 'new_cases', labels
= {'date': 'Day', 'new_cases': 'Number of New Cases'}, title = 'North America”)
fig.show()
*matplot lib library is easiest to use
OPP
class= blueprint for creating objects object= data structure created using a class as its blueprint instance – NO self
attribute- self.attribute define a class
class Dog:
instance attribute class Dog:
def __init__(self, name, people):
self.name=name
slef.age = age
class attributes class Dog:
numLegs= 4
def __eq__(self, other):
determines what makes things equal to e/o
return self.name == other.name and self.age == other.age def __lt__(self, other):
used to define sorting, called when < is used return self.age < other.age def __str__(self):
called when object is printed or cast to string
return f”{self.name} is {self.age} years old”
def __repr__(self):
called when object is printed return f”{self.name}”
Copy
list1= [1,2,3]
list1=list2 this does not copy the list, it simply copies the memory location list2.append(999) they both get 999 at the end
lista= [3,4,5]
listb= copy.copy(lista) #does not share memory, it's a newly constructed list object lista.append(98)
print(listb) #345
nested_lista= [[1,2],[3,4],[5,6]]
nested_listb = copy.copy(nested_lista)
nested_lista.append([1,1,1]) only list a changed
nested_lista= [[1,2],[3,4],[5,6]]
nested_listb = copy.copy(nested_lista)
nested_lista[0][0] = 9 #both changed bc nested list
nested_lista= [[1,2],[3,4],[5,6]]
nested_listb = copy.deepcopy(nested_lista
)
nested_lista[0][0] = 9 #only a changes
*if you assign an identified to an existing object an alias is created * copy.copy = copying references to the sublists
Inplace inplace = True changes original data frame
Fundamentals enumerate():
creates a tuple (index, value) for index, val in enumerate([“anna”, “emily”])
[(0, ‘anna’), (1, ‘Emily’)] returns enumerate object
zip():
pairs items of each iterable, creates tuple, returns zip object new= list(zip(list1,list2)): [(1,’one’), (2,’two’)]
lambda
: add= lambda a: a +10
returned value defined after colon
conditional: print(“even” if num%2 ==0 else “odd”)
list comprehension
: list= [expression for item in iterable if condition] list=[i**2 for i in range(10)] i**2 value is in list dictionary comp
: {key:val for item in iterable if x}
{i:i**2 for i in range(4)} {0:0, 1:1, 2:4, 3:9}
{lis[i]:lis2[i] for i in range range len(lis)}
{key:val for key,val in zip([1,2,3], “abc”)}
[:-1] everything but last column
Command line
mkdir: creates a directory cd: full path of current folder
ls: list content in currect directory cat: display content of file if __name__ == "__main__": -> will only print if running from command line. Executes only when you execute as a script Lists: Mutable, can iterate through Method
Usage
.append()
Adds an element at the end of the list
.extend()
Add the elements of a list (or any iterable) to the end of the current list
.index()
Returns the index of the first element with the specified value
.count()
Returns the number of elements with the specified value
.remove()
Removes the first item with the specified value
sorted() -> returns a new list of sorted values
sorted(alist, key=lambda x:x[1]) -> sorts by first index
.sort() -> mutates original list returns none
alist.sort(reverse= True) -> cannot assign this to anything or it returns none list.append(4) -> adds 4 to end of list
Tuples
Method
Usage
.count()
Returns the number of times a specified value occurs in a tuple
.index()
Searches the tuple for a specified value and returns the position of where it was found
immutable and cannot be sorted tup = (1,2,3) can iterate, index, slice strings immutable and iterable
.lower() .upper() .isdigit() .split() .replace()
string.split() -> makes string into a list by splitting at the spaces, returns a list
string.join() joins iterables on a string, returns string
“ “. join(alist) -> must have string before . f-strings: print(f"{2} plus {3} equals {2 + 3}")
dictionary dict= {90:”a”, 80:”b”} key:value
keys: for key in mydict.keys()
value: for val in mydict.values()
both: for key,val in mydict.items()
access value: dictionary[“key”]
updating: dictionary[“key”] = value -> it it already exists it gets updated
delete: del dict[‘key’]
sets: no indexing/slicing set={1,2”3”}
can add/remove, takes out duplicates Fundamentals
range(start, stop, step) stop is exclusive
indexing-> list[start:stop:step]
enumerate(): creates a tuple (index, value) for index, val in enumerate([“anna”, “emily”])
[(0, ‘anna’), (1, ‘Emily’)] returns enumerate object
zip(): pairs items of each iterable, creates tuple, returns zip object new= list(zip(list1,list2)): [(1,’one’), (2,’two’)]
lambda: add= lambda a: a +10
returned value defined after colon
conditional: print(“even” if num%2 ==0 else “odd”)
list comprehension: list= [expression for item in iterable if condition] list=[i**2 for i in range(10)] i**2 value is in list dictionary comp: {key:val for item in iterable if x}
{i:i**2 for i in range(4)} {0:0, 1:1, 2:4, 3:9}
{lis[i]:lis2[i] for i in range range len(lis)}
{key:val for key,val in zip([1,2,3], “abc”)}
File I/O -> list of strings
open file, readlines to create a list of all lines, strip newline char .strip(), split on delimiter .split(“,”)
with open(“file.txt”, “r” as f:
text= f.read()
f.read(): one long string read(:4) 4 char in data
f.readline(): string one line at a time
f.readlines(): list of every line as a string seek(): moves curser thru file fileObject.seek(offset)
writing: open file, write header, loop thru data writing each row as string w/ newline char at end
with open(“text.file”, “w”) as out:
out.write(“one\ntwo\n”) CSV file -> list of lists
each list represents a row of data
with open(“names.csv”,”r”) as f:
reader=csv.reader(f)
data =list(reader) >list of list
data[1:] eliminates header line with open(“files.csv”,”w”) as fout:
writer=csv.writer(fout) >creates writer object writer.writerow(data) > writes one new row writer.writerows(data) all rows in the file
with open(“csvFileName.csv”, “r”) as fin:
dictReader = csv.DictReader(fin)
listOfDicts = [dict(line) for line in dictReader]
with open(“csvFile.csv”, “w”) as fout:
dw = csv.DictWriter(fout, fieldnames = [‘key1’, ‘key2’, ...])
dw.writeheader()
JSON: web service responses double quotes for strings, true/false for Boolean, null instead None, dict keys must be string type load: JSON to python loads(): parses a string of JSON code and turns it into python dictionary load(): parses JSON file into a python dictionary
with open(“file.json”, “r”) as f:
dict=json.load(f)
dump: python to JSON
dumps(): takes python dict and returns JSON string
dump(): takes python dict and dumps into JSON file
with open(“fileout.json”, “w”) as f:
json.dump(output_dict, f) f= what you dump to
XML: formatted as element trees HTML: for data display
starts with <!doctype html> begins with <html> and ends with </html>
visible part is between <body> and </body>
headings are defined with the <h1> to <h6> tags
links with <a> tag
<ul> unordered list <ol> ordered list <li> list item
table defined with <table>
<tr> row <th> table header <td> data cell <img src = “xx.jpg”>
API: request module import requests
: Imports the requests module response = requests.get("https://someurl.com"): Sends a
request to the website - returns a response object response.status_code
: The status code of the request (an
attribute) gives an integer response.text
: The text that was retrieved by the get request (an attribute) response.json(): Returns the text that was retrieved converted into python (only works if the text was stored in the json format)
print(response) =status code only
print(response.text[:500])= 1
st
500 characters response = requests.
post
(“
https://example.com
”) -> sends info to a website
200: successful request, 404: url not found, 500: internal error, 401/3: unauthorized Escape Sequences : not printable character
\n = newline \t= tab \\=backsplash
RegEx
To make non greedy put
?
after the + or *
[A-Z][a-z]* capital letter followed by zero or more lower case
print(re.findall(".+C",text)) start with one or more character and end with a capital letter C
Meta character
meaning
.
Matches any character
\
Escape special/meta characters
|
Or operator
^
Match at beginning of string/line. Represents “not” in a character class
$
Match at end of string/line
*
Match 0 or more of the
preceding regex
+
Match 1 or more of the preceding regex
?
Match 0 or 1 of the preceding regex
{}
Bounded repetition
[]
Create a character class
()
Capture group within the matched substring
Character class
What it matches
[a-z]
Any lowercase letter
[A-Z]
Any uppercase letter
[a-zA-Z]
Any letter
[^A-Z]
Anything except uppercase letters
Predefined character class
What it matches
\d
Any digit, equivalent to
[0-9]
\D
Any non-digit, equivalent to [^0-9]
\s
Any whitespace char,
equal to [ \t\n\r\f\v]
\S
Any non-whitespace char, equal to [^\t\n\r\f\
v]
\w
Any alphanumeric char,
equal to [a-zA-Z0-9_]
\W
Any non alphanumeric char, equal to [^a-zA-
Z0-9_]
re
.match
(
‘regEx ’,
a_string
): Checks if the beginning of a_string matches the pattern. returns a Match
object. Otherwise, it returns None
.
re
.search
(
‘regEx ’, a_string
): Checks if any part of a_string matches the pattern. returns a Match
object
corresponding to the first matching part
re
.findall
(
‘regEx ’, a_string
): Checks a_string for all non-overlapping
matches to the regex supplied and returns a list
of the strings that match
re
.sub
(r
‘regEx ’, new_string
, a_string
): Checks a_string for all matches to the regex and returns a string
with each match replaced by new_string
method
What it does
match_object
.start()
Returns the index of the start of the string that matched match_object
.end()
Returns the index after the end of the string that matched
match_object
.group()
Returns the string
that matched match_object
.span()
Returns a tuple
of the starting and ending indices of the string matched by the regex
*Ending index is exclusive
SQL: structured query language Schema - a collection of related tables and constructs
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
class DoublyLinkedList: def __init__(self): self.head = None
def is_empty(self): if self.head == None: return True else: return False
def enqueue_front(self, data): new_node = Node(data) new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node
def enqueue_rear(self, data): new_node = Node(data) new_node.next = None if self.head is None: new_node.prev = None self.head = new_node return last = self.head while(last.next is not None): last = last.next last.next = new_node new_node.prev = last return
def peek(self): return self.head.data
def dequeue_front(self): if self.head is None: return temp = self.head self.head = self.head.next self.head.prev = None return temp.data…
arrow_forward
public void OnSend(View v){
String phoneNumber = number.getText().toString();
String smsmessage = message.getText().toString();
if(phoneNumber == null || phoneNumber.length() == 0 || smsmessage == null || smsmessage.length() == 0){
return;
}
if(checkPermission(Manifest.permission.SEND_SMS)){
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, smsmessage, null, null);
Toast.makeText(this, "Message sent", Toast.LENGTH_SHORT).show();
}
Question 2:
Explain the following code:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
XFragment xfragment = new XFragment();
ft.add(R.id.Main_fragment, xfragment);…
arrow_forward
Using Java programming language create a linked list named Cars with four elements: "SUV cars", "Pickup cars", "Sport cars", and "Sedan cars".
Apply the following activities on the code you’ve created and provide screen shot of each result:
Add a new element “Classic car” at the beginning of the linked list using iterator.
Add a new element “Economic cars" after the element "Sedan Cars" using iterator.
Print the LinkedList backward from the last element to the first element using hasPrevious()
arrow_forward
Question Completion Status:
QUESTION 1
Write a Java Program to do the following:
Create an LinkedList object and store 5 different Float objects.
Using a Listlterator do the following:
Compute the average of all numbers.
Attach File
Browse My Computer
lck Sape and Submit to save and submit Clhck Save Al Answers to save all answers.
arrow_forward
In Java
MailBox- client:String- emails: Email[]- actualSize: int+ Mailbox()+ Mailbox(client:String)+ getClient(): String+ getEmail(int index): Email+ getActualSize(): int+ addEmail(email: Email): void+ sortEmailsByDate(): void+ findEmail(year:int: Email+ countUrgent():int+ toString(): String
Write java code for all the methods shown on the class diagram. Below arethe details needed for the different methods:a. The default constructor will assign the client a default name (any value ofyour choice). Keep in mind that a single mailbox (e.g., gmail) can handle amaximum of 15 emails, but it can hold less, which is the actual size of theemails array. So, the constructor should instantiate the emails arrayinstance variable by creating an array of size 15. It should also set theactualSize variable to 0.b. The MailBox (String client) constructor should call the default constructorusing chaining. It should then initialize the client variable using the clientparameter.c. The toString method…
arrow_forward
function removeErrMsgs() {
var errMessages = document.getElementsByClassName('msg');for (let msg of errMessages) {msg.innerHTML = "";}}function validateValues() {var toBeReturned = true;removeErrMsgs();var fname = document.getElementById("fname").value;if (fname.length > 30) {document.getElementsByClassName('msg')[0].innerHTML = "First name can not be longer than 30 characters";toBeReturned = false;}
var lname = document.getElementById("lname").value;if (lname.length > 30) {document.getElementsByClassName('msg')[1].innerHTML = "Last name can not be longer than 30 characters";toBeReturned = false;}
var phone = document.getElementById('num').value;if (phone.length > 8) {document.getElementsByClassName('msg')[2].innerHTML = "Phone number can not be greater than 8 numbers";toBeReturned = false;}
var items = document.getElementById('items').value;if (items > 4 || items < 2) {document.getElementsByClassName('msg')[3].innerHTML = "Item numbers should be between 1 and…
arrow_forward
this is an android app with android studio .
package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ListView;public class PlayerActivity2 extends AppCompatActivity {ListView simpleList;String SerialNo[] = {"1", "2", "3", "4", "5", "6","7","8","9","10"};int flags[] = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5, R.drawable.image6, R.drawable.image7, R.drawable.image8, R.drawable.image9, R.drawable.image10};String Names[] = {"mmm", "nnn", "aaa.", "bbb", "ccc", "ddd","eee jk"," ijk","Virgil jk","gil jklk"};String Score[] = {"1", "2","3", "5", "4", "3","5","5","5","5"};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity2);simpleList = (ListView)findViewById(R.id.simpleListView);//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_listview,…
arrow_forward
Lab 20 Removing the first element in a list
Start this lab with the code listed below. The LinkedList class defines the rudiments of the code needed to build a linked list of Nodes. Complete the code for the removeFirst method, which should remove and return the first element in the linked list. Throw a NoSuchElementException if the method is invoked on an empty list. Use the LinkedListRunner class’s main method to test your code.
Java language
arrow_forward
Don't copy from anywhere... please fast... typed answer
Assignment: Linked List of Students
You have been tasked with implementing a program in Java that uses a linked list to store and manage a list of students in a class. Each student should have a name and a grade.
Your program should include the following classes:
Student: Represents a student in the class. Each student should have a name and a grade.
Node: Represents a node in the linked list. Each node should store a reference to a student and a reference to the next node in the list.
LinkedList: Represents the linked list itself. Each linked list should have a reference to the first node in the list.
Your task is to implement these classes using a linked list and demonstrate their functionality by creating a console-based interface for users to interact with the system.
Your program should allow users to:
Add a new student to the class at the end of the list.
View information about a student, including their name and grade.…
arrow_forward
PLEASE REFER TO THE IMAGES FOR INSTRUCTIONS
PLEASE USE STARTER CODE - CODE IN PYTHON3
### starter code
import random
def spider_web(web_map, starting_place, destination):
pass
def spider_web_rec(web_map, starting_place, destination, visited):
pass
def make_spider_web(num_nodes, seed=0):
if seed:
random.seed(seed)
web_map = {}
for i in range(1, num_nodes + 1):
web_map[f'Node {i}'] = []
for i in range(1, num_nodes + 1):
sample = random.sample(list(range(i, num_nodes + 1)), random.randint(1, num_nodes - i + 1))
print('sample', i, sample)
for x in sample:
if i != x:
web_map[f'Node {i}'].append(f'Node {x}')
web_map[f'Node {x}'].append(f'Node {i}')
return web_map
if __name__ == '__main__':
num_nodes, seed = [int(x) for x in input('Input num_nodes, seed: ').split(',')]
the_web = make_spider_web(num_nodes, seed)
print(spider_web(the_web, 'Node 1',…
arrow_forward
Java
arrow_forward
Assign negativeCntr with the number of negative values in the linked list.
Thanks.
// ===== Code from file IntNode.java =====public class IntNode {private int dataVal;private IntNode nextNodePtr;
public IntNode(int dataInit, IntNode nextLoc) {this.dataVal = dataInit;this.nextNodePtr = nextLoc;}
public IntNode(int dataInit) {this.dataVal = dataInit;this.nextNodePtr = null;}
/* Insert node after this node.* Before: this -- next* After: this -- node -- next*/public void insertAfter(IntNode nodePtr) {IntNode tmpNext;
tmpNext = this.nextNodePtr; // Remember nextthis.nextNodePtr = nodePtr; // this -- node -- ?nodePtr.nextNodePtr = tmpNext; // this -- node -- next}
// Grab location pointed by nextNodePtrpublic IntNode getNext() {return this.nextNodePtr;}public int getDataVal() {return this.dataVal;}}// ===== end =====
// ===== Code from file CustomLinkedList.java =====import java.util.Random;
public class CustomLinkedList {public static void main(String[] args) {Random randGen = new…
arrow_forward
Python Code:
class Node: def __init__(self, initial_data): self.data = initial_data self.next = None
def __str__(self): return str(self.data)
class LinkedList: def __init__(self): self.head = None self.tail = None
def append(self, new_node): if self.head == None: self.head = new_node self.tail = new_node else: self.tail.next = new_node self.tail = new_node def Generate(self,num_nodes): # Your code goes here
def printList(self): # Your code goes here def swap(self): # Your code goes here if __name__ == '__main__': LL = LinkedList() num_nodes = int(input()) LL.Generate(num_nodes) LL.swap() LL.printList()
arrow_forward
Python Code:
class Node: def __init__(self, initial_data): self.data = initial_data self.next = None
def __str__(self): return str(self.data)
class LinkedList: def __init__(self): self.head = None self.tail = None
def append(self, new_node): if self.head == None: self.head = new_node self.tail = new_node else: self.tail.next = new_node self.tail = new_node def Generate(self,num_nodes): # Your code goes here
def printList(self): # Your code goes here def swap(self): # Your code goes here if __name__ == '__main__': LL = LinkedList() num_nodes = int(input()) LL.Generate(num_nodes) LL.swap() LL.printList()
*****NOTE*******
Consider the following example to get an idea of how the output of the above program should be
Example:
Input
5 Morning Noon Afternoon Evening Night…
arrow_forward
1. The following interfaces are part of the Java Collections Framework except?
a. SortedListb. SortedMapc. Setd. ArrayListe. HashSet
2. Which assertion about the HashMap class is not true?
a. HashMap class is not synchronized.b. HashMap class extends AbstractMap and implements Map interface.c. HashMap maintain order of its element.d. HashMap uses a hashtable to store the map.
arrow_forward
Objective:
This activity has the purpose of helping students to design proper hashing strategies. (Objective 3).
Students Instructions:
After studying this module, write the answer to the following programming assignments in a text file and
submit them as an attached Word doc or PDF through the provided link in Blackboard. The deadline for
submitting this assignment is indicated on "Tools", which is located in "Calendar" in the "Blackboard"
platform. You will have two (2) attempt to send your answers by Assignment link before the deadline and
the last submission would be considered as your final solution. This exercise has
Implement a dictionary by using hashing and separate chaining. Question:
arrow_forward
2 LinkedList remove and iterator
Your class ICS211LinkedList.java must have the exact same class variables as LinkedList.java, that is, head, tail, and size. You must also keep the checkInvariants() method, and call it at the beginning and end of both of the two public
methods (remove and iterator) you must add in creating your ICS211LinkedList class.
2.1 LinkedList remove
Implement the E remove(int index) method defined by the java.util.List interface.
Removing a node from a linked list requires access to the node preceding the node to be removed. This means you must have a loop which starts at the head and follow the links until you are at the correct index.
If the index is size-1, which is the last valid index of the list, remember to update the tail reference.
If the index is 0, this is a special case that updates the head reference. If the list only has one element, the tail reference must also be updated.
Make sure your code works correctly for
• an empty list (must throw…
arrow_forward
Assignment Apex: Apply SOQL on Contact to get the Contacts for Account those we got from 1st SOQL:
Add a new method:
Name: getContactInformationForSpecificAccount
Return Type: Map>
args: List
arrow_forward
Design a class that acquires the JSON string from question #1 and converts it to a class data member dictionary. Your class produces data sorted by key or value but not both. Provide searching by key capabilities to your class. Provide string functionality to convert the dictionary back into a JSON string.
question #1:
import requestsfrom bs4 import BeautifulSoupimport json
class WebScraping: def __init__(self,url): self.url = url self.response = requests.get(self.url) self.soup = BeautifulSoup(self.response.text, 'html.parser') def extract_data(self): data = [] lines = self.response.text.splitlines()[57:] # Skip the first 57 lines for line in lines: if line.startswith('#'): # Skip comment lines continue values = line.split() row = { 'year': int(values[0]), 'month': int(values[1]), 'decimal_date': float(values[2]),…
arrow_forward
A linked list is built in this lab. Make sure to keep track of the head node.
ContactNode.java - Class definition
ContactList.java - Contains main() method
(2) Build the ContactNode class per the following specifications:
Private fields
String contactName
String contactPhoneNumber
ContactNode nextNodePtr
Constructor with parameters for name followed by phone number
Public member methods
getName() - Accessor
getPhoneNumber() - Accessor
insertAfter()
getNext() - Accessor
printContactNode()
Ex: If the name is Roxanne Hughes and the phone number is 443-555-2864, printContactNode() outputs:
Name: Roxanne Hughes Phone number: 443-555-2864
(3) Define main() to read the name and phone number for three contacts and output each contact. Create three ContactNodes and use the nodes to build a linked list.
Ex: If the input is:
Roxanne Hughes 443-555-2864 Juan Alberto Jr. 410-555-9385 Rachel Phillips 310-555-6610
the output is:
Person 1: Roxanne Hughes, 443-555-2864 Person 2: Juan…
arrow_forward
Create a flow chart using this code:
#class for nodesclass Node:def __init__(self, data=None, link=None):self.data=dataself.link=linkdef __str__(self):return str(self.data)
#class for Linked listclass LinearList:def __init__(self, start=None,nodecount=0):self.start=startself.nodecount=nodecount #stores number of nodes in linked listdef addBegNode(self, value=None):#Adding nodes at beginningnode=Node(value)node.link=self.startself.start=nodeself.nodecount=self.nodecount+1
def printList(self):#traverse add display nodesptr=self.startwhile ptr:print(ptr)ptr=ptr.linkprint()def bubblesort(self):for lst in range(self.nodecount-1): #for controlling passes of Bubble Sortcurrent=self.startnxt=current.linkprevious=Nonewhile nxt: #Comparisons in passesif current.data>nxt.data:if previous==None:previous=current.linknxt=nxt.linkprevious.link=currentcurrent.link=nxtself.start=previouselse: temp=nxtnxt=nxt.linkprevious.link=current.linkprevious=temptemp.link=currentcurrent.link=nxtelse:…
arrow_forward
The compareTo method. First you compare this.ticker which is a String, then if they are the same then you compare by the this.purchasePrice which is a double
hashCode
public int hashCode()
The hashCode method using the Code-> Generate equals and hashCode with no changes
Overrides:
hashCode in class Object
Returns:
int Representing the hashCode
compareTo
public int compareTo(Stock another)
The compareTo method not auto generated Compares first by ticker and if the tickers are the same secondarily compares by price
Specified by:
compareTo" in interface Comparable<stock>
Parameters:
another - the object to be compared.
Returns:
int Representing order
Throws:
IllegalArgumentException"- if another is null.
arrow_forward
Lab 20 Removing the first element in a list
Start this lab with the code listed below. The LinkedList class defines the rudiments of the code
needed to build a linked list of Nodes. Complete the code for the removeFirst method, which should
remove and return the first element in the linked list. Throw a NoSuchElementException if the
method is invoked on an empty list. Use the LinkedListRunner class's main method to test your
code.
import java.util.NoSuchElementException;
public class LinkedList
private Node first;
public LinkedList () { first = null; }
public Object getFirst ()
if (first == null) { throw new NoSuchElementException (); }
return first.data;
}
public void addFirst (Object element)
Node aNode - new Node () ;
aNode.data - element;
aNode.next = first;
first = aNode;
public Object removeFirst ()
// put your code here
}
public String tostring ().
String temp = "";
Node current = first;
while (current != nul1)
temp = temp + current.data.toString () + '\n';
current =…
arrow_forward
Lab 20 Removing the first element in a list
Start this lab with the code listed below. The LinkedList class defines the rudiments of the code needed to build a linked list of Nodes. Complete the code for the removeFirst method, which should remove and return the first element in the linked list. Throw a NoSuchElementException if the method is invoked on an empty list. Use the LinkedListRunner class’s main method to test your code.
import java.util.NoSuchElementException;public class LinkedList{ private Node first; public LinkedList() { first = null; } public Object getFirst() { if (first == null) { throw new NoSuchElementException(); } return first.data; } public void addFirst(Object element) { Node aNode = new Node(); aNode.data = element; aNode.next = first; first = aNode; } public Object removeFirst() { // put your code here } public String toString() { String temp = ""; Node current = first;…
arrow_forward
Estimated Completion Time: 2-3 minutes
Which of the following situations will lead to an object being aliased? Select all that apply.
n Assigning a list to L1, then assigning L1 to L2
n Assigning a string to S1, then assigning the result of slicing S1 (i.e. S1[:]) to S2
n Assigning a list to L1, then assigning the result of a copy() method on L1 to L2
n Assigning a list to L1, then assigning the result of slicing L1 (i.e., L1[:]) to L2
n Assigning a string to S1, then assigning the result of a replace() method on S1 to S2
n Assigning a list to L1, then using L1 in a function call with header "def foo(x: List) -> List"
n Assigning a string to S1, then using S1 in a function call with header "def foo(x: str) -> None"
n Assigning two lists to L1 and L2, then assigning the result of adding them to L3
arrow_forward
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Empty Doubly Linked Listclass DoublyLinkedList: def __init__(self): self.head = None
def append(self, new_data): if self.head == None: self.head = new_data self.tail = new_data else: self.tail.next = new_data new_data.prev = self.tail self.tail = new_data def printList(self): if(self.head == None): print('Empty!') else: node = self.head while(node is not None): print(node.data), node = node.next
def remove(self, current_node): successor_node = current_node.next predecessor_node = current_node.prev
if successor_node is not None: successor_node.prev = predecessor_node
if predecessor_node is not None: predecessor_node.next = successor_node
if…
arrow_forward
QUESTION 11
You need to store a list of messages so that the most recently-added message is always first. Should you use an ArrayList or a
LinkedList?
It doesn't matter in this case.
Linked List
ArrayList
QUESTION 12
You need to store a collection of employees in a big company so that you can look them up by name. Should you use an List,
a Map, or or a Set?
O It doesn't matter in this case.
List
Set
Map
arrow_forward
>
>
©Citizen
©Company
model
model
• licenseNo: String
e location: String
expiryDate: Date
Company(int, String,String,String,Date)
• getLicenseNo() String
• setLicenseNo(String).void
• getLocation() String
• setlocation(String) void
• getExpiryDate().Date
• setExpiryDate(Date).void
• toString() String
nationalNo: int
- bDate: Date
nationality: String
FCitizen(int,String,int,Date,String)
• getNationalNo() int
• setNationalNo(it) void
• getbDate():Date
• setbDate(Date):void
• getNationality() String
• setNationality(String) void
toString() String
>
©Customer
model
-bookings
• book
• cance
id: int
name: String
FCustomer(int,String)
• removeBookedObject(int).void
• getBookings() ArrayList
• setBookings(ArrayList)void
• getid()int
• setid(int).void
• getName():String
• setName(String) void
• getTotalPayment() double
toString() String
-booki
-customers
<
arrow_forward
For any element in keysList with a value greater than 100, print the corresponding value in itemsList, followed by a space. Ex: If keysList = {42, 105, 101, 100} and itemsList = {10, 20, 30, 40}, print:20 30 Since keysList.at(1) and keysList.at(2) have values greater than 100, the value of itemsList.at(1) and itemsList.at(2) are printed.
#include <iostream>#include <vector>using namespace std;
int main() { const int SIZE_LIST = 4; vector<int> keysList(SIZE_LIST); vector<int> itemsList(SIZE_LIST); unsigned int i;
for (i = 0; i < keysList.size(); ++i) { cin >> keysList.at(i); }
for (i = 0; i < itemsList.size(); ++i) { cin >> itemsList.at(i); }
/* Your solution goes here */
cout << endl;
return 0;}
arrow_forward
For any element in keysList with a value greater than 100, print the corresponding value in itemsList, followed by a space. Ex: If keysList = {42, 105, 101, 100} and itemsList = {10, 20, 30, 40}, print: 20 30
Since keysList.at(1) and keysList.at(2) have values greater than 100, the value of itemsList.at(1) and itemsList.at(2) are printed.
#include <iostream>#include <vector>using namespace std;
int main() {const int SIZE_LIST = 4;vector<int> keysList(SIZE_LIST);vector<int> itemsList(SIZE_LIST);unsigned int i;
for (i = 0; i < keysList.size(); ++i) {cin >> keysList.at(i);}
for (i = 0; i < itemsList.size(); ++i) {cin >> itemsList.at(i);}
/* Your solution goes here */
cout << endl;
return 0;}
Please help me with this problem using c++.
arrow_forward
Exercise 2:
Create a Book class; where:
lo Each book contains the following information: book title, book Author name, barcode (as
long integers) and book topic.
6 Implement an appropriate constructor(s) and all necessary get/set methods.
Test Book class:
lo Create different book objects (at least 5 books) and store them in a LinkedList sorted by
book barcode value. Generate a unique random integer value for the barcode.
O Iterate through the LinkedList and print out the books' details
o Create a second LinkedList object containing a copy of the above LinkedList, but in
reverse order
arrow_forward
A map is a container that stores a collection of ordered pairs, each pair consists of a key and a value, <key, value>. Keys must be unique. Values need not be unique, so several keys can map to the same values. The pairs in the map are sorted based on keys.
Group of answer choices
True
False
arrow_forward
In Java Language
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
- class DoublyLinkedList: def __init__(self): self.head = None def is_empty(self): if self.head == None: return True else: return False def enqueue_front(self, data): new_node = Node(data) new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node def enqueue_rear(self, data): new_node = Node(data) new_node.next = None if self.head is None: new_node.prev = None self.head = new_node return last = self.head while(last.next is not None): last = last.next last.next = new_node new_node.prev = last return def peek(self): return self.head.data def dequeue_front(self): if self.head is None: return temp = self.head self.head = self.head.next self.head.prev = None return temp.data…arrow_forwardpublic void OnSend(View v){ String phoneNumber = number.getText().toString(); String smsmessage = message.getText().toString(); if(phoneNumber == null || phoneNumber.length() == 0 || smsmessage == null || smsmessage.length() == 0){ return; } if(checkPermission(Manifest.permission.SEND_SMS)){ SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNumber, null, smsmessage, null, null); Toast.makeText(this, "Message sent", Toast.LENGTH_SHORT).show(); } Question 2: Explain the following code: button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); XFragment xfragment = new XFragment(); ft.add(R.id.Main_fragment, xfragment);…arrow_forwardUsing Java programming language create a linked list named Cars with four elements: "SUV cars", "Pickup cars", "Sport cars", and "Sedan cars". Apply the following activities on the code you’ve created and provide screen shot of each result: Add a new element “Classic car” at the beginning of the linked list using iterator. Add a new element “Economic cars" after the element "Sedan Cars" using iterator. Print the LinkedList backward from the last element to the first element using hasPrevious()arrow_forward
- Question Completion Status: QUESTION 1 Write a Java Program to do the following: Create an LinkedList object and store 5 different Float objects. Using a Listlterator do the following: Compute the average of all numbers. Attach File Browse My Computer lck Sape and Submit to save and submit Clhck Save Al Answers to save all answers.arrow_forwardIn Java MailBox- client:String- emails: Email[]- actualSize: int+ Mailbox()+ Mailbox(client:String)+ getClient(): String+ getEmail(int index): Email+ getActualSize(): int+ addEmail(email: Email): void+ sortEmailsByDate(): void+ findEmail(year:int: Email+ countUrgent():int+ toString(): String Write java code for all the methods shown on the class diagram. Below arethe details needed for the different methods:a. The default constructor will assign the client a default name (any value ofyour choice). Keep in mind that a single mailbox (e.g., gmail) can handle amaximum of 15 emails, but it can hold less, which is the actual size of theemails array. So, the constructor should instantiate the emails arrayinstance variable by creating an array of size 15. It should also set theactualSize variable to 0.b. The MailBox (String client) constructor should call the default constructorusing chaining. It should then initialize the client variable using the clientparameter.c. The toString method…arrow_forwardfunction removeErrMsgs() { var errMessages = document.getElementsByClassName('msg');for (let msg of errMessages) {msg.innerHTML = "";}}function validateValues() {var toBeReturned = true;removeErrMsgs();var fname = document.getElementById("fname").value;if (fname.length > 30) {document.getElementsByClassName('msg')[0].innerHTML = "First name can not be longer than 30 characters";toBeReturned = false;} var lname = document.getElementById("lname").value;if (lname.length > 30) {document.getElementsByClassName('msg')[1].innerHTML = "Last name can not be longer than 30 characters";toBeReturned = false;} var phone = document.getElementById('num').value;if (phone.length > 8) {document.getElementsByClassName('msg')[2].innerHTML = "Phone number can not be greater than 8 numbers";toBeReturned = false;} var items = document.getElementById('items').value;if (items > 4 || items < 2) {document.getElementsByClassName('msg')[3].innerHTML = "Item numbers should be between 1 and…arrow_forward
- this is an android app with android studio . package com.example.myapplication;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ListView;public class PlayerActivity2 extends AppCompatActivity {ListView simpleList;String SerialNo[] = {"1", "2", "3", "4", "5", "6","7","8","9","10"};int flags[] = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5, R.drawable.image6, R.drawable.image7, R.drawable.image8, R.drawable.image9, R.drawable.image10};String Names[] = {"mmm", "nnn", "aaa.", "bbb", "ccc", "ddd","eee jk"," ijk","Virgil jk","gil jklk"};String Score[] = {"1", "2","3", "5", "4", "3","5","5","5","5"};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity2);simpleList = (ListView)findViewById(R.id.simpleListView);//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_listview,…arrow_forwardLab 20 Removing the first element in a list Start this lab with the code listed below. The LinkedList class defines the rudiments of the code needed to build a linked list of Nodes. Complete the code for the removeFirst method, which should remove and return the first element in the linked list. Throw a NoSuchElementException if the method is invoked on an empty list. Use the LinkedListRunner class’s main method to test your code. Java languagearrow_forwardDon't copy from anywhere... please fast... typed answer Assignment: Linked List of Students You have been tasked with implementing a program in Java that uses a linked list to store and manage a list of students in a class. Each student should have a name and a grade. Your program should include the following classes: Student: Represents a student in the class. Each student should have a name and a grade. Node: Represents a node in the linked list. Each node should store a reference to a student and a reference to the next node in the list. LinkedList: Represents the linked list itself. Each linked list should have a reference to the first node in the list. Your task is to implement these classes using a linked list and demonstrate their functionality by creating a console-based interface for users to interact with the system. Your program should allow users to: Add a new student to the class at the end of the list. View information about a student, including their name and grade.…arrow_forward
- PLEASE REFER TO THE IMAGES FOR INSTRUCTIONS PLEASE USE STARTER CODE - CODE IN PYTHON3 ### starter code import random def spider_web(web_map, starting_place, destination): pass def spider_web_rec(web_map, starting_place, destination, visited): pass def make_spider_web(num_nodes, seed=0): if seed: random.seed(seed) web_map = {} for i in range(1, num_nodes + 1): web_map[f'Node {i}'] = [] for i in range(1, num_nodes + 1): sample = random.sample(list(range(i, num_nodes + 1)), random.randint(1, num_nodes - i + 1)) print('sample', i, sample) for x in sample: if i != x: web_map[f'Node {i}'].append(f'Node {x}') web_map[f'Node {x}'].append(f'Node {i}') return web_map if __name__ == '__main__': num_nodes, seed = [int(x) for x in input('Input num_nodes, seed: ').split(',')] the_web = make_spider_web(num_nodes, seed) print(spider_web(the_web, 'Node 1',…arrow_forwardJavaarrow_forwardAssign negativeCntr with the number of negative values in the linked list. Thanks. // ===== Code from file IntNode.java =====public class IntNode {private int dataVal;private IntNode nextNodePtr; public IntNode(int dataInit, IntNode nextLoc) {this.dataVal = dataInit;this.nextNodePtr = nextLoc;} public IntNode(int dataInit) {this.dataVal = dataInit;this.nextNodePtr = null;} /* Insert node after this node.* Before: this -- next* After: this -- node -- next*/public void insertAfter(IntNode nodePtr) {IntNode tmpNext; tmpNext = this.nextNodePtr; // Remember nextthis.nextNodePtr = nodePtr; // this -- node -- ?nodePtr.nextNodePtr = tmpNext; // this -- node -- next} // Grab location pointed by nextNodePtrpublic IntNode getNext() {return this.nextNodePtr;}public int getDataVal() {return this.dataVal;}}// ===== end ===== // ===== Code from file CustomLinkedList.java =====import java.util.Random; public class CustomLinkedList {public static void main(String[] args) {Random randGen = new…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