midterm_1_uofzona

py

School

University Of Arizona *

*We aren’t endorsed by this school

Course

244

Subject

Computer Science

Date

Dec 6, 2023

Type

py

Pages

16

Uploaded by MajorTankBarracuda45

Report
#ODD ALL THE ODD NUMBER FROM A LIST def add_odd(list): sum = 0 for i in list: if i % 2 != 0: sum += i return sum list = [2,3,4,17,6] print(add_odd(list)) #-------------------------------------------------- #ODD THE EVEN DIGITS OF A NUMBER def even_sum(n): sum = 0 for i in str(n): if int(i) % 2 == 0: sum += int(i) return sum print(even_sum(4456)) #-------------------------------------------------- #RETURN THE LARGEST NUMBER AMONG 3 NUMBERS def find_max(a,b,c): max = 0 if a >= b and a >= c: max = a elif b > c: # b > a and c > a max = b else: max = c return max print(find_max(0,0,1)) #--------------------------------------------------- #COMPUTE AND RETURN THE SUM OF SQUARE UP TO THE GIVEN NUMBER N def sum_of_squares(n): sum = 0
for i in range(n): sum += (i**2) return sum print(sum_of_squares(100)) #---------------------------------------------------- #GIVEN A STRING, RETURN TRUE IF ITS PURE, OTHERWISE RETURN FALSE def is_pure(str1): alpha = "abcdefghijklmnopqrstuvwxyz" str2 = str1.lower() print(str2) for i in str2: if (i in alpha) == False: print(i) return False break for i in str2: if (i in alpha) == True: print(i) return True print(is_pure("GhJifJ")) #----------------------------------------------------- #COMPUTE THE AVERAGE OF NUMBERS IN A STRING def average(str1): sum = 0 count = 0 for i in str1: if i.isnumeric(): sum += int(i) count += 1 num = sum / count return num print(average("2gos6nds4")) #------------------------------------------------------ #RETURN THE GREATEST COMMON DEVISOR AMONG 3 NUMBERS def gcd(a,b,c): lowest = 0 if (a <= b) and (a <= c):
lowest = a elif b <= c: lowest = b else: lowest = c divisors = [] for x in range(1,lowest+1): if ((a % x == 0) and (b % x == 0) and (c % x == 0)): divisors.append(x) return max(divisors) print(gcd(12,16,14)) #------------------------------------------------------- #RETURN BASE 12 NUMBER OF A DECIMAL NUMBER def base12(x): result = " " while (x > 0): r = x % 12 if (x == 10): result = "A" + result elif (x == 11): result = "B" + result else: result = str(r) + result x = x // 12 return result print(base12(912)) #-------------------------------------------------------- #SEPERATE THE NUMBERS IN THE STRING AND ODD THEM def sum_of_num(str1): sum = 0 for i in str(str1): if i.isnumeric(): sum += int(i) return sum print(sum_of_num("asdk5ksd8dsk3"))
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
#-------------------------------------------------- # SUM OF ALTERNATIVE NUMBERS def num_sum(str1): sum = 0 list = str1.split(",") count = 0 for i in list: count += 1 if (count % 2 != 0): sum = float(i) + sum elif (count % 2 == 0): sum = sum - float(i) return sum print(num_sum("65.21,7.3,44,12.1,33.2")) print(num_sum("65.21,7.3,44,12.1,33.2,1,0")) print(num_sum("65.21,7.3,44,12.1,33.2,1,0,2.0")) print(num_sum("65.21,7.3,44,12.1,33.2,1,0,2.0,5.0")) # -------------------------------------------------- # SMALLEST NUMBER def smallest(a, b, c): min = 0 if a < b and a < c: min = a elif b < c: min = b else: min = c return min print(smallest(8, 8, 10)) # -------------------------------------------------- # REMOVE THE NUMBERS FROM THE STRING def number(str1): str2 = "" for i in str1:
if not (i.isnumeric()): str2 = str2 + str(i) return str2 print(number("h3y2jda")) # -------------------------------------------------- # LARGEST CUBE BEFORE THE GIVEN NUMBER def cube(n): largest = 0 x = 1 while (x ** 3) <= n: if (x ** 3) > largest: largest = (x ** 3) x += 1 return largest print(cube(100)) # -------------------------------------------------- # GIVE THE NO. OF PALINDROME NUMBERS SMALLER THAN 'N' def palindrome(n): count = 0 for i in range(n): # going from 0 to n-1 counting 0 as a palindrome if str(i)[0] == str(i)[len(str(i)) - 1]: count += 1 return count print(palindrome(44)) # -------------------------------------------------- # GIVEN A NUMBER PRINT TRUE IF THE NUMBER IS PERFECT AS # N FOR WHICH THE SUM OF DIVISORS IS 2N, N = 6 IS A PERFECT NUMBER SINCE WE HAVE # 1 + 2 + 3 + 6 = 12.
def num(n): sum = 0 for i in range(1, n + 1): if (n % i) == 0: sum += i if sum == (2 * n): return True else: return False print(num(6)) # -------------------------------------------------- #Write a program that examines three variables x , y , and z, and prints the largest odd number #among them. If none of them are odd, it should print a message to that effect. x = 888 y = 653 z = 34 max = 0 if (x >= 0) and (x % 2 == 1): max = x elif (y >= 0) and (y % 2 == 1): max = y elif (z >= 0) and (z % 2 == 1): max = z else: print("No numbers are odd") print(max) #-------------------------------------------------- #Write a program that asks the user to input 10 integers, and then prints the largest odd number #that was entered. If no odd number was entered, it should print a message to that effect. This is a #more general version of Question 1. For example of the integers were: 10, 9, 7, 12, 2, 5, 15, 100, 90, 60, #then the program would print 15 as the largest odd number.
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
x = 0 max = 0 while x < 10: number = int(input("Define Integer")) if (number > max) and (number % 2 == 1): max = number x = x + 1 if (max != 0): print(max, 'is the greatest number') else: print('No number is odd') #-------------------------------------------------- #Write a program that adds the amounts of money in a list. An example input is: #23 CAD, 345 CAD, 55 CAD. The output for this input is 423 CAD amount=[] a= int(input("Input number of Items: ")) for i in range(a): b=float(input("Input Amount: ")) amount.append(b) total=sum(amount) print("Sum of amount = ", total, 'CAD') #-------------------------------------------------- #Write a program that converts a given positive integer to its binary representation. #Hint: write the program using a for loop. To get the number of bits in a given integer, use the #function bit_length() in python. For example, for a = 983265982365, a.bit_length() will be 40. a=3 print(bin(a)) y =a.bit_length() for i in range(y): if a>= 2**(y-i-1): print(1, end="") a= a-2**(y-i-1) else: print(0, end="") print()
#-------------------------------------------------- #Let f(x) = x**5 + 52*x**3 - 29 be a function. This function has only one root in the real #numbers. Write a bisection search algorithm to find that root up to two digits of accuracy, i.e., #for epsilon = 0.01 as in the class. def ComputeFunction(x): return x ** 5 + 52 * x ** 3 - 29 a = 0 c = 2 b = a + (c - a)/2 epsilon = b - a count = 0 while epsilon > 0.01: if ComputeFunction(a) * ComputeFunction(b) < 0: a = a c = b b = a + (c - a)/2 else: a = b c = c b = a + (c - a)/2 epsilon = b - a count += 1 print(a) print("The number of iterations is: ", count) #-------------------------------------------------- #Solve question 2 using the Newton-Raphson method. Compare the number of iterations with #the bisection search. def ComputeFuntion(x): return x ** 5 + 52 * x ** 3 - 29 def ComputeDerivative(x): return 5 * x ** 4 + 156 * x ** 2 a = 0.1 b = 2 epsilon = b -a count = 0 while epsilon > 0.01:
b = a - (ComputeFunction(a) / ComputeDerivative(a)) epsilon = b - a a = b count += 1 print(a) print("The number of iterations is: ", count) #-------------------------------------------------- #You have written an essay that should be at least five pages long, but it is only 4.5 pages. You #ecide to use your new python skills to stretch it out by putting spaces between each letter #and the next. Write a function that takes a string and a number and prints out the string with #number of spaces between each pair of letters. #def spacedout(str, numSpaces) def spacedout(str, nmb): separator = " " * nmb return separator.join(str) s = input("input content") n = int(input("the number of of space = ")) print(spacedout(s,n)) #-------------------------------------------------- #Write a python program that returns the reverse of a given string. #'def reverse(str1)' def reverse(str): new = "" n = len(str) for i in range(n): new = new + str[n - i - 1] return new def isPalindrome(str): if reverse(str) == str: return (True) else: return(False) str = "Hello" print(reverse(str)) print(isPalindrome(str))
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
#-------------------------------------------------- #Write a recursive function that prints all the permutations of a given string. def returnPermutation(s): n = len(s) l = [] if n == 1: l.append(s) return l for i in range(n): c_0 = s[i] s_1 = s[:i] + s[i+1:] L = returnPermutation(s_1) for w in L: l.append(c_0 + w) return l print(returnPermutation("abc")) #-------------------------------------------------- #Given an integer n, write a python program that finds the digit with the highest number of #occurrences in n. For example, for n = 823778823478234768238 the program should return 8. #'def findHighestOccur(n)' def findHighestOccur(n): count = [0 for i in range(10)] for one in str(n): count[int(one)] += 1 max_occur = count.index(max(count)) return max_occur n = 983254682376587235235 print(findHighestOccur(n)) #-------------------------------------------------- #Assume that L is a list with one element. The element might be a number or it might be a list #of one element, where that element might be a number or a list of one element, and so on.
#Return the innermost number. You must use recursion. Your solution cannot use a loop. def innermost(x): #Defining a function to give the innermost element from the list if type(x[0]) == int: #Opening an 'if and else' statement return x[0] else: y = x[0] return innermost(y) l = [5] #Assigning 'l' a value print(innermost(l)) #printing the innermost element from the above element l = [[5]] #Assigning 'l' a value #-------------------------------------------------- #Assume that T is a tuple. Return a tuple which is the reverse of T. You must use recursion. #Your solution cannot use a loop or a list or a built-in reverse function. Hint: Reverse the tuple #starting at the second element, and concatenate to the end of that reversed tuple the first #element. #Test your program with the following: #(1, 2, 3, 4, 5) #('red', 'green', 'blue', 'yellow') def reverse(t): #Defining a function to reverse new = () if len(t) == 1: #Opening an 'if and else' statement new = t return new else: new = reverse(t[1:]) + t[:1] return new t = ("a", "b", "c") #Giving 't' a value print(reverse(t)) #printing the output
t = (1, 2, 3, 4, 5) #Giving 't' a value print(reverse(t)) #printing the output t = ('red', 'green', 'blue', 'yellow') #Giving 't' a value print(reverse(t)) #-------------------------------------------------- #Assume that sub and bigstring are strings. Return True if sub is part of bigstring, False #otherwise. You must use recursion. Your solution cannot use a string funtion or the 'in #operation'. Your solution cannot use a loop. Hint: check if sub is the beginning of bigstring, #and if not, consider the string obtained by removing the first letter from bigstring. def isSubstring(str, s): l1 = len(str) l2 = len(s) if l1 < l2: return False else: if str[:l2] == s: return True else: return isSubstring(str[1:], s) str = "I am a student" s = "I am" print(isSubstring(str, s)) #-------------------------------------------------- #Assume that phrase is a string. Return the number of words in phrase. Assume that words #are separated by one or more blanks. You are not allowed to use the built-in function split() def numberofwords(s): counter = 0 for c in s: if c == " ": counter += 1
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
counter += 1 return counter s = "A white cat and a black cow" print(numberofwords(s)) #-------------------------------------------------- #Return the first value of n such that the sum #Sum = 4/1 - 4/3 + 4/5 - 4/7 + ... + 4 * (-1)**(n+1)/(2n - 1) #is within epsilon of math.pi = 3.141592653589793. For example, if epsilon is 1, then return 1, #since 4 is within 1 of pi. If epsilon is 0.5 then return 2, since 4 is not within 0.5 of pi but 4 - 4/3 #= 2.67, and that is within 0.5 of pi epsilon = float(input("Enter Integer")) #Defining a variable b = 1 #Defining 'b' a value sum = 0 #Defining 'sum' a value pi = 3.14 #Giving the value to 'pi' while True: #Opening a while loop sum = sum + 4 * (-1) ** (b + 1) / (2 * b - 1) if abs(sum - pi) <= epsilon: #Opening an 'if' statement break b += 1 print(b) #-------------------------------------------------- #Find a given element in a list using a recursive function. The function is defined as #find(elm_list, x), where elm_list is the input list and x is the element to be found. The function #return the index of x if x is in the list, otherwise it returns -1. def find(elm_list, x): #Defining a function as find(elm_list, x) if (len(elm_list) == 1): if (elm_list[0] == x):
#Opening an 'if' statement to find x in the list return x #If 'x' is found it is returned else: #else return -1 #-1 is returned if (elm_list[0] == x): return x else: return find(elm_list[1:], x) elm_list = [1.2, 3, 555, 66, 6, 35, 345, 345, 78, 12341] x = 78 print(find(elm_list,x)) print(elm_list.index(x)) #-------------------------------------------------- #Write a function that computes the inner product of two lists. The inner product of two lists #L1 and L2 of length n is defined as L1[0] * L2[0] + L1[1] * L2[1] + ... + L1[n 1]. If #the lists are not of the same length, the function should return None. def innerProduct(l1, l2): #Defining a function as innerProduct len1 = len(l1) #Assigning the variable 'len1' a value len2 = len(l2) #Assigning the vairable 'len2' a value total = 0 counter = 0 if len1 == len2: #Opening an if statement, if the length of the two lists are equal for i in l1: #Opening a for loop total += (i * l2 [counter]) counter += 1 print(total) return total else: return None print(innerProduct([8.17, 4.99, 16.56, 7.31, 0.21, 16.18, 13.75,
11.28, 4.3, 17.79], #Giving the lists to print the product [17.68, 1.19, 2.64, 13.01, 8.5, 15.04, 0.3, 18.72, 4.58, 9.66])) #-------------------------------------------------- #Write a function that extract a number from a string. The string can contain any character. #The number you return is the concatenation of all the digits you find in the string. For #example, the extracted number from the string is 823755. str = "1ksdj4sdf>R?387BDYGrrf%44@2" #Assigning the values to the variable print("Given String : " + str) #Printing the given string num = "" for c in str: #Opening a for loop, to find a digit in the given string if c.isdigit(): #Checking digits in the stirng num = num + c print("Extracted Numbers : " + num) #-------------------------------------------------- #Write a function that computes the sum #1 + 1 / 2**2 + 1 / 3**2 + ... + 1 / n**2 #for a given integer n. For large n, this sum converges to pi**2 / 6 where pi = #3.141592653589793. How large should n be for the sum to be within distance 0.001 of pi**2 / 6? def equation(n): #Defining a function as equation sum = 0 for i in range(n): #Opening a for loop sum += 1/(i+1)**2 #If sum is equal to 1/(i+1)**2 return sum #Return sum def piEquation(): #Defining a function as 'piEquation' pi = 3.141592653589793
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
#Assigning the variable 'pi' a value total = pi**2/6 return total #Returning total def nFind(): #Defining a function as 'nFind' n = 1 #Assigning 'n' a value of 1 epsilon = 0.001 #Assigning epsilon value while True: #Opening a while loop if abs(equation(n) - piEquation()) <= epsilon: #Opening an if statement break n += 1 return n #Returning n print(nFind()) #--------------------------------------------------