ITC - 740
Why is the code below often added to a Python program file? if __name__ == "__main__": main()
It executes the main() function only if this file is executed as the main program.
If you want to interact with R and other languages in an entirely online format, which environment works best?
Microsoft Azure Notebooks
Choosing two variables from a data frame, how can you look at the correlation of those variables?
cor.test(df$variable, df$variable)
Which alternative code is logically equivalent to the code below? max=x if (x>y) else y
max=y if (x>y): max=x
Which function adds new variables and preserves existing ones?
mutate()
Which data types are double precision by default?
numerical variables
While _____ checks whether a path exists, _____ checks whether a path is a file.
path.exists(); path.isfile()
If you are using a .csv file, how can you easily import your data into R?
the read_csv() command
When can you use a matrix?
When you have data that is all of the same type.
What value should be returned by the URL request getcode() call to confirm that the specified site can be properly connected to?
200
For the HTML file below, how many times will the handle_starttag() and handle_endtag() methods of the Python-provided HTML parser class be called? <div class="sidebar"> <img src="pic.gif" height="50" width="100" /> <button type="button" id="btn-submit">Submit</button> </div>
3 and 3
If you want to sort packages into topics on the R project website, what should you select?
CRAN Task Views
When viewing datasets that come in the datasets package, you are given their name and a few words to describe them. If you want more information, what can you select?
Index
When installing RStudio for this course, which version should you download?
RStudio Desktop
How can the following code be rewritten using the piping function? round(prop.table(margin.table(UCBAdmissions, 3)), 2) * 100
UCBAdmissions %>% margin.table(3) %>% prop.table %>% round(2) %>% multiply_by(100)
How can you generate an array so it creates the following? , , 1 [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 4 7 10 13 16 [2,] 2 5 8 11 14 17 [3,] 3 6 9 12 15 18
a1 <- array(c( 1:18), c(3, 6, 1)) a1
In order to output the sequence of numbers below, what will you need to input? 30 27 24 21 18 15 12 9 6 3 0
seq(30, 0, by = -3)
The following code, which is supposed to dump the google.com homepage HTML to the console, is missing a line at the ??? placeholder. What should this line be? import urllib.request webUrl = urllib.request.urlopen("http://www.google.com") ??? print(results)
results = webUrl.read()
You want to arrange bars in a chart from greatest to least in value. Which command would replace the BLANK in the code below to achieve this? diamonds %>% select (clarity) %>% table() %>% BLANK Barplot()
sort(decreasing = T) %>%
Which function enables you to get the values that are used for locating each of the elements in your graph?
the boxplots.stats() function
If you want to include quotes in your labels when creating a scatterplot, which character must you include?
the escape or backslash (\) character
If you have categorial variables or factors, which functions help you calculate the frequency of your variables
the summary() and table() functions
You create a simple calendar program that needs to print tomorrow's day of the week. Which code will work under all circumstances?
today=date.today() days=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] print("Tomorrow will be "+days[(today.weekday()+1)%7])
How can the following code be changed to reflect a line chart, with a title of "US Population 1790 - 1970", labeling the x-axis "Price of Diamonds" and the y-axis "Frequency"? plot(uspop)
uspop%>% plot( main = "US Population 1790-1970", xlab = "Year", ylab = "Population (in millions)" )
The default structure in R is a(n) _____.
vector
When should you verify what the VS Code python.pythonPath setting is set to?
when you have multiple installations of Python on your computer
Your program already imported the ZipFile module using from zipfile import ZipFile. How can you leverage this module to create a new zip archive and add a file to it?
with ZipFile("archive.zip","w") as newzip: newzip.write("file.txt")
How can you indicate that something is a comment, and not a command that should be run?
with the hashtag (#) symbol
What should come instead of the ??? placeholders for this code to correctly print the number of days until your birthday on Jun 30? Hint: the number of days in a timedelta object can be returned using its days attribute. today=date.today() bday=date(today.year,6,30) diff=??? if diff>0: print("Birthday in %d days" % diff) else: print("Birthday in %d days" % (???))
(bday-today).days; diff+365
What will the following script print? def inc(a,b=1): return(a+b) a=inc(1) a=inc(a,a) print(a)
4
How would you improve the code below? f = open("myfile.txt", "r") contents = f.read()
Check that f.mode == 'r' before calling f.read() to read from the file.
The statement below fails when you try to run it. Which troubleshooting step is irrelevant for this scenario? doc = xml.dom.minidom.parse("myfile")
Confirm that the file 'myfile' is first loaded to memory.
What class does Python provide to parse HTML?
HTMLParser
Can you print all cities and states in this JSON data, and what approach will you take if you can? [ { "country": [ { "city": "New York", "state": "NY" }, { "city": "Boston", "state": "MA" } ]}, { "country": [ { "city": "Quebec", "state": "QC" }, { "city": "Toronto", "state": "ON" } ]} ]
It is possible, by using one for i in theJSON loop and within it another nested for j in i["country"] loop.
Which real-world scenario is best described as a standard while loop?
Start reading a book, and stop after reading a certain number of pages.
This code has three critical issues. Which is not actually an issue? def main: print(hello!)
The function must be defined with the keyword 'func', not 'def'.
When would you use a data-oriented programming language, such as R?
When you need to analyze your data in ways that specifically address the questions important to you.
What is the difference between shutil.copy() and shutil.copystat() functions?
While shutil.copy() copies the file content, shutil.copystat() copies the file metadata.
You make a barplot with the following code. Using color names, how can you color the barplot red? `x = c(24, 13, 7, 5, 3, 2) barplot(x)
barplot(x, col = "red3")
You have an existing class Simple() that returns the sum of two numbers using its Add(x,y) method. How can you leverage it to build another class that calculates the inverse of the sum of two numbers?
class Advanced(Simple): def Inverse(self,x,y): return (1/Simple.Add(self,x,y))
In Python, what is the correct way to develop a class called Person that has parameters in the initialize function called name, age, and sex?
class Person: def __initialize__(self, name, age, sex): self.name = name self.age = age self.sex = sex
Using the table command, how can you create a contingency table specifying two variables in R?
ct <- table(df$variable, df$variable) ct
What code should come instead of the ??? placeholders to have a function that takes the amount of local currency and a varying number of exchange rates, and prints the value of the currency at each provided exchange rate? def Calc(???): for i in rates: print(???)
currency,*rates; currency*i
Which call will return the same result like date.today()?
datetime.date(datetime.now())
You need to set the annual payment in one function and print the respective monthly payment in a separate function. How would you fix the suggested code to work properly? def SetAnnual(): annual=10000 def PrintMonthly(): print("Your monthly payment is "+annual/12+" USD.") SetAnnual() PrintMonthly()
def SetAnnual(): global annual annual=10000 def PrintMonthly(): print("Your monthly payment is "+str(annual/12)+" USD.") SetAnnual() PrintMonthly()
Which function will return the sum of the first item in the data list and every tenth item after?
def Sum10th(data): sum=0 for i,d in enumerate(data): if (i % 10 == 0): sum=sum+d return sum
How can you filter by multiple variables using piping to return data where "regions" are equal to "South" or "psychRegions" are equal to "Relaxed and Creative"?
df %>% filter(region == "South" | psychRegions == "Relaxed and Creative") %>% print ()
Which code takes the variable "psychRegions" and recodes it so "Relaxed" displays a value of yes if "psychRegions" says "Relaxed and Creative"?
df %>% mutate(Relaxed = recode(psychRegions, "Relaxed and Creative" = "yes", "Friendly and Conventional" = "no", .default = "no")) %>% select(state_code, psychRegions, relaxed)
Using the pipes process from tidyverse, which code correctly shows a boxplot that compares price and color?
diamonds %>% select(color, price) %>% plot()
Which two procedures are needed to calculate the distance and hierarchy of the clusters in your cluster chart created with the code below? hc %>% plot(labels = df$state_code)
dist and hclust
Given the XML below, how will you add a third item to the list that has a yellow color and a small size? <?xml version="1.0" encoding="UTF-8" ?> <catalog> <item color="blue" size="large"/> <item color="red" size="medium"/> </catalog>
doc = xml.dom.minidom.parse("my.xml") newItem = doc.createElement("item") newItem.setAttribute("color", "yellow") newItem.setAttribute("size", "small") doc.firstChild.appendChild(newItem)
You need to print the content of the "list.txt" file to the console. Which code can you use, assuming the file must already exist and must not be overwritten or created?
f=open("list.txt",'r') print(f.read())
Given the following JSON data stored in a theJSON object, how can you list only the skill names? { "name": "John", "title": "Python Developer", "skills": [{ "name": "coding", "level": "expert" }, { "name": "documentation", "level": "basic" }] }
for i in theJSON["skills"]: print(i["name"])
Which code will you use to generate a date and time output in the following format? 13-Mar-2020 16:42:58
from datetime import datetime now=datetime.now() print(now.strftime("%d-%b-%Y %H:%M:%S"))
What code will you need to place instead of the ??? placeholder for the script to print '3'? a=1 b=2 def func(): ??? func() print(b)
global b b=a+b
How can the following code be changed to reflect a histogram, with a title of "History of the Price of Diamonds", labeling the x-axis "Price of Diamonds" and the y-axis "Frequency"? hist(diamonds$price)
hist(diamonds$price, main = "History of the Price of Diamonds", ylab = "Frequency", xlab = "Price of Diamonds")
Which code snippet can you use to print the number of digits in the number variable? You can assume this number is always positive and always less than 10,000.
if (number>=1000): print(4) elif (number>=100): print(3) elif (number>=10): print(2) else: print(1)
Where are the objects created in RStudio kept and displayed?
in the Environment pane
How can you add a regression line that goes through your data and superimposes it on top of the scatter plot?
lm(df$volunteering ~ df$museum) %>% abline()
Given that now=datetime.now(), which call may produce different results on different computers?
print(now.strftime("%c"))
What is the best way to see which version of python3 is installed without running it?
python3 --version
To install R, which URL should you use?
r-project.org