NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

What is monkey patching in Python?

class monkey:
def patch(self):
print ("patch() is being called")

def monk_p(self):
print ("monk_p() is being called")

# replacing address of "patch" with "monk_p"
monkey.patch = monk_p

obj = monkey()

obj.patch()
# monk_p() is being called





How can you replace string space with a given character in Python?

def str_replace(text,ch):
result = ''
for i in text:
if i == ' ':
i = ch
result += i
return result

text = "D t C mpBl ckFrid yS le"
ch = "a"

str_replace(text,ch)
# 'DataCampBlackFridaySale'


Given a positive integer num, write a function that returns True if num is a perfect square else False.

valid_square(10)
# False
valid_square(36)
# True



def valid_square(num):
square = int(num**0.5)
check = square**2==num
return check

valid_square(10)
# False
valid_square(36)
# True


You are provided with a large string and a dictionary of the words. You have to find if the input string can be segmented into words using the dictionary or not.
s = "datacamp"
dictionary = ["data", "camp", "cam", "lack"]



def can_segment_str(s, dictionary):
for i in range(1, len(s) + 1):
first_str = s[0:i]
if first_str in dictionary:
second_str = s[i:]
if (
not second_str
or second_str in dictionary
or can_segment_str(second_str, dictionary)
):
return True
return False


s = "datacamp"
dictionary = ["data", "camp", "cam", "lack"]

can_segment_string(s, dictionary)
# True



LEFT OUTER JOIN
----------------------
SELECT columns
FROM table1
LEFT JOIN table2 ON join_condition;




Recursive Functions in Python

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))



------------------------------------------
Number of Vowels in a String word
st='Hello world I Love Python'



st_new=st.split()
vow='AEIOUaeiou'
dt={}
for word in st_new:
count=0
for x in word:
if x in vow:
count= count+1
dt[word]=count

print(dt)

{'Hello': 2, 'world': 1, 'I': 1, 'Love': 2, 'Python': 1}



https://chetu.zoom.us/j/4725716289?pwd=aUR4NURMM0d2R0EvT0EwRUxhTzFXdz09

-----------------------------------------------------------------
# Define the array
# Print the results
print(f"The smallest element in the array is: {smallest_element}")
print(f"The largest element in the array is: {largest_element}")
array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# Initialize variables to store the smallest and largest elements
smallest_element = array[0]
largest_element = array[0]

# Iterate through the array to find the smallest and largest elements
for num in array:
if num < smallest_element:
smallest_element = num
if num > largest_element:
largest_element = num

# Print the results
print(f"The smallest element in the array is: {smallest_element}")
print(f"The largest element in the array is: {largest_element}")


----------------------
Find all triplets with zero sum
arr = [0, -1, 2, -3, 1]



def findTriplets(arr, n):

found = False
for i in range(0, n-2):

for j in range(i+1, n-1):

for k in range(j+1, n):

if (arr[i] + arr[j] + arr[k] == 0):
print(arr[i], arr[j], arr[k])
found = True

# If no triplet with 0 sum
# found in array
if (found == False):
print(" not exist ")


# Driver code
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)


0 -1 1
2 -3 1
-------------------------------

def sub_decor(fun):
def inner(a,b):
result=fun(a,b)
sub_result= a-b
return result, sub_result
return inner

@sub_decor
def add(a,b):
return a+b

rest, sub_ret=add(10,5)
print(rest, sub_ret)


-----------------------



nums = [3,2,2,3]
val = 3

# nums=[0,1,2,2,3,0,4,2]
# val=2


nums2=[]

count = 0
ln=len(nums)
for x in range(ln):
if nums[x]!=val:
nums2.append(nums[x])
count=1+count
real_c= len(nums)- count
nums2.extend('_'*real_c)

print(nums2,count)

# [0, 1, 3, 0, 4, '_', '_', '_'] 5
# [2, 2, '_', '_'] 2


----------------------------------------------------
def sum_of_n(num):
sum=0
for x in range(num+1):
sum=sum+x
return sum




Time Complexity: The loop in your function iterates from 0 to num, performing a constant-time operation (adding x to the sum) in each iteration. Since the loop runs num + 1 times, the time complexity is O(n), where n represents the input value num.

Space Complexity: The space complexity refers to the additional memory used by the algorithm. In your function, the only variables that consume memory are sum and x. These variables occupy a constant amount of space regardless of the input size. Therefore, the space complexity is O(1) (constant space)




def sum_of_n(num):
return (num*(num+1))//2

---------------------------------------
factorial

def fect_num(x):
if x==1:
return x
else:
return x*fect_num(x-1)

print(fect_num(3))
-------------------






Time Complexity:The computation of the sum involves a single multiplication, an addition, and an integer division. These operations are constant-time (O(1)) because they don’t depend on the input size.
Therefore, the overall time complexity of your sum_of_n function is O(1).

Space Complexity:The function uses only a single variable (sum) to store the result. This variable occupies a constant amount of memory, regardless of the input value.
Hence, the space complexity of your function is also O(1) (constant space)



print(sum_of_n(10))


-------------------------------


nums=[3,3,3,4,4,4,4,2]
k=2
dt={}
for x in nums:
if x in dt:
dt[x]+=1
else:
dt[x]=1
st=sorted(dt.items(),key=lambda x:x[1], reverse=True)

# print(st)
# [(4, 4), (3, 3), (2, 1)]

# lt=[(4, 4), (3, 3), (2, 1)]
lt_new=[x[0] for x in st[:k]]
print(lt_new)


-------------------------------
import pandas as pd

# Define the dictionaries
marks = {
'Marks': [93, 81, 88, 80, 70, 40],
'id': [1, 2, 3, 4, 5, 6],
'department':['BA','bcom','BA','bcom','btech','btech']
}

students = {
'id': [1, 2, 3, 4, 5],
'Name': ['Amy', 'Maddy', 'Shyam', 'Ram', 'Ama'],
'Age': [19, 12, 22, 23, 45]
}

# Create DataFrames from the dictionaries
df_marks = pd.DataFrame(marks)
df_students = pd.DataFrame(students)

# Merge the DataFrames on the 'id' column
df_combined = pd.merge(df_students, df_marks, on='id')

# Display the combined DataFrame


# Group by 'department' and find the second highest marks
second_highest_marks = df_combined.groupby('department').apply(lambda x: x.nlargest(2, 'Marks').iloc[-1], )

print(second_highest_marks)
------------------------------

import pandas as pd

# Sample data
data = {
'id': [1, 2, 3, 4, 5],
'salary': [50000, 60000, 70000, 80000, 90000]
}

# Create DataFrame
df = pd.DataFrame(data)

# Sort by salary in descending order and drop duplicates
df_sorted = df.sort_values(by='salary', ascending=False).drop_duplicates(subset='salary')

# Get the second highest salary row
second_highest_salary_row = df_sorted.iloc[1] if len(df_sorted) > 1 else None

if second_highest_salary_row is not None:
second_highest_salary = second_highest_salary_row['salary']
second_highest_id = second_highest_salary_row['id']
print(f"Second highest salary: {second_highest_salary}, ID: {second_highest_id}")
else:
print("There are less than two unique salaries.")


     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.