Saturday, November 7, 2020

Linear Search algorithm

Linear Search Algorithm

Dear Readers,

In this Blog today I would Share about Linear Search Algorithm a must know for everyone whether you want to are searching for a book starting with particular alphabet in bookshelf in any order, or you want to find a kid in row of children standing for the assembly(pun intended),etc. .

So, what is Linear Search?

In most simple words, It is to find a particular element in a set of given array of elements kept in any random order.

Picture depicting Linear Search
So, I would Share the necessary step in accordance with the picture then a python code for the same

Step 1: make an array of elements.
Step 2: take the input of element you want to check in the array you made.
Step 3: then simply compare that input element or key to each and every element of your array by creating a finite loop which ends when the last element of the array is checked
# its time complexity is O(n) ,Meaning though it is simple but not very efficient especially on large arrays .😟

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#1.make an array
my_array = input('enter input separated with commas for split:\n').split(',')
# all numbers entered are in string form so
my_list =[int(i) for i in my_array]
#2.take you key or whatever you want to check
key = int(input('Enter key:\n'))
#3.here the magic begins


# called my function for action
def linear_search(array,key):
    for index in range(len(array)):
        if array[index]==key:
            return 'Yes found your element in array at:\n%d'%(index)
    return -1

print(linear_search(my_list,key))

If you enjoyed reading this blog as much as I enjoyed writing it then do not forget to share it and subscribe for more such blogs

Friday, November 6, 2020

Binary Search algorithm Python

 What is Linear Search?

Dear Readers,
In this Algorithm the way of searching an element from an array is to sort it and them keep dividing it on the basis of its value of elements v/s the desired element to be checked.

Picture of searching

It wouldn't be wrong to say a picture is worth thousand words so:

Binary Search example
# Note here middle for arr = [1,2,3,4] would be 3 since len(list) ==4//2 ==>2 and arr[2] = 3
                                               ↕ ↕ ↕ ↕
               indice's for arr-==> 0 1 2 3
So there are basic steps involved:
Step 1: sorting the entered elements in array 
Step 2:then get the key(desired element to be checked) from input
Step 3 :Set low value equal to zero and high value = len(list)-1
Step 4: calculate the middle value of array using average of low value and high value ((low+high)//2)
Step 5:then take middle element of array and match with key(38)
Step 6: If it matches quit with index of element
Step 7:Else if the key value is greater than mid value set low value as next to mid value and keep high value as same(i.e 45 will be new low and high will be 90 ) 
Step 6:and if the key value is less than mid value set high value just behind  mid value and keep low value as same(i.e 6 will be new low and high will be 23 ) 
Step 8: again calculate the middle values respectively (i.e if Step 5 new_mid will be 77  and for Step 6 
new_mid would be 12)
Step 9: This process will repeat until key matchs with middle value.
# its time complexity is O(logn)

===>Here's the code in python so it makes it easy to interpret for beginners:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Returns index of x in arr if present, else -1 
def binary_search(arr, low, high, x): 

	# Check base case 
	if high >= low: 

		mid = (high + low) // 2

		# If element is present at the middle itself 
		if arr[mid] == x: 
			return mid 

		# If element is smaller than mid, then it can only 
		# be present in left subarray 
		elif arr[mid] > x: 
			return binary_search(arr, low, mid - 1, x) 

		# Else the element can only be present in right subarray 
		else: 
			return binary_search(arr, mid + 1, high, x) 

	else: 
		# Element is not present in the array 
		return -1

# Test array 
arr = [ 2, 3, 4, 10, 40 ] 
x = 10

# Function call 
result = binary_search(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") 

I hope you liked this blog on Binary Search  you can check out more such blogs on my blogspot and for more info on this topic : click here!

Thursday, November 5, 2020

Five Unbelievable Facts About Python

Dear Readers,

Here I would like to Share 5 amazing or unbelievable facts about python programming language which you might haven't noticed yet!!


picture depicting unique facts in python











So without Wasting your time lets just jump to the facts:

1. What if I said you to compare your name with your best friends name ,sounds illogical right?:

---> Well in python you can actually compare strings based on lexicographic values(comparing dictionary order wise)

1
2
>>'abc' < 'adc'
True

True (since d comes after b if seen alphabetically)

2. Do you really want to know BTS(behind the scenes ) in python programming?: 

--->Well dis module is there for your aide (it means disassemble ) so it disassembles your code into human readable format and lets you know what your interpreter is doing 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import dis
def hello():
    print('Hello')

print(dis.dis(hello))

#Output:
  3           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('Hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
None

For more info click me!

3. We can compare tuples and lists also in python(for coders):

--->

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
3,4,5 < 6,7,8
(3, 4, True, 7, 8)
# here our interpreter takes it as 3,4,(5<6),7,8
# hence we use 
>>> (3,4,5)<(5,3,7)
True
>>> (3,4,5)<(2,1,9)
False
# so majority wins more i.e more trues make # output true
# similarly you can use lists
>>>[1,2,3]<[2,3,4]
True

4. How would you take logical interpretation for True or False statements?

--->Well our Python has something for us in that case

In python any value not equal to zero(in number terms) is true and you can use True in place of 1 as well and None,0,'',[],{},(),etc depict False 

1
2
3
4
5
>>> True == 1
True
>>> True is 1
False
# they share equal values but they are not same

5.How should you code, or what should be the format?

---> Well guess what guys python solved this as well with the zen of python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

So guys I hope you enjoyed it reading this blog as much as I enjoyed Writing it please comment and subscribe for more such blogs on regular basis. Also you can check more of my blogs like random module in python, simple calculator

Wednesday, November 4, 2020

String Formatting-3

 String Formatting-3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
1. endswith()-to check whether string ends with a particular character(case sensitive)

-->print('numpy'.endswith('y'))

-->True

2. find()/index()- method finds the first occurrence of the specified value,returns -1 if not found,almost like index method.

-->print('Debug'.find('b'))

-->2

-->print('Debug'.find('s'))

-->-1

-->print('Debug'.index('s'))

-->ValueError



3. replace()- This method replaces a specified phrase with another specified phrase.

-->print('hi there'.replace('hi','hello'))

-->hello there



4. split()-splits a string into list,based on a seprator(default string).

-->print('harsh'.split())

-->['harsh']

-->print('h,a,r,s,h'.split(','))

-->['h','a','r','s','h']



5. join()-joins a iterable into string,using a seprator(default string).

-->print(','.join(['h','a','r','s','h']))

-->'h,a,r,s,h

String Formatting-2

 String Formatting-2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
1. isalpha()-to check whether string has only alphabets

-->print('alpha'.isalpha())

-->True



2. isdigit()-to check whether string has only digits

-->print('1010'.isdigits())

-->True



3. isspace()-to check whether string has only spaces

-->print('   '.isspace())

-->True



4. center()-this will center align the string ,using specified character(space is default) as a fill character

-->print('Python'.center(10,'*'))

-->**Python**



5. startswith()-to check whether string starts with a particular character(case sensitive)

-->print('numpy'.startswith('n'))

-->True

String Formatting-1


String Formatters

Part -1

Dear Readers ,
today I would like to share about string formatter in python and I have them all in this single blog,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Important string operations-1

1. len()-to evaluate the length of a string

-->print(len('sample'))

-->6



2. str()-create new string object from given object

-->print(type(str(6)))

-->'<class 'str'>'



3. lower()-to covert a string to lowercase

-->print('HI'.lower())

-->hi



4. upper()-to covert a string to uppercase

-->print('hi'.upper())

-->HI



5. strip()-strip the spaces in input there are two subtype's lstrip and rstrip also

-->print('  Python  '.strip())

-->Python

-->print('  Python'.lstrip())

-->Python

-->print('Python  '.rstrip())

-->Python

Tuesday, November 3, 2020

Calculator



 Calculator

Dear Readers,

Today I would share a super cool application of python programming
by making a calculator:

==>1. Our function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def operator_func(selection,a,b):
    if selection =='add':
        return a+b
    elif selection =='sub':
        return a+b
    elif selection =='multiply':
        return a+b
    elif selection =='divide':
        try:
            return a/b
        except ZeroDivisionError as e :
            error = f'error occured :{e}'
            return error

==>2.Here we select our operator and numbers:

1
2
3
operator = input('select:\n1.add\n2.subtract\n3.multiply\n4.divide\n')
num1 = int(input('enter number_1\n'))
num2 = int(input('enter number_2\n'))

==>3.We get the value attached to the keys of the operator_dict using get method:

1
2
operator_dict ={'1':'add','2':'sub','3':'multiply','4':'divide'}
selection = operator_dict.get(operator,'select valid operator')

==>4.Get our answer:

1
print(f'your answer is :\n{operator_func(selection,num1,num2)}')

Sunday, November 1, 2020

OS & SYS

System Module  and OS Module 

     Its Important Functionalities
 

Dear Readers,
Today I would like to share major functionalities from OS and SYS module,
Function of OS module is that it allows the user(you) to interact with the operating system of your device:

1.os.name

==>This helps to get the information on current operating system of your device
1
2
>>> os.name
'nt'

2.os.getcwd()

==>This Function os.getcwd(), returns the Current Working Directory(CWD) of the file used to execute the code, can vary from system to system.

1
2
>>> os.getcwd()
'C:\\Users\\Example\\OneDrive\\Desktop\\python playlist'

3. os.rename('existing_file_name','new_file_name')

==> This function is used to change the name of the file. The name of the file changes only if, the file exists and user has sufficient privilege permission to change the file.

1. sys.argv

 ==>This function returns a list of command line arguments passed to python script. The name of the script is always the item at index 0,and the rest of the arguments are stored at subsequent indices.

1
2
>>> sys.argv[0]
'C:\\Users\\Adarsh tiwari\\OneDrive\\Desktop\\python playlist\\test.py'

2. sys.exit

==>This causes the script to exit to either python console or the command prompt. This is a way of safe exit in case of generation of error

3.sys.path

==>This modules search paths can be identified using this function

1
2
>>> sys.path
['C:\\Users\\Adarsh tiwari\\OneDrive\\Desktop\\python playlist', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Adarsh tiwari\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']

4.sys.maxsize

==>This module returns the largest value an integer can take
1
2
>>> sys.maxsize
9223372036854775807

Linear Search algorithm

Linear Search Algorithm Dear Readers, In this Blog today I would Share about Linear Search Algorithm a must know for everyone whether you wa...