lab_1_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

3

Uploaded by suckmyassbuddy on coursehero.com

""" **CIVE 2350: Numerical Methods for Civil Engineers** **Lab A: Learning Python** """ # %% Question `area_triangle` """ Write a program to return the area of a triangle with sides `a` and `b`. Example: Input : 2, 3 Output : 3 """ def area_triangle(a, b): area = (a * b)/2 return area # Test the function area_triangle(2, 10) # %% Question `swap_list` """ Write a program to swap first and last element of a list. Examples: Input : [12, 35, 9, 56, 24] Output : [24, 35, 9, 56, 12] Input : [1, 2, 3] Output : [3, 2, 1] """ def swap_list(input_list): output_list = input_list.copy() output_list [0] = input_list[-1] output_list[-1] = input_list[0] return output_list # Test the function swap_list([1, 2, 3, 4, 5]) # %% get_max ''' Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python. (It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise.) ''' def get_max(m,n): if m < n: return n else: return m get_max(6,5) # %%
''' Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I". ''' def get_reverse_string(input): output = input [::-1] return(output) get_reverse_string('I am testing') # %% """ With a given integer number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). Example: Input: 8 Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} """ def get_dict_series(x): my_num = int(x) my_dict = dict() for elem in range(1,my_num+1): my_dict[elem] = elem*elem return(my_dict) get_dict_series(8) # %% """ Write a function that accepts a sentence and returns the number of letters and digits as a string with format "x letters and x digits" Hint: You can use `.isalpha()` and `.isdigit()` Example: Input: "hello world! 123" Output: "10 letters and 3 digits" """ def count_letters_and_digits(x): letters = 0 numbers = 0 strl = str(x) for i in strl: if i.isalpha(): letters+=1 elif i.isdigit(): numbers+=1 else: pass return (str(letters) + ' letters ' + 'and ' + str(numbers) + ' digits') count_letters_and_digits("hello world! 123") #%% """ Write a method which takes 2 digits, X,Y as input and generates a 2-dimensional
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