SC1003 Quiz 1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is the following output for 85? mark = float(input('what is your mark')) if 90 <= mark <= 100: print('You got A') elif 80 <= mark <90: print('You got B') elif 70 <= mark < 80: print('You got C') else: print('Not good')

You got B

Which of the following lists corresponds to 'range(15, 3, -4)'?

[15, 11, 7]

True or False: For counter-controlled loops, the number of repetition is not known before the loop body starts.

False

Given below, what will be the values of val_1 and val_2, respectively? myStr = 'Hello World'val_1 = 'd' < 'D'val_2 = 'd' in myStr

False and True

mystr = 'Hello World' print(mystr[6])

'W'

mystr = 'Hello World' print(mystr[:-6:-2])

'drW'

What should be the values of A and B so that the expression 'A and B' is True.

A = True; B = False

Write a program that asks the user for the number of boys and that of girls in a class. The program should calculate and display the percentage of boys and girls in the class. A sample run is as follows: Enter the number of boys: 65 Enter the number of girls: 77 Boys: 46% Girls: 54% Write the Python program.

# Get the number of boys. boys = int(input("Enter the number of boys: ")) # Get the number of girls. girls = int(input("Enter the number of girls: ")) # Calculate the total number of students. total = boys + girls ##output version 1: round function percent_boys = round(boys/total*100) percent_girls = round(girls/total*100) # Print the percentage of boys. print("Boys:",str(percent_boys) + "%") # Print the percentage of boys. print("Girls:",str(percent_girls) + "%") ##output version 2: format function using % # Calculate the percentage of boys. percent_boys = boys / total # Calculate the percentage of girls. percent_girls = girls / total # Print the percentage of boys. print("Boys:", format(percent_boys, ".0%")) # Print the percentage of girls. print("Girls:", format(percent_girls, ".0%"))

Write a Python program, in the fewest number of lines possible, which creates a list of all the square numbers: x2 (where 1<=x<=100) that are divisible by 3.

# solution 1: to generate the list by list comprehension list1 = [x**2 for x in range(1,101) if x**2 % 3 == 0] print(list1)

Consider a system for storing anonymous grades of each lab class. Define a data structure, which can identify individuals in each lab group by an ID number 1-40 (inclusive). To identify the person in the entire class you would also need the group name, e,g., 'FE2'. Each corresponding person should have a number between 1-100 (inclusive) to define grade.

# solution 1: to use a dictionary # the key is a tuple (group_name, ID). NOTICE: the key has to be immutable and unique # the value is the grade grades = { ('FS1', 1) : 45, ('FS1', 2) : 75, ('FS1', 3) : 25, ('FS1', 4) : 65, ('FS2', 1) : 75, ('FS2', 2) : 40, ('FS2', 3) : 70, ('FS2', 4) : 80 } print(grades[('FS1', 1)])

mystr = 'Hello World' print(mystr[8:-4])

' ' (empty String)

In using modulus operator in Python, which of the following statements is true? 14 % 5 = 4 18 % 5 = 0 9 % 4 = 2 3 % 1 = 2

14 % 5 = 4

User input if the output of the following code was 23? date = input("date of today?") thedaybeforeyesterday = int(date) - 2 print(thedaybeforeyesterday)

25

What will be the result of the given expression below? len('a c') * ord('a')

291

myStr = 'Python Rules' print(myStr[::-2].upper().find('Y'))

5

Henry has 50 sweets to be distributed to 7 children. In Python, which of the following expressions calculates the maximum number of sweets each child would receive and the corresponding result?

50 // 7; 7

Given that x = 9 and y = 3, what is the output 'of x ** y' in Python?

729

Which of the following is NOT a valid variable name in Python programming? ic_number_8 _8icnumber 8_IC_Number icnumber8

8_IC_Number

In Python, which of the following symbols is used to mark a start of a block?

:

What is an assignment operator

=

What is the difference between a flowchart and pseudocode?

A flowchart is a diagrammatic description of an algorithm while pseudocode directly uses informal English to describe an algorithm, step by step, with one step per line.

In the following statements about Python functions, which one is FALSE? A function should be defined for one task and should not be too long. A function can have at most one return statement. Functions should be reusable. A function can be called by other functions. When designing functions, we should always provide comments.

A function can have at most one return statement.

In the following statements about recursive functions, which one is FALSE? Recursive functions support the divide-and-conquer problem solving. Recursive functions are usually concise and elegant. A function that invokes itself is called a recursive function. A recursive function is always efficient than its loop-based version.

A recursive function is always efficient than its loop-based version.

A flowchart needs to represent a situation whether a student has fever or not... the system will consider the temperature; if it's 37.5 and above, it will be considered 'Fever', else it is 'Normal'.Which of the following algorithm constructs is this an example of?

Branching

What statement can be used to immediately exit the execution of a current loop?

Break Statement

Which of the following is False?: None of the options C++ and Java support Object-Oriented Programming. Python and Java are very portable across different computer platforms. C and Python are interpreted languages.

C and Python are interpreted languages

Which of the following is TRUE about the given Pseudocode. IF condition is True Then Siute1 Else Suite2 End If Execute SUITE1 when condition is true. Execute SUITE2 when condition is true. End program when condition is false. End program when condition is true.

Execute SUITE1 when condition is true.

n the following statements about Contacts, which one is FALSE? Contacts = {'Bill':28, 'Rich':30, 'John':15, 'Jane':27} 'Bill'is called a key, and it is immutable. Contacts has eight elements. Contacts['Rich'] is 30. Contacts is a dictionary. Contacts['Bill'] is mutable.

Contacts has eight elements

True or False: While statement allows repetition of a suite in Python codes as long as the condition, which is a Boolean expression, is False.

False: While statement allows repetition of a suite in Python codes as long as the condition, which is a Boolean expression, is True.

Correct for-Syntax in Python

For iterating_var in <sequence>: Suite (one or more statements)

Initialize passes to zero Initialize failures to zero Initialize student_counter to one While student_counter is less than or equal to ten Input the next score * * * * * add one to student_counter EndWhile * *

If the student passed Add one to passes else Add one to failures EndIf print the number of passes print the number of failures

Arrange the following steps according to the chronological logic of general looping structure. (Loop Body, Test, Update, Initalize)

Initialize (loop control variable) test (continue or no) loop body (main computation being repeated) update (Modify the value of the loop control variable so that next time when we test, we may exit the loop)

Initialize student_counter to zero While student_counter is less than or equal to ten Input the next score Add the score into the total EndWhile Set the class average to the total divided by ten There are some errors in the above Pseudocode. Please indicate where the errors are and how to correct them

Initialize total to zero (Must initialize variable before use) Initialize student_counter to one (if counter starts from zero, will be 11 students instead of 10) While student_counter is less than or equal to ten Input the next score Add the score into the total Add one to student_counter (update looping control variable) EndWhile Set the class average to the total divided by ten

Which of the following is NOT true about an algorithm? It must be ambiguous. It must consider all possible decision points. Every step must be clear and precise. It must terminate.

It must be ambiguous

When choosing a password for online accounts, there are typically certain requirements for the strength of the password. Develop a Python program for testing if a string satisfies some appropriate criteria for a strong password. It's up to you to define the requirements.

LENGTH = 8 # the minimum length for a strong password password = input("Input your password: ") upCase = False # indicating if the password has at least one upper case letter, default value: False lowCase = False # indicating if the password has at least one lower case letter, default value: False digit = False # indicating if the password has at least one digit, default value: False for char in password: # iterate on each character of the password if char.isupper(): # if the character is in upper case, set upCase to True upCase = True if char.islower(): # if the character is in lower case, set lowCase to True lowCase = True if char.isdigit(): # if the character is a digit, set digit to True digit = True length = len(password) # get the length of the password strong = upCase and lowCase and digit and length > LENGTH # strong would be True, if all the conditions hold if strong: print("Your password is strong enough.") else: print("Your password is weak.")

In computer programming, this refers to a sequence of instruction that is continually repeated until a certain condition is reached?

Loop

Advantage of Interpreted language over Compiled language for coding program?

More portable across different computer platforms

In the following statements about composite types/ data structures, which one is FALSE? Data structures are usually associated with specific operations. Data structures provide particular ways to store data. One data structure can be used to solve all problems. A composite type is constructed based on primitive or other composite types.

One data structure can be used to solve all problems

Language normally used for web-based applications

PHP

Which of the following is correct?: C++ and R are compiled language. None of the options Python and Javascript are interpreted language. C and Java are interpreted language.

Python and Javascript are interpreted language

For a sentinel-controlled loop, how do you call the value that signifies the end of the loop?

Sentinel Value

Given the function definition below, which of the following descriptions is FALSE? def sum(x, y):return x + y The function calculates the sum of its parameters and returns the result. The function has two parameters. The function name is called sum. The function definition has no errors.

The function definition has no errors

Which of the following is TRUE about the given Python Code? count = 7 while count <15: count = count + 1 print("count= ", count, end=" ") The loop will stop when count = 7. The loop will be repeated 7 times. The loop will not end. The loop will be false when count = 15.

The loop will be false when count=15

Which of the following is not an element of iterative accumulation? The variable to store the accumulation result. The print statement to print the result. The target value in each iteration. The loop to drive accumulation iteratively.

The print statement to print the result.

Which of the following statements is NOT true about variables in Python? Variables can use uppercase and lowercase letters through A to Z. Variables can be of any length. Variables cannot start with a number. The variable 'MyNameIs' is the same as the variable 'My_Name_Is'.

The variable 'MyNameIs' is the same as the variable 'My_Name_Is'.

Mary = 35 print(Mary > 24)

True

True or False. While loop is useful for the purpose of repeatedly asking the user for an input until the input fulfills the requirement.

True

what would be the result of the expression 37.5 != 375

True

Given the Python statements below, which of the following descriptions is FALSE? aList = list('abc') bList = [1, 3.14, 'a', True] aList is constructed by calling the constructor of lists. aList has one element, i.e., the string 'abc'. The string 'abc' is an iterable object. bList has four elements.

aList has one element, i.e., the string 'abc'.

Problem solving using computational methods is based on ___________ and the ___________ that implement them.

algorithms, programs

Sample : enter a string (enter #### to stop): apple enter a string (enter #### to stop): banana enter a string (enter #### to stop): strawberry enter a string (enter #### to stop): book enter a string (enter #### to stop): #### 3 strings with letter 'a' while True: str = input("enter a string: ") for letter in str: if letter == 'a': break count +=1 print(count , "strings with letter 'a'") There are some errors in the above program. Please indicate where the errors are and how to correct them

count=0 while True: str_sentinal = input("enter a string (enter #### to stop): ") if str_sentinal =="####": break for letter in str_sentinal : if letter == 'a': count +=1 break print(count , "strings with letter 'a'")

four steps used in computational thinking process

decomposition pattern recognition abstraction algorithm design

2 reasons for choosing high-level programming language over machine-language for coding program

easier to code program less error prone in coding program

total = 4 + 5 finalResult = total * 5 finalresult = finalResult -1 print('finalresult')

finalresult

What is the output of the following Python program? value = 6 if value % 2 == 0: print("first", value) elif value % 3 == 0: print("second", value) while value <= 9: value = value + 1 if value == 8: continue else: pass print ("third", value) else: print ("fourth", value) print("fifth", value)

first 6, third 7, third 9, third 10, fourth 10, fifth 10

What data type would you use for the price of milk tea in dollars?

float

Write a simple Python program to implement the Pseudocode of FizzBuzz problem in discussion #1.

for num in range(1, 21): if num % 15 ==0: print("FizzBuzz") elif num %3 ==0: print("Fizz") elif num %5==0: print("Buzz") else: print(num)

General Python syntax for If-Else statement

if condition: StatementBlockfor True else: StatementBlockfor False

What is Abstraction? Why do we need it? What are the two aspects of Abstraction?

l Abstraction is a process to identify what is important without worrying too much about the detail so that we can focus on the important part. l Since Abstraction provides a means to distil what is essential, it can help us to come up with manageable approach to create computational solutions. In addition, Abstraction also help us to view things at different degrees of detail. l Abstraction can be performed in two main aspects: data and algorithm, which form the two bases for programming: data structures and functions. This session is focus on the first part, data structures.

Write the FizzBuzz algorithm using pseudocode. FizzBuzz is a standard interview problem. The Problem state: Write a code that prints each number from 1 to 20 on a new line. Print "Fizz" if the number is the multiple of 3. Print "Buzz" if the number is multiple of 5 For number which is multiple of both 3 and 5 print "FizzBuzz" The sample run is as follows: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz

num : 1 FOR num -> 1 to 20 IF num MOD 15 ===0 PRINT "FizzBuzz" ELSE IF num MOD 3 ===0 PRINT "Fizz" ELSE IF num MOD 5===0 PRINT "Buzz" ELSE PRINT num ENDIF ENDFOR

This built-in function in Python displays related message and data on the shell screen.

print

myStr = "AbCdE" str1 = symmetricString(myStr) print(str1)

print(str1) # AbCdEEdCbA

myStr = "ABC" str1 = reverseAndRepeat(myStr, 2) str2 = reverseAndRepeat(myStr, 3) print(str1) print(str2)

print(str1) # CCBBAA print(str2) # CCCBBBAAA

myStr = "AbCdE" str1 = reverseAndOppositeCase(myStr) print(str1)

print(str1) # eDcBa

How do you call the following: "==", "<=", "!="

relational operators

Given two lists of grades (list of integers) from two classes, write a Python program that will check which class has the highest average score and the highest maximum score.

scores1 = [10, 11, 15, 20, 55, 76, 90, 84] scores2 = [4, 9, 12, 98, 35, 42, 4, 5, 10] avg1 = float(sum(scores1) / len(scores1)) avg2 = float(sum(scores2) / len(scores2)) maxNum = max(max(scores1), max(scores2)) maxAvg = max(avg1, avg2) print("Highest Avg: ", maxAvg) print("Hightest Score: ", maxNum)

In the following statements about something, which one is FALSE? something = [x for x in range(1, 10) if x % 2 == 0] something has five elements. something[::-1] gives you the list [8, 6, 4, 2]. something is list. The second element of something is 4. something is generated by list comprehension.

something has 5 elements

In the following statements about something, which one is FALSE? something = (1, 3.14, 'Python', True) something a tuple. something has four elements. 2 in something evaluates to False. something is mutable.

something is mutable

In the following statements about something, which one is FALSE? something = [1, 2, 'Python', [3, 4], True] 2 in something evaluates to True. something[::-1] gives you the list [True, [3,4], 'Python', 2, 1] something[3] is a list something is mutable. something[3][1] is a list something has five elements. somethingis a list.

something[3][1] is a list.

True or false: Branching occurs when an algorithm makes a choice to one of two or more things

true

For each of the following, discuss what the outcome will be if they are executed by a Python interpreter (e.g.IDLE3) in the sequence shown. c = 10 7 = a a = d a = c + 1 a + c = c 3 + a 7up = 10 import = 1003 b = math.pi * c int = 500 a ** 3 a,b,c = c,1,a b,c,a = a,b c = b = a = 7 print( A ) print( "b*b + a*a = c*c" ) print( 'A' ) print( "c" = 1 )

valid, python statement invalid, LHS cannot be a literal invalid because d hasn't been created or defined valid, python statement (LHS is a variable, RHS is an expression) invalid, because LHS cannot be an expression, should be a variable valid, python expression invalid, python naming convention: cannot start a variable name with a digit invalid, import is a reserved word in python invalid, need to first "import math" valid valid valid invalid, different number of elements on both sides valid invalid, A not defined valid valid invalid

Which of the following declares a variable, var1 and assigns it a string value, var2?

var1 = "var2"

What is like a labeled box that represents and stores data temporarily

variable

While-Syntax in Python

while <boolean expression>: Suite (one or more statements)

Write a Python program that reads an integer from the user, which is the width of the pattern below, and then prints out the pattern. Suggestion: use nested for loops. Hint: print("*",end=""). Enter Pattern Width: 5 * ** *** **** ***** **** *** ** *

width = int(input("Please enter pattern width: ")) for i in range (1,width * 2): if i < width: count = i else: count = width * 2 - i for j in range (count): print("*", end="") print()


Kaugnay na mga set ng pag-aaral

Advanced Computer Science Chapter 11

View Set

Pathophysiology Chapter 18 Urinary System Disorders

View Set

Finance - Capital Budgeting Techniques

View Set

Psychology Ch's 13-16 Final Exam S2

View Set