lab_2_learning_python

.py

School

University of Texas, Rio Grande Valley *

*We aren’t endorsed by this school

Course

2350

Subject

Civil Engineering

Date

Apr 3, 2024

Type

py

Pages

2

Uploaded by suckmyassbuddy

""" **CIVE 2350: Numerical Methods for Civil Engineers** **Lab B: Learning Python** """ import math # %% Question `sort_last` """ # Given a list of non-empty tuples, return a list sorted in increasing # order by the last element in each tuple. # e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields # [(2, 2), (1, 3), (3, 4, 5), (1, 7)] Hint: use `sorted` with a custom key """ def sort_last(tup): tup.sort(key = lambda x: x[1]) return tup tup = [(1, 7), (1, 3), (3, 4, 5), (2, 2)] print(sort_last(tup)) # %% """ Write a program which can compute the factorial of a given number using a recursive function.. Example: Input: 8 Output: 40320 """ def get_factorial(x): if x == 1: return 1 else: return x * get_factorial(x-1) get_factorial(8) # %% """ Write a function that takes a list and returns a new list that contains a sorted list of unique elements in the first. Example: Input: [1, 5, 2, 3, 4, 5, 2, 3, 4] Output: [1, 2, 3, 4, 5] """ def get_uniques(x): return sorted(set(x)) get_uniques([1, 5, 2, 3, 4, 5, 2, 3, 4]) # %% """ Return the average of a list of numbers Example: Input: [5, 3, 4, 5, 2] Output: 3.8 """ def get_average(x):
return sum(x)/len(x) x = [5,3,4,5,2] get_average(x) # %% """ Write a program to calculate the area of a circle. Import the "math" library to get pi """ def get_area_circle(radius): import math return math.pi*(radius**2) get_area_circle(4) #%% """ Define a class called "Vehicle". Write the special __init__ method for the class to take the following propoerties: - "color" - "max_speed_in_miles" Add a method "get_speed_in_kilometers" to the class, that returns the speed in km by converting the value in "max_speed_in_miles" """ class Vehicle(): def __init__(self, color, max_speed_in_miles): self.color = color self.max_speed_in_miles = max_speed_in_miles def get_speed_in_kilometers(self): return self.max_speed_in_miles*1.609344 v1 = Vehicle(color = 'red', max_speed_in_miles = 60) v1.get_speed_in_kilometers() #%% """ Write a class for a "Bus" as a subclass (inheritance) from the class "Vehicle". """ class Bus(Vehicle): pass b1 = Bus("white", 80) # %%
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help