# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Exercises 1

import numpy as np
import torch

# +
# Using a python list, create a torch tensor with
# a value of 10 and a data type of 32 bit floating point.


# answer


# +
# Using a python list element, create a torch tensor with
# a value of 10 and a long data type (torch.long or torch.int64).

# answer


# +
# Extract the value of the tensor from the previous cell as a python scalar type, e.g.
print(type(3.14))


# answer


# +
# Find the Matrix-vector product of Fib and x.

Fib = torch.tensor([[1, 1], [1, 0]], dtype=torch.long)
x = torch.ones(2, dtype=torch.long)


print("Fib x:")

# answer


# +
# Change the dimensions of P to (1, 9).
P = torch.randn(3,3)


print(P.shape)


# answer


# +
# Convert this numpy ndarray to a tensor.
# Make sure its data type is torch.float32.
a = np.ones((2,3,))


# answer


# +
# Convert this torch tensor to a numpy ndarray.
t = torch.tensor([2,3,5,7,11], dtype=torch.float32)


# answer


# +
# Determine (programmatically) if you have an Nvidia GPU 
# on your machine, and the libraries to support it.

# answer


# +
# Rewrite the Numpy version of Sieve of Eratosthenes using torch instead of numpy.
import numpy as np

# Modified from primesfrom3to, listed here:
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188
#
def numpy_sieve(n):
    """ Returns a array of primes p <= n """

    # a byte for each integer 0 up to n-1
    candidates = np.ones(n+1, dtype=np.uint8)
    candidates[0:2] = 0  # 0 and 1 are not prime

    max_divisor = int(np.ceil(np.sqrt(n)))
    divisors = np.arange(2, max_divisor+1, dtype=np.long)

    for i in divisors:
        if candidates[i]:  # if the ith entry is true, therefore i is prime

            # starting with i*i, set all multiples of i to 0
            candidates[i*i::i] = 0

    return np.nonzero(candidates)[0]


# answer


StarcoderdataJupyterScriptsDedupFiltered