Successfully reported this slideshow.

×

# ECE-PYTHON.docx

Engineering https://uii.io/YEkV0c

Engineering https://uii.io/YEkV0c

## More Related Content

### ECE-PYTHON.docx

1. 1. 1. a. Write a program to get the list of even numbers upto a given number # Python program to print Even Numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93] # iterating each number in list for num in list1: # checking condition if num % 2 == 0: print(num, end=" ") Output 10 4 66 b. Write a program to get the ASCII distance between two characters print ("Please enter the String: ", end = "") string = input() string_length = len(string) for K in string: ASCII = ord(K) print (K, "t", ASCII) Output: Please enter the String: "JavaTpoint# " 34 J 74 a 97 v 118 a 97 T 84 p 112 o 111 i 105 n 110 t 116 # 35 c. Write a program to get the binary form of a given number. n=int(input("Enter a number: ")) a=[] while(n>0): dig=n%2 a.append(dig) n=n//2 a.reverse() print("Binary Equivalent is: ") for i in a: print(i,end=" ")
2. 2. d. Write a program to convert base 36 to octal def convert_to_other_bases(decimal): # Convert to binary binary = "{0:b}".format(decimal) # Convert to octal octal = "{0:o}".format(decimal) # Convert to hexadecimal hexadecimal = "{0:x}".format(decimal) # Print results print(f"{decimal} in binary: {binary}") print(f"{decimal} in octal: {octal}") print(f"{decimal} in hexadecimal: {hexadecimal}") convert_to_other_bases(55) Output 55 in binary: 110111 55 in octal: 67 55 in hexadecimal: 37
3. 3. 2 a. Write a program to get the number of vowels in the input string (No control flow allowed) string=raw_input("Enter string:") vowels=0 for i in string: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowels=vowels+1 print("Number of vowels are:") print(vowels) b. Write a program to check whether a given number has even number of 1's in its binary representation (No control flow, thenumbercanbein any base) class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ n = str(bin(n)) print(n) one_count = 0 for i in n: if i == "1": one_count+=1 return one_count num = "000000101101" ob1 = Solution() print(ob1.hammingWeight(num)) Input num = "000000101101" Output 4 c. Write a program to sort given list of strings in the order of their vowel counts. def Check_Vow(string, vowels): # The term "casefold" has been used to refer to a method of ignoring cases.
4. 4. string = string.casefold() count = {}.fromkeys(vowels, 0) # To count the vowels for character in string: if character in count: count[character] += 1 return count # Driver Code vowels = 'aeiou' string = "Hi, I love eating ice cream and junk food" print (Check_Vow(string, vowels)) Output: {'a': 3, 'e':3 , 'i':2 , 'o':3 , 'u':1}
5. 5. 3 a. Write a program to return the top 'n' most frequently occurring chars and their respective counts. E.g. aaaaaabbbbcccc, 2 should return [(a5) (b 4) def top_chars(input, n): list1=list(input) list3=[] list2=[] list4=[] set1=set(list1) list2=list(set1) def count(item): count=0 for x in input: if x in input: count+=item.count(x) list3.append(count) return count list2.sort(key=count) list3.sort() list4=list(zip(list2,list3)) list4.reverse() list4.sort(key=lambda list4: ((list4[1]),(list4[0])), reverse=True) return list4[0:n] pass o/p:[('a', 2), ('c', 1)] b. Write a program to convert a given number into a given base. # Python program to convert any base # number to its corresponding decimal # number # Function to convert any base number # to its corresponding decimal number def any_base_to_decimal(number, base): # calling the builtin function # int(number, base) by passing # two arguments in it number in # string form and base and store # the output value in temp temp = int(number, base) # printing the corresponding decimal # number print(temp) # Driver's Code if __name__ == '__main__' : hexadecimal_number = '1A' base = 16 any_base_to_decimal(hexadecimal_number, base) Output: 26
6. 6. 4 a. Write a program to convert a given iterable into a list. (Using iterator # Sample built-in iterators # Iterating over a list print("List Iteration") l = ["geeks", "for", "geeks"] for i in l: print(i) # Iterating over a tuple (immutable) print("nTuple Iteration") t = ("geeks", "for", "geeks") for i in t: print(i) # Iterating over a String print("nString Iteration") s = "Geeks" for i in s : print(i) # Iterating over dictionary print("nDictionary Iteration") d = dict() d['xyz'] = 123 d['abc'] = 345 for i in d : print("%s %d" %(i, d[i])) Output : List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345
7. 7. b. Write a program to implement user defined map() function # Python program to demonstrate working # of map. # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) Output : [2, 4, 6, 8] c. Write a program to generate an infinite number of even numbers (Use generator) def number_gen(start=0, step=1): while True: yield start start += step d. Write a program to get a list of even numbers from a given list of numbers. (use only comprehensions Python program to print Even Numbers in given range start = int(input("Enter the start of range: ")) end = int(input("Enter the end of range: ")) # iterating each number in list for num in range(start, end + 1): # checking condition if num % 2 == 0: print(num, end=" ") Output: Enter the start of range: 4 Enter the end of range: 10 3 6 8 10
8. 8. 5 Write a program to implement round robin Python3 program for implementation of # RR scheduling # Function to find the waiting time # for all processes def findWaitingTime(processes, n, bt, wt, quantum): rem_bt = [0] * n # Copy the burst time into rt[] for i in range(n): rem_bt[i] = bt[i] t = 0 # Current time # Keep traversing processes in round # robin manner until all of them are # not done. while(1): done = True # Traverse all processes one by # one repeatedly for i in range(n): # If burst time of a process is greater # than 0 then only need to process further if (rem_bt[i] > 0) : done = False # There is a pending process if (rem_bt[i] > quantum) : # Increase the value of t i.e. shows # how much time a process has been processed t += quantum # Decrease the burst_time of current # process by quantum rem_bt[i] -= quantum # If burst time is smaller than or equal # to quantum. Last cycle for this process else: # Increase the value of t i.e. shows # how much time a process has been processed t = t + rem_bt[i] # Waiting time is current time minus # time used by this process wt[i] = t - bt[i] # As the process gets fully executed # make its remaining burst time = 0 rem_bt[i] = 0 # If all processes are done if (done == True): break # Function to calculate turn around time def findTurnAroundTime(processes, n, bt, wt, tat):
9. 9. # Calculating turnaround time for i in range(n): tat[i] = bt[i] + wt[i] # Function to calculate average waiting # and turn-around times. def findavgTime(processes, n, bt, quantum): wt = [0] * n tat = [0] * n # Function to find waiting time # of all processes findWaitingTime(processes, n, bt, wt, quantum) # Function to find turn around time # for all processes findTurnAroundTime(processes, n, bt, wt, tat) # Display processes along with all details print("Processes Burst Time Waiting", "Time Turn-Around Time") total_wt = 0 total_tat = 0 for i in range(n): total_wt = total_wt + wt[i] total_tat = total_tat + tat[i] print(" ", i + 1, "tt", bt[i], "tt", wt[i], "tt", tat[i]) print("nAverage waiting time = %.5f "%(total_wt /n) ) print("Average turn around time = %.5f "% (total_tat / n)) # Driver code if __name__ =="__main__": # Process id's proc = [1, 2, 3] n = 3 # Burst time of all processes burst_time = [10, 5, 8] # Time quantum quantum = 2; findavgTime(proc, n, burst_time, quantum) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10) Output PN BT WT TAT 1 10 13 23 2 5 10 15 3 8 13 21 Average waiting time = 12, Average turn around time = 19.6667
10. 10. 6 a. Write a program to sort words in a file and put them in another file. The output file shouldhave only lower case words, so any upper case words from source must be lowered. (Handle exceptions open both files with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile: # read content from first file for line in firstfile: # append content to second file secondfile.write(line) b. Write a program return a list in which the duplicates are removed and the items are sorted from a given input list of strings. Python 3 code to demonstrate # removing duplicated from list # using set() # initializing list test_list = [1, 5, 3, 6, 3, 5, 6, 1] print ("The original list is : " + str(test_list)) # using set() # to remove duplicated # from list test_list = list(set(test_list)) # printing list after removal # distorted ordering print ("The list after removing duplicates : " + str(test_list)) Output The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1, 3, 5, 6]
11. 11. 7.a. Write a programto test whether given strings are anagrams are not s1=raw_input("Enter first string:") s2=raw_input("Enter second string:") if(sorted(s1)==sorted(s2)): print("The strings are anagrams.") else: print("The strings aren't anagrams.") b. Write a program to implement left binary search. def binarySearchAppr (arr, start, end, x): # check condition if end >= start: mid = start + (end- start)//2 # If element is present at the middle if arr[mid] == x: return mid # If element is smaller than mid elif arr[mid] > x: return binarySearchAppr(arr, start, mid-1, x) # Else the element greator than mid else: return binarySearchAppr(arr, mid+1, end, x) else: # Element is not found in the array return -1 arr = sorted(['t','u','t','o','r','i','a','l']) x ='r' result = binarySearchAppr(arr, 0, len(arr)-1, x) if result != -1: print ("Element is present at index "+str(result)) else: print ("Element is not present in array") Element is present at index 4
12. 12. 8. a. writea class Person with attributes name, age, weight (kgs), height (ft) and takes them through the constructor and exposes a method get_bmi_result() which returns one of "underweight", "healthy", "obese" # asking for input from the users the_height = float(input("Enter the height in cm: ")) the_weight = float(input("Enter the weight in kg: ")) # defining a function for BMI the_BMI = the_weight / (the_height/100)**2 # printing the BMI print("Your Body Mass Index is", the_BMI) # using the if-elif-else conditions if the_BMI <= 18.5: print("Oops! You are underweight.") elif the_BMI <= 24.9: print("Awesome! You are healthy.") elif the_BMI <= 29.9: the_print("Eee! You are over weight.") else: print("Seesh! You are obese.") Output: Enter the height in cm: 160 Enter the weight in kg: 61 Your Body Mass Index is 23.828124999999996 Awesome! You are healthy. Next Topi cb. Write a program to convert the passed in positive integer number into its prime factorization form import math # Below function will print the # all prime factor of given number def prime_factors(num): # Using the while loop, we will print the number of two's that divide n while num % 2 == 0: print(2,) num = num / 2 for i in range(3, int(math.sqrt(num)) + 1, 2): # while i divides n , print i ad divide n while num % i == 0: print(i,) num = num / i
13. 13. if num > 2: print(num) # calling function num = 200 prime_factors(num) Output: 2 2 2 5 5