Team Ai
Datasetpublic

GunA-SD/bash_code

This dataset is a collection of bash programs from various GitHub repositories and open source projects. The dataset might contain harmful code.

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
9likes68downloads
INS_CODE_PY.txt43009 linesDownload Raw Back to root
1# write a python program to add two numbers2num1 = 1.53num2 = 6.34sum = num1 + num25print(f'Sum: {sum}')6 7 8# write a python function to add two user provided numbers and return the sum9def add_two_numbers(num1, num2):10    sum = num1 + num211    return sum12 13 14# write a program to find and print the largest among three numbers15num1 = 1016num2 = 1217num3 = 1418if (num1 >= num2) and (num1 >= num3):19   largest = num120elif (num2 >= num1) and (num2 >= num3):21   largest = num222else:23   largest = num324print(f'largest:{largest}')25 26 27# write a program to find and print the smallest among three numbers28num1 = 1029num2 = 1230num3 = 1431if (num1 <= num2) and (num1 <= num3):32   smallest = num133elif (num2 <= num1) and (num2 <= num3):34   smallest = num235else:36   smallest = num337print(f'smallest:{smallest}')38 39 40# Write a python function to merge two given lists into one41def merge_lists(l1, l2):42    return l1 + l243 44 45# Write a program to check whether a number is prime or not46num = 33747 48if num > 1:49   for i in range(2, num//2 + 1):50       if (num % i) == 0:51           print(num,"is not a prime number")52           print(f"{i} times {num//i} is {num}")53           break54   else:55       print(f"{num} is a prime number")56 57else:58   print(f"{num} is not a prime number")59 60 61# Write a python function that prints the factors of a given number62def print_factors(x):63   print(f"The factors of {x} are:")64   for i in range(1, x + 1):65       if x % i == 0:66           print(i)67 68 69# Write a program to find the factorial of a number70num = 1371factorial = 172 73if num < 0:74   print("No factorials for negative numbers!")75 76elif num == 0:77   print("The factorial of 0 is 1")78 79else:80   for i in range(1,num + 1):81       factorial = factorial*i82   print(f"The factorial of {num} is {factorial}")83 84 85# Write a python function to print whether a number is negative, positive or zero86def check_pnz(num):87    if num > 0:88       print("Positive number")89 90    elif num == 0:91       print("Zero")92 93    else:94       print("Negative number")95 96 97# Write a program to print the multiplication table of a given number98 99num = 9100for i in range(1, 11):101   print(f"{num} x {i} = {num*i}")102 103 104# Write a python function to print powers of 2, for given number of terms105def two_power(terms):106    result = list(map(lambda x: 2 ** x, range(terms)))107 108    print(f"The total terms are: {terms}")109    for i in range(terms):110       print(f"2^{i} = {result[i]}")111 112 113# Write a program to filter the numbers in a list which are divisible by a given number114my_list = [11, 45, 74, 89, 132, 239, 721, 21]115 116num = 3117result = list(filter(lambda x: (x % num == 0), my_list))118 119print(f"Numbers divisible by {num} are {result}")120 121 122# Write a python function that returns the sum of n natural numbers123def sum_natural(num):124    if num < 0:125       print("Please enter a positive number!")126    else:127       sum = 0128       while(num > 0):129           sum += num130           num -= 1131       return num132 133 134# Write a program to swap first and last elements in a list135my_list = [1, 2, 3, 4, 5, 6]136my_list[0], my_list[-1] = my_list[-1], my_list[0]137 138 139# Write a python function to find the area of a circle, whose radius is given140def findArea(r):141    PI = 3.142142    return PI * (r*r)143 144 145# Write a program to print the sum of squares of first n natural numbers146n = 21147sum_n = 0148for i in range(1, n+1):149    sum_n += i**2150print(sum_n)151 152 153# Write a program to print the length of a list154my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]155 156print(len(my_list))157 158 159# Write a pythno function to print the length of a given tuple160my_tuple = (1, 2, 3, 4, 5, 6, 7, 8)161 162print(len(my_tuple))163 164 165# Write a python function to print the elements of a given list, one element in a line166def custom_print(l):167    for _ in l:168        print(_)169 170 171# Write a python function to remove all the odd numbers from a list and return the remaining list172def remove_odd(my_list):173    result = list(filter(lambda x: (x % 2 == 0), my_list))174    return result175 176 177# Write a python function to remove all the even numbers from a list and return the remaining list178def remove_even(my_list):179    result = list(filter(lambda x: (x % 2 != 0), my_list))180    return result181 182 183# Write a function that takes two lists as input and returns a zipped list of corresponding elements184def zip_list(list1, list2):185    return list(zip(list1, list2))186 187 188# Write a program to to print the contents of a given file189file_name = 'temp.txt'190with open(file_name, 'r') as f:191    print(f.read())192 193 194# Write a functin that returns the LCM of two input numbers195def lcm(a, b):196    if a>b:197        min_ = a198    else:199        min_ = b200    while True:201        if min_%a==0 and min_%b==0:202            break203        min_+=1204    return min_205 206 207# Write a program to print the unique elements in a list208my_list = [1, 2, 4, 5, 2, 3, 1, 5, 4, 7, 8, 2, 4, 5, 2, 7, 3]209print(set(my_list))210 211 212# Write a function that returns the sum of digits of a given number213def digisum(num):214    sum_=0215    while num > 0:216        dig = num % 10217        sum_+=dig218        num//=10219    return sum_220 221 222# Write a program to check and print whether a number is palindrome or not223num = 12321224temp = num225rev = 0226while num > 0:227    dig = num % 10228    rev = rev*10 + dig229    num//=10230if temp==rev :231    print("The number is a palindrome!")232else:233    print("The number isn't a palindrome!")234 235 236# Write a function that prints a given value, n number of times237def print_n(val, n):238    for _ in range(n):239        print(val)240 241 242# Write a function to find the area of sqaure243def square_area(a):244    return a*a245 246 247# Write a function to find the perimeter of a square248def square_perimeter(a):249    return 4*a250 251 252# Write a function to find the area of rectangle253def rectangle_area(l, b):254    return l*b255 256 257# Write a function to find the permieter of a rectangle258def rectangle_perimeter(l, b):259    return 2*(l+b)260 261 262# Write a python function to find the area of a circle, whose radius is given263def findArea(r):264    PI = 3.142265    return PI * (r*r)266 267 268# Write a function to calculate and return electricity bill. Units used are given. Price per unit is fixed and is increased after 750 units.269def calc_elect_bill(units):270    if units > 0:271        if units <= 750:272            return 5*units273        else:274            return 5*(750) + 7*(units-750)275 276    else:277        return -1278 279 280# Write a function to return day of a week, given the number281def give_day(n):282    day_dict = {1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday'}283    return day_dict[n]284 285 286# Write a program to calculate and print the volume of a cylender287r = 3288h = 5289pi = 3.14290volume = pi*(r**2)*h291print(volume)292 293 294# Write a function to calculate and return the average of input numbers295def calc_avg(*args):296    if len(args) > 0:297        return sum(args)/len(args)298    return None299 300 301# Write a function to calculate compound interest, given p, r, t302def comp_int(p, r, t):303    amount = p * (1 + (r/100))**t304    interest = amount - p305    return interest306 307 308# Write a function to calculate simple interest, given p, r, t309def simp_int(p, r, t):310    interest = (p*r*t)/100311    return interest312 313 314# Write a program to print a given string, replacing all the vowels with '_'315st = "Where is this going? Could you please help me understand!"316vowels = "AEIOUaeiou"317 318for v in vowels:319    st = st.replace(v, '_')320 321print(st)322 323 324# Write a functio to check whether a number if perfect or not325def is_perfect(n):326    sum_ = 0327    for i in range(1, n//2 + 1):328        if n%i == 0:329            sum_+=i330    if sum_ == n:331        return True332    return False333 334 335# Write a function that returns seperate lists of positive and negative numbers from an input list336def seperate_pn(l):337    pos_list = []338    neg_list = []339    for _ in l:340        if _<0:341            neg_list.append(_)342        else:343            pos_list.append(_)344    return pos_list, neg_list345 346 347# Write a program to find and print the area of a triangle, whose hight and width are given.348h = 12349w = 11350area = 0.5*h*w351print(area)352 353 354# Write a function to find acceleration, given u, v and t355def acc(u, v, t):356    return (v-u)/t357 358 359# Write a lambda function to multiply two numbers360multiply = lambda a, b: a*b361 362 363# Write a lambda function to add two numbers364add = lambda a, b: a+b365 366 367# Write a lambda function that gives True if the input number is even otherwise False368even = lambda a: True if a%2 == 0 else False369 370 371# Write a lambda function to to give character grom it's ascii value372ascii = lambda a: chr(a)373 374 375# Write a lambda function to that gives the number of digits in a number376dig_cnt = lambda a: len(str(a))377 378 379# Write a program to to check if a triangle is valid or not, given it's all three angles380def is_valid_triangle_angle(a, b c):381    if a+b+c == 180:382        return True383    return False384 385 386# Write a program to to check if a triangle is valid or not, given it's all three sides' length387def is_valid_triangle_length(a, b c):388    if a>0 and b>0 and c>0:389        if a+b > c and a+c > b and b+c > a:390            return True391    return False392 393 394# Write a lambda functio that gives the word count in a statement.395count_word = lambda s: len(s.split(' '))396 397 398# Write a program to extract and print digits of a number in reverse order. The number is input from user.399num = int(input("Enter a number with multiple digit: "))400n=0401while num>0:402    a = num%10403    num = num - a404    num = num/10405    print(int(a),end="")406    n = n + 1407 408 409# Write a function that takes in height(m) and weight(kg), calculates BMI and prints the comments410def bmi(height: "Meters", weight: "Kgs"):411    bmi = weight/(height**2)412    print("Your BMI is: {0} and you are ".format(bmi), end='')413    if ( bmi < 16):414       print("severely underweight.")415    elif ( bmi >= 16 and bmi < 18.5):416       print("underweight.")417    elif ( bmi >= 18.5 and bmi < 25):418       print("healthy.")419    elif ( bmi >= 25 and bmi < 30):420       print("overweight.")421    elif ( bmi >=30):422       print("severely overweight.")423 424 425# Write a program that prints all the alphabets in a string and skips all other characters426string = "$john.snow#@Got.bad_ending/com"427for ch in string:428    if (ch>='A' and ch<='Z') or (ch>='a' and ch<='z'):429        print(ch, end='')430    else:431        pass432 433 434# Write a function that takes number of disks in tower of hanaoi problem and returns the minimum number of steps required435def hanoi(x):436    if x == 1:437        return 1438    else:439        return 2*hanoi(x-1) + 1440 441 442# Write a lambda function to convert centimeters to inches443cm_to_inch = lambda x: x/2.54444 445 446# Write a lambda function to find the union of two lists447union = lambda a, b: list(set(a)|set(b))448 449 450# Write a lambda function to find the intersection of two lists451intersection = lambda a, b: list(set(a)&set(b))452 453 454# Write a program that adds the square of two numbers and prints it455a = 32456b = 21457 458result = a**2 + b**2459print(result)460 461 462# Write a python function to concat the input strings and there's also a choice for seperator463def con_str(*args, sep = ' '):464  return sep.join(args)465 466 467# Write a program to print all the even numbers in a range468r1, r2 = 1, 28469 470for _ in range(r1, r2+1):471  if _%2 == 0:472    print(_)473 474 475# write a python program to sort dictionary items476dict1 = {'car': [7, 6, 3],477             'bike': [2, 10, 3],478             'truck': [19, 4]}479 480print(f"The original dictionary is : {str(dict1)}")481 482res = dict()483for key in sorted(dict1):484    res[key] = sorted(dict1[key])485 486print(f"The sorted dictionary : {str(res)}")487 488 489# write a program to display date and time490import datetime491now = datetime.datetime.now()492time= now.strftime("%Y-%m-%d %H:%M:%S")493print(f"Current date and time : {time}")494 495 496# write a program to return the absolute value497num = -10498print(f'Absolute of {num} is {abs(num)}')499 500 501# write a python program to check the length of list502sample_list = ['a','b','c']503print(f'length of sample_list is {len(sample_list)}')504 505 506# write a Python program to calculate number of days between two dates.507from datetime import date508f_date = date(2019, 4, 15) # YYYY/MM/DD509l_date = date(2020, 4, 15) # YYYY/MM/DD510delta = l_date - f_date511print(f'No of days between {f_date} and {l_date} is:{delta.days}')512 513 514# write a Python program to convert Python objects into JSON strings.515import json516python_dict =  {"name": "David", "age": 6, "class":"I"}517json_dict = json.dumps(python_dict, sort_keys=True, indent=4)518print(f"json dict : {json_dict}")519 520 521# write a Python program to get the largest number from a list522def max_num_in_list(list):523    max = list[0]524    for a in list:525        max = a if a > max else max526    return max527print(f'max_num_in_list [1, 10, -8, 0], Ans:{max_num_in_list([1, 10, -8, 0])}')528 529 530# write a Python program to remove duplicates from a list531a = [10,20,30,20,10,50,60,40,80,50,40]532 533dup_items = set()534uniq_items = []535for x in a:536    if x not in dup_items:537        uniq_items.append(x)538        dup_items.add(x)539 540print(f'dup_items:{dup_items}')541 542 543# write a Python program to flatten a shallow list544import itertools545original_list = [[2,4,3],[1,5,6], [9], [7,9,0], [1,2,3,4]]546new_merged_list = list(itertools.chain(*original_list))547print(f'merged list/flatten:{new_merged_list}')548 549 550# write a Python program to create multiple list551obj = {}552for i in range(1, 11):553    obj[str(i)] = []554print(f'create multiple list:{obj}')555 556 557# write a Python program to merge two dictionaries558d1 = {'a': 100, 'b': 200}559d2 = {'x': 300, 'y': 200}560d = d1.copy()561d.update(d2)562print(f'merge two dictionaries:{d}')563 564 565# write a Python program to Sum all the items in a dictionary566my_dict = {'data1':100,'data2':-54,'data3':247}567print(f'Sum all the items in a dictionary:{sum(my_dict.values())}')568 569 570# write a python program to Get the maximum and minimum value in a dictionary571my_dict = {'x':500, 'y':5874, 'z': 560}572key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))573key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))574 575print('Maximum Value in a dictionary: ',my_dict[key_max])576print('Minimum Value in a dictionary: ',my_dict[key_min])577 578 579# write a python program to do nothing for a condition580if 1 + 1 == 2:581    pass # Nothing582 583 584# write a python program to make use of enumerate method585for count, value in enumerate(obj):586    print(count, value)587 588 589# write a python program to make use of setdefault for missing dictionary keys590a_dict = {'a':1}591a_dict.setdefault('b',2)592print(f'After appending with new value:{a_dict}')593 594 595# write a python program to make use of maps596def square(number):597    return number ** 2598 599numbers = [1, 2, 3, 4, 5]600 601squared = map(square, numbers)602 603print(f'mapped numbers:{list(squared)}')604 605 606# write a python program to make use of modulo operator607print(f'modulo 15 % 4: Sol->{15 % 4}')608 609 610# write a python program to explain enclosing and global scope611x = 'global'612 613def f():614    x = 'enclosing'615    def g():616        print(x)617    g()618    return x619obj1 = f()620print('explain global scope:',obj1)621 622 623# write a python program to expain local and global scope624def f1():625    x = 'enclosing'626    def g():627        x = 'local'628        return x629    x=g()630    return x631obj2 = f1()632print('explain local scope:',obj2)633 634 635# write a python program to make use of regular expression for matching636import re637print('Find the characters in the given string:',re.findall(r'[a-z]+', '123FOO456', flags=re.IGNORECASE))638 639 640# write a python program to make use of regular expression for matching641s = 'foo123bar'642m = re.findall('123', s)643print('find the number position:',m)644 645 646# write a python program to convert lower string to UPPERCASE647a = 'string'648print(f'convert lowercase to uppercase:{a.upper()}')649 650 651# write a python program to convert uppercase string to lower652a = 'STRING'653print(f'convert lowercase to uppercase:{a.lower()}')654 655 656# write a Python Program to Find the Square Root657num = 8658 659num_sqrt = num ** 0.5660print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))661 662 663# write a Python Program to Convert Kilometers to Miles664kilometers = 10.0665 666conv_fac = 0.621371667 668miles = kilometers * conv_fac669print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))670 671 672# write a Python Program to Convert Celsius To Fahrenheit673celsius = 37.5674fahrenheit = (celsius * 1.8) + 32675print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))676 677 678# write a Python Program to Check if a Number is Positive, Negative or 0679num = 10680if num > 0:681   print("Positive number")682elif num == 0:683   print("Zero")684else:685   print("Negative number")686 687 688# Python Program to Check if a Number is Odd or Even689num = 100690if (num % 2) == 0:691   print("{0} is Even".format(num))692else:693   print("{0} is Odd".format(num))694 695 696# Python Program to Display the multiplication Table697num = 12698for i in range(1, 11):699   print(num, 'x', i, '=', num*i)700 701 702# write a program for Rolling the dices703import random704min = 1705max = 6706 707print("Rolling the dices...and the values are",random.randint(min, max))708print("Rolling the dices...and the values are",random.randint(min, max))709 710 711# write a python program to calculate the average712list1 = [1,3,4,5]713average = (sum(list1)) / len(list1)714print(f"the average score is:  {average} ")715 716 717# write a python program to print reverse list718print(f'reverese the given list elements:{list1[::-1]}')719 720 721# write a python program for creating the thread722import threading723from threading import Thread724import time725 726def print_time( threadName, delay):727    count = 0728    while count < 5:729        time.sleep(delay)730        count += 1731        print("%s: %s" % ( threadName, time.ctime(time.time()) ))732 733# try:734#     Thread(target=print_time, args=("Thread-1", 2, )).start()735#     Thread(target=print_time, args=("Thread-1", 4, )).start()736# except:737#     print("Error: unable to start thread")738 739 740# write a python program to check a num is less than 1000741def near_thousand(n):742      return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))743print('near to 1000',near_thousand(1000))744print('near to 1300',near_thousand(1300))745 746 747# write a python program to convert lower case to upper for list of elements748x = ['ab', 'cd']749for i in x:750    print(i.upper())751 752 753# write a python program to break when the num is perfectly divisible754i = 1755while True:756    if i%3 == 0:757        break758    print(i)759 760    i+= 1761 762 763# write a python program to check name exists in given list764names1 = ['Amir', 'Bala', 'Chales']765for n in names1:766    name = n.lower()767    if 'amir' == name:768        print('Yes name exists:',name)769    else:770        print('No')771 772 773# write a python program to print a matrix as output774matrix = [[1, 2, 3, 4],775       [4, 5, 6, 7],776       [8, 9, 10, 11],777       [12, 13, 14, 15]]778 779for i in range(0, 4):780    print(matrix[i][1], end = " ")781 782 783# write a python program to calculate the time taken784from time import localtime785 786activities = {8: 'Sleeping',787              9: 'Commuting',788              17: 'Working',789              18: 'Commuting',790              20: 'Eating',791              22: 'Resting' }792 793time_now = localtime()794hour = time_now.tm_hour795 796for activity_time in sorted(activities.keys()):797    if hour < activity_time:798        print (activities[activity_time])799        break800else:801    print ('Unknown, AFK or sleeping!')802 803 804# write a python program to search a key in the text file805fname = 'sample.txt'806l='keyword' # Enter letter to be searched807k = 0808 809with open(fname, 'r') as f:810    for line in f:811        words = line.split()812        for i in words:813            if(i==l):814                k=k+1815print("Occurrences of the letter:",k)816 817 818# write a python program to expalin list comprehension and print alternative values819t = (1, 2, 4, 3, 8, 9)820print([t[i] for i in range(0, len(t), 2)])821 822 823# write a python program to sort tuple values824a=(2,3,1,5)825tuple_sorted = sorted(a)826print(tuple(tuple_sorted))827 828 829# write a python program to multiple two list values830l1=[1,2,3]831l2=[4,5,6]832print('multiply two list values:',[x*y for x in l1 for y in l2])833 834 835# write the list comprehension to pick out only negative integers from a given list โ€˜lโ€™.836l1=[1,2,3,-4,-8]837 838print('negative integers:', [x for x in l1 if x<0])839 840 841# write a python program to convert all list elements to upper case842s=["pune", "mumbai", "delhi"]843print([(w.upper(), len(w)) for w in s])844 845 846# write a python program to expalin python zip method847l1=[2,4,6]848l2=[-2,-4,-6]849for i in zip(l1, l2):850	print(i)851 852 853# write a python program to add two list using python zip method854l1=[10, 20, 30]855l2=[-10, -20, -30]856l3=[x+y for x, y in zip(l1, l2)]857print('added two list:',l3)858 859 860# write a list comprehension for number and its cube861l=[1, 2, 3, 4, 5, 6, 7, 8, 9]862print([x**3 for x in l])863 864 865# write a list comprehension for printing rows into columns and vv866l=[[1 ,2, 3], [4, 5, 6], [7, 8, 9]]867print([[row[i] for row in l] for i in range(3)])868 869 870# write a list comprehension for printing rows into columns and vv871def unpack(a,b,c,d):872    print(a+d)873x = [1,2,3,4]874unpack(*x)875 876 877# write a python program to use python lambda function878lamb = lambda x: x ** 3879print(lamb(5))880 881 882# write a python program to multiply a string n times883a = 'python'884print(a*5)885 886 887# write a python to check two numbers are greater than or equal or less than888def maximum(x, y):889    if x > y:890        return x891    elif x == y:892        return 'The numbers are equal'893    else:894        return y895 896print(maximum(2, 3))897 898 899# write a python to dict to zip and print as dictionary elements in original form900a={"a":1,"b":2,"c":3}901b=dict(zip(a.values(),a.keys()))902print(b)903 904 905# write a python program to delete an dictionary element906a={1:5,2:3,3:4}907a.pop(3)908print(a)909 910 911# write a python program to check two dictionary are equal or not912d1 = {"john":40, "peter":45}913d2 = {"john":466, "peter":45}914d1 == d2915 916 917# write a python program to print only dictionary keys as list918d = {"john":40, "peter":45}919print(list(d.keys()))920 921 922#write a python program to check two lists are equal or not923a=[1, 4, 3, 5, 2]924b=[3, 1, 5, 2, 4]925print(a==b)926 927 928#write a python program to check two lists are equal or not929a=frozenset(set([5,6,7]))930print(a)931 932 933#write a python program to sum the set of unqiue elements934a={5,6,7}935print(sum(a,5))936 937 938#write a python program to implement try catch code939try:940    s={5,6}941    s*3942except Exception as e:943    print(e)944 945 946#write a python program to count the len of unique elements947nums = set([1,1,2,3,3,3,4,4])948print(len(nums))949 950 951#write a python program to split in python952print('abcdefcdghcd'.split('cd', 2))953 954 955# write a python program to add title to string956print('ab cd-ef'.title())957 958 959# write a python program to print equal lenght of string960print('ab'.zfill(5))961 962 963# write a python program to use string replace964print('abcdef12'.replace('cd', '12'))965 966 967#  write a python program to check string istitle968str1 = 'Hello!2@#World'969if str1.istitle():970    print('Yes string is title')971 972 973#  write a python program to do lstrip on string974print('xyyzxxyxyy'.lstrip('xyy'))975 976 977#  write a python program to check identifier/keyword978print('for'.isidentifier())979 980 981#  write a python program to check is an num/int982print('11'.isnumeric())983 984 985#  write a python program to check is an variable is printable986print('1@ a'.isprintable())987 988 989#  write a python program to check it contains any space990print(''''''.isspace())991 992 993#  write a python program to check is an title994print('HelloWorld'.istitle())995 996 997#  write a python program to check is all are num/int998print('ab,12'.isalnum())999 1000 1001#  write a python program to check is all are alphanumeric1002print('ab'.isalpha())1003 1004 1005#  write a python program to check is all are digit1006print('0xa'.isdigit())1007 1008 1009#  write a python program to use f string1010var1 = 'python language'1011print(f'f-string is an good feature in {var1}')1012 1013 1014#  write a python program to iterate an dict and concatenate1015D=dict(p='san', q='foundry')1016print('{p}{q}'.format(**D))1017 1018 1019# write a python program to replace blank space to 11020a='1 0 0 1'1021print(a.replace(' ', '1'))1022 1023 1024# write a python program to explain the generator1025def f11(x):1026    yield x+11027g=f11(8)1028print(next(g))1029 1030 1031# write a python program to replace blank space to 11032def f12(x):1033    yield x+11034    print("test")1035    yield x+21036g=f12(9)1037print(next(g))1038 1039 1040# write a python program to replace blank space to 11041a = re.compile('[0-9]')1042z= a.findall('3 trees')1043print(z)1044 1045 1046# write a python program to print current working directory1047import os1048print(os.getcwd())1049 1050 1051# write a python program to print the ascii value of a string1052print([ord(ch) for ch in 'abc'])1053 1054 1055# write a python program to use extend in list/ append to a list1056a=[13,56,17]1057a.append([87])1058a.extend([45,67])1059print(a)1060 1061 1062# write a python program to replace blank space to 11063my_string = 'balaji'1064k = [print(i) for i in my_string if i not in "aeiou"]1065print('Not a vowel',k)1066 1067 1068# write a python program to add and square a range of number1069x = [i**+1 for i in range(3)]; print(x)1070 1071 1072# write a python program to replace blank space to 11073print([i+j for i in "abc" for j in "def"])1074 1075 1076# write a python program to multiply two list with list comprehensive1077l1=[1,2,3]1078l2=[4,5,6]1079print([x*y for x in l1 for y in l2])1080 1081 1082# write a python program to print only digit or only apha charac in a given list1083l=["good", "oh!", "excellent!", "#450"]1084print([n for n in l if n.isalpha() or n.isdigit()])1085 1086 1087# write a python program to print todays date1088tday=datetime.date.today()1089print(tday)1090 1091 1092# write a python program to check tuple are immutable1093a=(1,2,3)1094try:1095    a = a+11096except Exception as e:1097    print(e)1098 1099 1100# write a python program to calculate factorial sum using list comprehensive1101import functools1102n =51103print(functools.reduce(lambda x, y: x * y, range(1, n+1)))1104 1105 1106# write a python program to print len of each characters1107words = ['cat', 'window', 'defenestrate']1108for w in words:1109    print(w, len(w))1110 1111 1112# write a python program to make increment on each call of method using lambda function1113def make_incrementor(n):1114    return lambda x: x + n1115f = make_incrementor(42)1116f(0)1117print(f(1))1118 1119 1120# write a python program to sort using list comprehensive1121pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]1122pairs.sort(key=lambda pair: pair[1])1123print(pairs)1124 1125 1126# write a python program to del the first element of the array/list1127a = [-1, 1, 66.25, 333, 333, 1234.5]1128del a[0]1129print(a)1130 1131 1132# write a python program to replace the first character of a given word1133word = "goal"1134word = "f" + word[1:]1135print(word)1136 1137 1138# write a python program to find a string in a given phrase1139phrase = "the surprise is in here somewhere"1140print(phrase.find("surprise"))1141 1142 1143# write a python program to expalin the use of f-string1144n = 31145m = 41146print(f"{n} times {m} is {n*m}")1147 1148 1149# write a python program to explain the use of assert1150x=11151y=81152assert x>y, 'X too small'1153 1154 1155# write a python program to multiply three numbers1156num1 = 1.51157num2 = 6.31158num3 = -2.31159product = num1 * num2 * num31160print(f'Product: {product}')1161 1162 1163# write a python function that when given two numbers, would divide the first number by second number and return the quotient and remainder1164def divide_first_number_by_second(num1, num2):1165    return (num1 // num2), (num1 % num2)1166 1167 1168# write a python function to return the largest and smallest numbers in the given list and return None if the list is empty1169def largest_and_smallest(list_of_nums):1170    if list_of_nums:1171        return max(list_of_nums), min(list_of_nums)1172    else:1173        return1174 1175 1176# write a recursive python function to print the nth fibonacci number, where n is provided as the argument1177def fibonacci_recursive(n):1178   if n <= 1:1179       return n1180   else:1181       return (recur_fibo(n-1) + recur_fibo(n-2))1182 1183 1184# write a python function that would read the given input file path and print its contents1185def read_and_print_file(filepath):1186    with open(filepath, "r") as infile:1187        print( infile.read() )1188 1189 1190# write a python program that would print the first n positive integers using a for loop1191n = 621192for num in range(n):1193    print(num)1194 1195 1196# write a python function that returns the input list sorted in ascending order1197def sort_ascending(list_to_be_sorted):1198    return sorted(list_to_be_sorted)1199 1200 

Showing the first 1,200 of 43009 lines. Download the file for the rest.