Skip to content

Jahnavichowdhary1/Python-DSA

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Python-DSA

I have done some problems in DSA

patterens we are gng to do here ok?

''' def square_pattern(n): result = [] for i in range(n): row = "*" * n result.append(row) return result print(square_pattern(5)) '''

''' def hallow_pattern(n): result=[] for i in range(n): if i==0 or i==(n-1):# here i == 0 means i=1,2,3,4,5, when n = 6 so our count is to be n-1

        result.append("*" * n)
    else:
        star ="*" 
        space = n-2
        row = star + " "*space+ star
        # row = "*" + ""*(n-2)+"*"
        result.append(row)
return result

print(hallow_pattern(4)) '''

here we are printing a rectangle n.m n= row and m= column

so my row depends on m colums

''' def rectangle(n,m): result = [] for i in range(n): # menas my columns i = 0,1,2,3 example row = "*" * m # here myrows prints based on my loops of i i.e my colums result.append(row) return result print(rectangle(4,7)) # for every index range of n , m will be give stars '''

we need to create right angle triangle (no spaces)

''' def right_triangle(n): result = [] for i in range(1, n+1): # here when n= 0 then i0 ntg so make n=1 row = "" * i result.append(row) return result print(right_triangle(6))

'''

invereted triangle

here see when i =0 means at loop 1 my triangle as all starts (n) when i =1 it reduces to 1 from n menass here i = 1 and n =6

so (n-i) stars we get

''' def inverted_right_triangle(n): result = [] for i in range(n):# check once after drawing this ques row = "*" *(n-i) # no spaces needed so ... result.append(row) return result print(inverted_right_triangle(7))

'''

pyramid

''' def pyramid_pattern(n): result =[] for i in range(1, n+1): stars = 2*i-1 # or "(2n-1) spaces = n-1 row = " "spaces + ""*stars + " "*spaces result.append(row) return result print(pyramid_pattern(5)) '''

#invereted pyramid '''



inverted pyramid and inverted triangle are differnt

'''

it means i = 0 then no spaces , i =1 one space at left and right so spaces = i

when i= 0 , total n stars when i = 1 ,n-2 stars when i =2 means n-2 stars

here pyramid is like removing 2 stars at every loop means when n = 6 then it has 6 rows

n=4 .], "*************

*********

******

***

*"

like this when n = 4

''' def inverted_pyramid(n): result = [] for i in range(1, n+1): stars = 2 *(n-i) + 1 # we have decrease stars on both side so we have to write 2 *(n-i) -1 insteaad of n-i spaces = i row =" "spaces + ""*stars + " "*spaces result.append(row) return result print(inverted_pyramid(6))

'''

print right angle triangle with numbers

''' def tringle_num(n): rst = [] for i in range(1, n+1): r = str(i)*i # becz they should not multiply ang give calc ans so str dont mult it act as concatinate rst.append(r) return rst print(tringle_num(4))

'''

#Floyds traingle ************************************************************************

means i = 0 contains 1, and i = 2 contains 2,3 and i= 3 comtains 4,5,6 so on

at evey iterations no.of range of i values are incerementing +1 times

''' def Floyds_trinagle(n): result =[] num = 1 for i in range(1, n+1): row =[] for j in range(i): # so it can only trace i = 1 meanss 1 loop we also want that when i =2 ,2-> values we need and that aslo has to inceremnt row.append(str(num)) # strings dosn't add they concatinate so use str(num) num += 1 result.append(" ".join(row)) # so when i = 2 , j= 0,1,2 then num becames ++ all time so we get 1,2,3,4,5,... return result print(Floyds_trinagle(4)) '''

It joins all the elements of the list into one string, placing a space between them

our nrml o/p when join not used

''' [ ['1'], ['2', '3'], ['4', '5', '6'], ['7', '8', '9', '10'] ] '''

this are not joined that are separated so use join.row[]

it becames\

''' [ ["1"], string can join ["2 3"], ["4 5 6"], ["7 8 9 10"] ]'''

DAIMOND PATTERN ?(pyramid + inverted pyramid)

''' def daimond(n): # n = 5 means starts with 1 and end with 5 rows by addings *s at ends res =[] for i in range(1, n+1): # upper part spaces = n-i stars = 2 *i-1 row = " "spaces+ ""*stars + " "spaces res.append(row) for i in range(n-1, 0, -1): # lower part spaces = n-i stars = 2i-1 row = " "spaces+ ""*stars + " "*spaces res.append(row) return res # stired uppewr and lower parts values print(daimond(5)) '''

Right angled triangle (means all *s should be stared from left to ryt pattern)

''' * **


**** like this '''

means we haver to write spces firsy and no need of corners spaces only we ehave space and star

spaces = n-i, star = i

''' def ryt_right_angle_triangle(n): result =[]

for i in range(1, n+1):
    spaces = n-i
    star = i
    r = " "*spaces + "*"*star
    result.append(r)
return result

print(ryt_right_angle_triangle(4)) '''

SANDGLASS PATTREN(inverted pyramid+ pyramid )

''' def sand_patteren(n): result = [] for i in range(1, n+1): spaces = i-1 stars = 2*(n-i)+1 row = " "spaces+ ""*stars + " "spaces result.append(row) for i in range(2, n+1): # already we have done one * so start from 2 spaces = n-i stars = 2i-1 row = " "spaces+ ""*stars + " "*spaces result.append(row) return result print(sand_patteren(6)) '''

HALLOW RIHGT TRIANGLE

''' * * * * * * * # hallow and traingle looks like this * * * * * * '''

so when i = 1 and i ==n then space + "" and n "*" else:middle terms hallow star space star

star is common on both side so spaces is ++ so find space ==?

''' def hallow_triangle(m): res = [] for i in range(1, m+1): spaces = m-i if i==1: r = " "spaces + "" res.append(r) elif i==m: r = m*"" res.append(r) else:# middle terms hallow contains inside_spaces = 2 * i - 3 r= " " * spaces + "" + " " * inside_spaces + "*" res.append(r) return res print(hallow_triangle(7)) '''

inverted hallow traingle#

''' write code

'''

number pyramid pattern

1

#12 #123 #1234... ''' def Pyramid_num(n): for i in range(1, n+1): for j in range(1, i+1): # upto i loop only it have to run print(j, end="") print() # to print in another line

Pyramid_num(4) '''

celsius to Farenheit

''' def celsius_faren(c): faren = (9/5)*c+32 return faren c = float(input()) f = celsius_faren(c) print(f) '''

or

''' c - float(input()) f = (9/5)*c+32 print '''

sum of lst

''' def sum_of_list(n): total = 0 for i in n: total = total+i return total print(sum_of_list([1,2,3,4,5])) # ([]) this is condition '''

''' def sum_of_list(lst): total = 0 for i in range(len(lst)): total += lst[i] return total '''

FIND LARGEST NUMBER IN LIST

''' def largest_num(lst): largest_nub=lst[0] for i in lst: if largest_nub < i: largest_nub = i return largest_nub print(largest_num([1,2,4,5,6,89])) '''

or

''' def largest_num(l): lar = 0 for i in range(len(l)): if lar < l[i]: lar = l[i] return lar # but this codes fails for all negative lst elements ([-12,-13,-3,-5,-23])

so better to use like lar = l[0] so its check this other elements in lst

print(largest_num([1,2,3,45,565])) '''

DUPLICATE REMOVING

here wwe can use like if num in our lst append or dont

''' def duplicate_remove(lst): result =[] for num in lst: if num not in result: result.append(num) return result print(duplicate_remove([12,33,33,15,66,90,12])) '''

[result.append(x) for x in lst if x not in result] list comprehension can slove in 1 line

def duplicate_remove(lst):

# return list(set(lst))

def duplicate_remove(lst):

# return list(dict.fromkeys(lst))

#CHECK ELEMENTS IN LST ARE UNIQUE ARE NOT ''' def unique_elem(lst): res = [] for i in lst: # i = 1 in lst then is it in res ? no means add that , i=22 in lst .is in res no so add that when lst num is already in res then false

    if i in res:
        return False
    res.append(i)
return True

print(unique_elem([1,22,2,3,4,5,4])) '''

REVERSE A LIST OF ELEMENTS

''' def rev_lst(lst): result =[] for num in lst[::-1]: result.append(num) return result print(rev_lst([1,2,3,4,5,5])) '''

or we can do

''' n = input() # means it try to take them as str"1234" result = [] for i in n[::-1]: # it works only for str, list,tuple result.append(i) print(result, end="") '''

COUNT NO.OF ODD, EVEN ELEMENTS IN LST

'''
def no_of_odd_even(lst): even_count = 0 odd_count = 0

for num in lst:
    if num%2 == 0:
        even_count += 1
    else:
        odd_count += 1
return(even_count, odd_count)

print(no_of_odd_even([-1,2,3,56,24,892,63,63452,99]))

'''

CONSECUTIVE DIFFERENCE WE NEED TO FIND

LETS IS WHAT IS CONSECUTIVE FIRST

lst = [4, 5, 6, 7]

for i in range(len(lst)-1):

if lst[i] + 1 == lst[i+1]:

print("Consecutive")

else:

print("Not Consecutive")

NOW maxium of (count)CONSECUTIVE DIFFERENCE

''' def consecutive(lst): max_diff = 0 for i in range(len(lst)-1): diff =abs(lst[i] - lst[i+1]) # abs -> so, we are using abs if my diff is (-)then abs remove negative sign # here we are finding difference of every elem so all give diff = 1 so for consecutive num alwasy diff is 1 if diff >max_diff: max_diff = diff return max_diff '''

print(consecutive([10,20,29,22,18])) here the max difference is 10 so max_diff = 10

FIND LARGESTED AND CREATE LARGE NUMBER FROM GIVE LIST BY ADDING THEM IT SHOULD BE LARGE NUM

so here if my lst = [6,2,46,7] hmy arrangement off adding has to be large so check

conditions 62467 or 24676, or 46726 or 76246 here 46726 is hights so if index loop i search ffor 1 element that should add besides elements

'''

def largest_num(arr): arr = [str(i) for i in arr] for i in range(len(arr)): for j in range(i+1, len(arr)): if arr[i] + arr[j] < arr[j] + arr[i]: arr[i], arr[j] = arr[j], arr[i] # swapped return "".join(arr) print(largest_num([1,2,35,6]))

'''

first we willa ssign all arr elements into str so that we can add them if str not menas they will give like 1+2 = 3 no crct

we are forming a largest num not suming so Str menas "1" + "2" = "12"

when i = 0, j= 1,n so evey element compares wiht beside element and we can swap them and change lst every loop

if i = 0 and lst [1,2,3,4] at j=1 our 12>21 so they swaps and i= 0 becames now 2 lst[2,1,3,4]now at j =2 again checks

y join? out arr added them like {"356"2""1"} sp use .join gives 35621

LINEAR SEARCH (MEANS TAKE ONE TARGET AND FIND WHERE IT LOCATED(INDEX))

''' def linear_search(arr,target): for i in range(len(arr)): if arr[i] == target: return i return -1 print(linear_search([1,2,3,4,5],4))

'''

''' just tried other med anove is good code

def linear_search(arr,target): resu = [] for i in range(len(arr)): if arr[i]==target: resu.append(i) return resu print(linear_search([1,2,3,4],2)) '''

BINARY SEARCH (INSTEAD OF SEARCHING EVERY ELEMENT WE DIVIDE THE LIST INTO 2 HAVLES)

''' def binary_lst(arr,target,low,high): # high = len(arr)-1 # low = arr[0] if low > high: return False m = (low+high)//2 # or low + (high-low)//2 if arr[m] == target: return True elif arr[m]<target: return binary_lst(arr,target,m+1,high) # low = m+1 # high =len(arr)-1 else: return binary_lst(arr,target,low,m-1) print(binary_lst([1,2,8,60,89],40,0,4))# binary search () lst always sorted '''

#REVERSE ARRAY ''' def rev_arr(lst): result=[] for i in lst[::-1]: result.append(i) return result print(rev_arr([1,3,4,5])) '''

''' for i in range(len(lst)-1, -1, -1): result.append(lst[i]) '''

when they ask dont using scling [::-1] then use above code

REMOVE duplicatats

''' def remove_duplicate(arr): res= [] for i in arr: if i not in res: res.append(i) return res print(remove_duplicate([1,22,33,22,14,1]))

def remove_duplicate(arr):

return list(set(arr))

'''

#FIND SECOND LARGEST NUMBER**********

def second_lar(arr):

first_lar=arr[0]

second= arr[0]

for num in arr:

if num > first_lar: # if any num is gretaer change lar value

second = first_lar # store the first large in second if we got new large num , so thta our second large is found

first_lar = num # here ww got new large num

# if our num not > first_lar then it can be grater than second num !!! so check that

elif num > second and num != first_lar:

second = num

return second

print(second_lar([1,2,33,443,534,63]))

FIND SECOND SMALLEST NUMBER IN LST

''' def second_lar(arr):

first_lar=arr[0]

second= float("inf") # to find 2nd smallest 

for num in arr:

    if num < first_lar: 

        second = first_lar 

        first_lar = num  

        

    elif num < second and num != first_lar: 

        second = num

return second

print(second_lar([1,2,33,443,534,63])) '''

FREQUENCY OF ELEMENTS ( means counting repeated elements in lst) we are have frequency of words

''' def frequency_elem(arr): result = [] # we have to count for num in arr: if num not in result: count = 0 for i in arr: if i == num: count += 1 print(num,count) # this well tell which num gets how many time result.append(num) print(frequency_elem([1,1,22,3,3,31]))

''' #frequency of words(setence should be split first ) ''' def freuq_words(arr): words =arr.split() freq={}

for word in words:
    if word  in freq:
        freq[word] +=1
    else:
        freq[word] = 1 # this give how word is counted 
    # freq stored some word here 
return freq

''' #FIND MAXMIUM AND MINIMUM def max_min(arr): maximum = arr[0] minimum = arr[0]

for num in arr:

    if num > maximum:
        maximum = num

    if num < minimum:
        minimum = num

return maximum, minimum

print(max_min([12,45,8,90,67]))

About

I have done some problems in DSA

Resources

License

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors