0% found this document useful (0 votes)
23 views10 pages

Ibm Ai

The document contains a series of programming tasks and concepts related to Python, including functions for cubing numbers, squaring even numbers, creating dictionaries from lists, and calculating various statistical distributions. It also discusses mutable and immutable data types, matrix multiplication, and provides examples of using libraries like NumPy and SciPy. Additionally, it concludes with a congratulatory note on passing with a grade of 92.85%.

Uploaded by

msalehtdc2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views10 pages

Ibm Ai

The document contains a series of programming tasks and concepts related to Python, including functions for cubing numbers, squaring even numbers, creating dictionaries from lists, and calculating various statistical distributions. It also discusses mutable and immutable data types, matrix multiplication, and provides examples of using libraries like NumPy and SciPy. Additionally, it concludes with a congratulatory note on passing with a grade of 92.85%.

Uploaded by

msalehtdc2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

For a given input list: 1, 2, 3, 4

1. Cube (element to power 3) each element


2. Return the results as a list

def get_cubed(lst):
return list(map(lambda x: x ** 3, lst))

lst = [1, 2, 3, 4]
result = get_cubed(lst)
print("Cubed values:", result)

Cubed values: [1, 8, 27, 64]

2. For a given input list: 1,2,3,4,5,6,7

1. Inspect each number in the input list and determine if it is even


2. Next square the even values
3. Finally return the squared evens in a list

def get_squared_evens(lst):
"""
INPUT: LIST (containing numeric elements)
OUTPUT: LIST (squared value of each even number in original list)
"""
squared_evens = []
for num in lst:
if num % 2 == 0: # Check if the number is even
squared_evens.append(num ** 2) # Square the even number
return squared_evens

# Example usage:
input_list = [1, 2, 3, 4, 5, 6, 7]
result = get_squared_evens(input_list)
print("Squared even values:", result)

Squared even values: [4, 16, 36]


3. Which of the following is/are NOT native or built-in data types in Python?

boolean
integer
float
heap
Correct
Correct!
string
varchar

4. For given input lists: a,b,c and 1,2,3

Create a dictionary from two input lists

def make_dict(lst1, lst2):


"""
INPUT: lst1, lst2 (equal-length lists)
OUTPUT: dict (with lst1 elements as keys and lst2 elements as values)
"""
if len(lst1) != len(lst2):
raise ValueError("Input lists must have the same length.")

result_dict = {}
for key, value in zip(lst1, lst2):
result_dict[key] = value

return result_dict

# Example usage:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
result_dict = make_dict(list1, list2)
print("Created dictionary:", result_dict)

Created dictionary: {'a': 1, 'b': 2, 'c': 3}


5. Mutable data types/collections in Python can be changed in place.
Immutable ones can not change in place. Which of the following are
mutable?

bool
int
float
set
list
string
tuple
complex

6. Which of the following is NOT true about Python?

Python code can run in IPython and Jupyter notebooks


Python allows for the inclusion of comments and pseudocode to better
organize code
Users can save .py files with an editor then subsequently execute them
from the command line
Base Python automatically parallelizes processing across cores when
multiple cores are available
Python allows users to save multiple functions in a .py file then import
those functions in a different file

(Correct. Base Python by default processes code with a single core. Multiprocessing requires
loading additional libraries/packages.)
7. For a given input list: abbcccddddeeeeeffffffggggggghhhhhhhh
Return a dictionary of character counts

1. Count the number of times each character appears in the string


2. Characters with a count of 0 should not be included in the output dictionary

def count_characters(string):
"""
INPUT: STRING
OUTPUT: DICT (with counts of each character in input string)

Return a dictionary of character counts


"""
char_counts = {}
for char in string:
if char in char_counts:
char_counts[char] += 1
else:
char_counts[char] = 1

# Remove characters with a count of 0


char_counts = {char: count for char, count in char_counts.items() if count
> 0}

return char_counts

# Example usage:
input_string = "abbcccddddeeeeeffffffggggggghhhhhhhh"
result_dict = count_characters(input_string)
print("Character counts:", result_dict)

The output will be:

Character counts: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':


6, 'g': 7, 'h': 8}
8. For the vector v = [2.0, -3.5, 5.1]:

1. Find the L1 norm of v


2. Return the result as a float

Certainly! Let’s calculate the L1 norm (also known as the Manhattan norm) of the vector v =
[2.0, -3.5, 5.1].

The L1 norm of a vector is the sum of the absolute values of its components. For a vector v with
components x_1, x_2, …, x_n, the L1 norm is given by:

∥v∥1=∣x1∣+∣x2∣+…+∣xn∣

In our case, we have:

∥v∥1=∣2.0∣+∣−3.5∣+∣5.1∣=2.0+3.5+5.1=10.6

Therefore, the L1 norm of vector v is approximately 10.6.

Let’s implement this in Python using NumPy:

import numpy as np

def calculate_l1_norm(v):
"""
INPUT: LIST or ARRAY (containing numeric elements)
OUTPUT: FLOAT (L1 norm of v)
"""
l1_norm = np.linalg.norm(v, ord=1)
return l1_norm

# Example usage:
vector_v = [2.0, -3.5, 5.1]
result = calculate_l1_norm(vector_v)
print("L1 norm of vector v:", result)

The output will be:

L1 norm of vector v: 10.6


9. NumPy array practice

1. Create a vector that starts at 1 and increases until 150


2. Turn the vector into a matrix with 10 rows and 15 columns
3. Return the sums for the 10 rows as a list. HINT: there should be ten values for the
printed sum
Use the following input vector values: vectorLower = 1; vectorUpper = 151
import numpy as np

def get_vector_sum(vectorLower, vectorUpper):


"""
INPUT: vector lower and upper bounds
OUTPUT: calculated value for vector sum
"""
# Create a vector ranging from 1 to 150
vector = np.arange(vectorLower, vectorUpper)
# Transform the vector into a 10x15 matrix
matrix = vector.reshape(10, 15)

# Calculate the row sums


row_sums = matrix.sum(axis=1).tolist()

return row_sums

# Example usage:
vectorLower = 1
vectorUpper = 151
result = get_vector_sum(vectorLower, vectorUpper)
print("Row sums:", result)

Row sums: [120, 345, 570, 795, 1020, 1245, 1470, 1695, 1920, 2145]

10. Which of the following pairs of events are mutually exclusive.


There can be more than one answer.

Odd numbers and the number 3


Even numbers and numbers greater than 10
Negative numbers and positive numbers less than 25
Correct
Numbers between 100-200 and numbers between 201-300
None of the above
11. Geometric distribution

The geometric distribution is a useful tool for modeling time to event data. A successful
street vendor says that on average 1 out of every 10 people who walk by on the street
stop to buy a taco.

1. Represent these data with a geometric distribution


2. What is the probability that the vendor has to wait until 20 people walk buy before
someone buys a taco?

import scipy.stats as stats

def geometric_distribution(p, k):


"""
Calculate the geometric probability for k trials.

Args:
p (float): Probability of success in a single trial.
k (int): Number of trials (starts from 1).

Returns:
float: Geometric probability for k trials.
"""
if k < 1:
raise ValueError("Number of trials (k) must be at least 1.")

# Calculate the geometric probability


prob = (1 - p) ** (k - 1) * p
return prob

# Example usage:
success_probability = 0.1 # Assuming 1 out of 10 people stop to buy a ta
co
num_trials = 20
result = geometric_distribution(success_probability, num_trials)
print(f"Geometric probability for {num_trials} trials: {result:.4f}")

Geometric probability for 20 trials: 0.0135


12. Poisson distribution

The Poisson distribution is a useful tool for modeling count data given discrete
intervals. Based on historical data the expected number of accidents at a busy
intersection is 4 per month.

1. Represent these data with a Poisson distribution


2. What is the probability of more than 7 accidents at that intersection next
month?

import scipy.stats as stats

def poisson_distribution(mu, k):


"""
Calculate the Poisson probability for k accidents.

Args:
mu (float): Average rate (mean) of accidents.
k (int): Number of accidents.

Returns:
float: Poisson probability for k accidents.
"""
if k < 0:
raise ValueError("Number of accidents (k) must be non-negative.")

# Calculate the Poisson probability


prob = 1 - stats.poisson.cdf(k, mu)
return prob

# Example usage:
average_accidents = 4 # Average accidents per month
num_accidents = 7
result = poisson_distribution(average_accidents, num_accidents)
print(f"Probability of more than {num_accidents} accidents: {result:.4f}"
)

Probability of more than 7 accidents: 0.0511


13. Gaussian distribution
The Gaussian or Normal distribution is use heavily throughout statistics and
data science. Lets assume scores for this assessment have a mean of 50% and a
standard deviation of 20%.

1. Represent these data with a Normal distribution


2. What is the probability of observing a score >= 80?
Use 50.0, 20.0, and 80 for your input values

import scipy.stats as stats

def gaussian_distribution(loc_val, scale_val, cdf_val):


"""
Calculate the probability of observing a score >= cdf_val in a Normal
distribution.

Args:
loc_val (float): Mean (average) of the distribution.
scale_val (float): Standard deviation of the distribution.
cdf_val (float): Value for which we want to find the cumulative p
robability.

Returns:
float: Probability of observing a score >= cdf_val.
"""
# Calculate the CDF at the given value
cdf = stats.norm(loc_val, scale_val).cdf(cdf_val)

# Probability of observing a score >= cdf_val


prob_greater_than_or_equal = 1 - cdf
return prob_greater_than_or_equal

# Example usage:
mean = 50.0
std_dev = 20.0
score = 80.0
result = gaussian_distribution(mean, std_dev, score)
print(f"Probability of observing a score >= {score}: {result:.4f}")

Probability of observing a score >= 80.0: 0.0668


14. Perform matrix multiplication on a square matrix HINT: A 2X2 matrix times a 2x2
matrix should yield a 2x2 matrix

def matrix_multiplication(A, B):


"""
Multiply two square matrices A and B.

Args:
A (list of lists): First square matrix (size n-by-n).
B (list of lists): Second square matrix (size n-by-n).

Returns:
list of lists: Resulting matrix (product of A and B).
"""
n = len(A) # Assuming A and B are both n-by-n matrices

# Initialize an empty matrix C with zeros


C = [[0] * n for _ in range(n)]

# Perform matrix multiplication


for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]

return C

# Example usage:
A = [[2, 3, 4], [6, 4, 2], [-1, 2, 0]]
B = [[1, 0, 2], [3, 1, 1], [2, 0, -1]]

result = matrix_multiplication(A, B)
for row in result:
print(row)

[19, 3, 3]
[22, 4, 14]
[5, 2, 0]

Congratulations! You passed!


Grade received 92.85%

You might also like