[go: up one dir, main page]

0% found this document useful (0 votes)
20 views20 pages

Tareas para La Asignatura Python 1 de La THD

The document contains a series of Python exercises focused on fundamental programming concepts such as using built-in functions, performing mathematical operations, type checking, string formatting, list manipulation, and dictionary operations. It includes instructions for executing commands in an interactive terminal, as well as examples and expected outputs for various expressions. Additionally, it covers the use of libraries like NumPy and demonstrates the creation and manipulation of data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views20 pages

Tareas para La Asignatura Python 1 de La THD

The document contains a series of Python exercises focused on fundamental programming concepts such as using built-in functions, performing mathematical operations, type checking, string formatting, list manipulation, and dictionary operations. It includes instructions for executing commands in an interactive terminal, as well as examples and expected outputs for various expressions. Additionally, it covers the use of libraries like NumPy and demonstrates the creation and manipulation of data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Alfonso Gutierrez Perez

Python
Exercise 1.1.1
Execute the following instructions in the interactive terminal and check the output:

1- help ( print )

Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

2- import numpy

3- dir ( numpy )

'around',
'array',
'array2string',
'array_equal',
'array_equiv',
'array_repr',
'array_split',
'array_str',
'asanyarray',
'asarray',
'asarray_chkfinite',
'ascontiguousarray',
'asfarray',
'asfortranarray',
'asmatrix',
'atleast_1d',

4- help ( numpy . linspace )

Help on function linspace in module numpy:

linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,


axis=0)
Return evenly spaced numbers over a specified interval.

Returns `num` evenly spaced samples, calculated over the


interval [`start`, `stop`].

The endpoint of the interval can optionally be excluded.

.. versionchanged:: 1.16.0
Non-scalar `start` and `stop` are now supported.

.. versionchanged:: 1.20.0
Values are rounded towards ``-inf`` instead of ``0`` when an
integer ``dtype`` is specified. The old behavior can
still be obtained with ``np.linspace(start, stop, num).astype(int)``

Parameters
----------
start : array_like
The starting value of the sequence.
stop : array_like
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
If True, `stop` is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (`samples`, `step`), where `step` is the spacing
between samples.
dtype : dtype, optional
The type of the output array. If `dtype` is not given, the data type
is inferred from `start` and `stop`. The inferred dtype will never be
an integer; `float` is chosen even if the arguments would produce an
array of integers.

.. versionadded:: 1.9.0

axis : int, optional


The axis in the result to store the samples. Relevant only if start
or stop are array-like. By default (0), the samples will be along a
new axis inserted at the beginning. Use -1 to get an axis at the end.

.. versionadded:: 1.16.0

Returns
-------
samples : ndarray
There are `num` equally spaced samples in the closed interval
``[start, stop]`` or the half-open interval ``[start, stop)``
(depending on whether `endpoint` is True or False).
step : float, optional
Only returned if `retstep` is True

Size of spacing between samples.

See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
number of samples).
geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
scale (a geometric progression).
logspace : Similar to `geomspace`, but with the end points specified as
logarithms.
Examples
--------
np.linspace(2.0, 3.0, num=5)
array([2. , 2.25, 2.5 , 2.75, 3. ])
np.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. , 2.2, 2.4, 2.6, 2.8])
np.linspace(2.0, 3.0, num=5, retstep=True)
(array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)

Graphical illustration:

import matplotlib.pyplot as plt


N=8
y = np.zeros(N)
x1 = np.linspace(0, 10, N, endpoint=True)
x2 = np.linspace(0, 10, N, endpoint=False)
plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
plt.ylim([-0.5, 1])
(-0.5, 1)
plt.show()
Exercise 1.2.1

Compute the result of the following expressions in the interactive terminal:

1- 6*3
Out[16]: 18
2- (2222*333)-(111*555)
Out[18]: 678321
3- ((2002+666)*3+1001)/(33*(222-444))
Out[28]: -1.229183729183729
4- (10**6)*(10**-5)
Out[33]: 10.0
5- 3**8/2**7
Out[34]: 51.2578125
6- ((2+1j)*(1-1j))/((1j**2)*(1+1j))
Out[41]: (-1+2j)
Exercise 1.2.2

Check the type of the results of the followin expressions using the type function.

1- 6/2
Out[42]: 3.0
2- 6//2
Out[43]: 3
3- 7/2
Out[44]: 3.5
4- 7//2
Out[46]: 3
5- 8/2.1
Out[47]: 3.8095238095238093
6- 8.//2.1
Out[48]: 3.0
Exercise 1.2.3
Evaluate the following expressions and data conversions in the interactive terminal:

1- Compute the quotient and the rest of the integer division 100/3.

100%3
Out[49]: 1

100//3
Out[50]: 33
2- Compute the ratio 100/3 in R
100/3
Out[52]: 33.333333333333336
3- rounded = int(round(5.66))
print("Rounded to int:", rounded)

4-clipped = int(5.66)
print("Clipped to int:", clipped)

import math

5-sqrt_2 = math.sqrt(2)
print(sqrt_2)
Exercise 1.3

1.( (6/2) == 3
Out[53]: True
2. (7/2) == 3
Out[54]: False
3.(7.//2.) == 3
Out[55]: True
4. (type(6/2)==type(3))
Out[63]: False
5. (type(6/2)==type(3.))
Out[64]: True
6. (type(6//2)==type(3))
Out[67]: True
7. ((6//2)==3 and 3>1)
Out[68]: True
8. ((6//2)==4 and 3>1)
Out[70]: False
9. ((6//2)==4 or 3<1)
Out[71]: False
10. ((6/2)==4 or not 3>1)
Out[72]: False
11. ((6/2)==3 and not 3<1)
Out[73]: True
12. (((6/2)==3 and 3<1) or True)
Out[74]: True
Exercise 1.4
a = 8.
b=2

print(type(a)) # Output: <class 'float'>


print(type(b)) # Output: <class 'int'>

c=a/b

c *= 2.0
d = c - 2.0

print("a =", a)
print("b =", b)
print("c =", c)
print("d =", d)
Exercise 1.5.1
Store the string ‘‘Fido’’, the int 2 and the float 1.5 into the variables name, age and
height and use those values to print the message “My dog Fido is 2 years old and 1.5 ft
high”

1. %-formatting (Old)

name = 'Fido'
age = 2
height = 1.5
message = "My dog %s is %d years old and %.1f ft high" % (name, age, height)
print(message)

2. . f-string

name = 'Fido'
age = 2
height = 1.5
message = f"My dog {name} is {age} years old and {height} ft high"
print(message)

3. format class-method

name = 'Fido'
age = 2
height = 1.5
message = "My dog {} is {} years old and {} ft high".format(name, age, height)
print(message)

Exercise 1.6.1
name = "Fido"
age = 2
height = 1.5
listDogData = [name, age, height]
message = "My dog {} is {} years old and {} ft high".format(*listDogData)
print(message)
listDogData[2] = 2.1
message = "My dog {} is {} years old and {} ft high".format(*listDogData)
print(message)
Exercise 1.6.2
1. Define a list numbers containing the multiples of 10: 10, 20, . . . , 100
numbers = [i * 10 for i in range(1, 11)]
2. Define a list letters containing the first five letters of the alphabet: a, b, c, d, e
letters = ['a', 'b', 'c', 'd', 'e']
3. Concatenate both lists numbers and letters into the list mixed (+ operator)
mixed = numbers + letters
4. Check the length of mixed with the len function.
length = len(mixed)
print(length)
5. Define the list numbersRepeated by concatenating 5 copies of numbers (*
operator) numbersRepeated = numbers * 5
6. Extract the multiples of 20 from numbersRepeated and store them into
multiples20 (slicing)
multiples20 = numbersRepeated[1::3]
7. Extract the numbers from mixed and print them for item in mixed:
if isinstance(item, int):
print(item)
Exercise 1.6.3
1. AA = [1, 2, 3]
AA[2] = 30
The third element is 3 not 30

2. TT = ["a", "b", "c"]


TT[0] = "A" AA[2] = 30
The first element is a not A
Exercise 1.6.4
1. Define the List week=[‘‘Monday‘‘, ‘‘Wednesday’’,’’Thursday’’].
week = ["Monday", "Wednesday", "Thursday"]
2. Define the list weekend=[‘‘Friday’’, ‘‘Saturday’’, ‘‘Sunday’’].
weekend = ["Friday", "Saturday", "Sunday"]
3. Remove “Friday” from weekend
weekend.remove("Friday")
4. Append “Friday” to week.
week.append("Friday")
5. Insert “Tuesday” at the right position into week.
week.insert(1, "Tuesday")
6. Add both weekend days to week
weekend = ['Friday', 'Saturday', 'Sunday']
week.extend(weekend)
print(week)
7. What is the output of print(week.index(‘‘Tuesday‘‘))?
The output of print(week.index('Tuesday')) will be 4
Exercise 1.6.5
S = n(n + 1) / 2

Substituting n = 7 into the formula:

S = 7(7 + 1) / 2
= 7(8) / 2
= 56 / 2
= 28

The sum using the range() function and the sum() function:

n=7
k_list = list(range(1, n+1))
S_sum = sum(k_list)

print(S_sum)

The output will be:

28
Exercise 1.7

1.Define at empty dictionary dictEmpty1 using the {}-syntax

2. Define at empty dictionary dictEmpty2 using the dict constructor

3. Store the data from exercise 1.5.1 into the dictionary dictDogData1 and access the
values from the dictionary to print the formatted string from the same exercise. Use
the keys “name”, “age” and “height” for the dictionary items and the {}-syntax do
define it.
4. Define a second dictionary dictDogDataCopy2 as in the previous Point but using the
dict constructor.
5. Six months later Fido grew to 2.1f t. Update the data in dictDogData1.
6. Add the entry “home” to dictDogData1 and set its value to “Deggendorf”
7. Print the list of the keys of dictDogData1
8. What is the output of the following print statements? Verify your answers by running
the code and explain the result. 1 print ( dictDogData . get ( ‘ ‘ name ’ ’ , ‘‘ Bello ’ ’) ) 2
print ( dictDogData . get ( ‘ ‘ NAME ’ ’ , ‘‘ Bello ’ ’) )

dictEmpty1 = {}
dictEmpty2 = dict()
dictDogData1 = {
"name": "Fido",
"age": 2,
"height": 1.5
}

message = "My dog {name} is {age} years old and {height} ft


high".format(**dictDogData1)
print(message)
dictDogDataCopy2 = dict(name="Fido", age=2, height=1.5)
dictDogData1["height"] = 2.1
dictDogData1["home"] = "Deggendorf"
print(list(dictDogData1.keys()))

Exercise 1.8.1
1.The sequence of instructions creates two lists, `aa` and `bb`, and assigns the value of
`aa` to a new variable `aaCopy`. The `+=` operator is used to concatenate `bb` to `aa`,
modifying the original list object referred to by `aa`. When `aaCopy` is printed, it will
output the modified list.

2.The sequence of instructions creates two lists `aa` and `bb`, assigns the value of `aa`
to a new variable `aaCopy`, and concatenates `aa` and `bb` using the `+` operator to
create a new list object for `aa`. When `aaCopy` is printed, it outputs the original list
object, which remains unchanged.

3.The sequence of instructions creates two lists aa and bb, assigns a copy of aa to a
new variable aaCopy using the copy method, and concatenates aa and bb using the +
operator to create a new list object for aa. When aaCopy is printed, it outputs the
original list object, which remains unchanged.

4.The sequence of instructions creates two lists aa and bb, assigns a slice of aa to a new
variable aaCopy, and concatenates aa and bb using the + operator to create a new list
object for aa. When aaCopy is printed, it outputs the original list object, which remains
unchanged.

5. The code creates two tuples, `aa` and `bb`, and assigns a copy of `aa` to `aaCopy`.
The tuples are then concatenated using the `+` operator and the result is assigned to
`aa`. Finally, the original tuple object referenced by `aaCopy` is printed. Since tuples are
immutable, `aaCopy` retains the same original values and is not affected by the
concatenation operation.
6.The code creates two tuples, `aa` and `bb`, and assigns `aa` to `aaCopy`. Then it
concatenates `aa` and `bb` using the `+` operator to create a new tuple object and
assigns it to `aa`. Finally, it prints the original tuple object referenced by `aaCopy`.
Exercise 1.8.2
import copy

# create a dictionary
dictDogData1 = {
"name": "Fido",
"age": 2,
"height": 1.5,
"friends": ["Bello", "Leo", "Waldi"]
}

# make a reference copy of the dictionary


dictDogData2 = dictDogData1

# make a shallow copy of the dictionary


dictDogData3 = copy.copy(dictDogData1)

# make a reference copy of the dictionary


dictDogData4 = dictDogData1

# make a shallow copy of the dictionary


dictDogData5 = copy.copy(dictDogData1)

# add Lilly to the list of Fido's friends


dictDogData1["friends"].append("Lilly")

# print the keys of all dictionaries


print("Keys of dictDogData1:", list(dictDogData1.keys()))
print("Keys of dictDogData2:", list(dictDogData2.keys()))
print("Keys of dictDogData3:", list(dictDogData3.keys()))

# print Fido's friends from all dictionaries


print("\nFido's friends in dictDogData1:", dictDogData1["friends"])
print("Fido's friends in dictDogData2:", dictDogData2["friends"])
print("Fido's friends in dictDogData4:", dictDogData4["friends"])
print("Fido's friends in dictDogData5:", dictDogData5["friends"])

You might also like