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

Saturday, October 31, 2020

swap nums

p> Dear readers,

Today we will try to perform swapping the numbers exercise in python, c and c++:

So there are two Logical ways used:

Logic 1:

Here :

1.copy elements from number_1 into a temporary variable 

2. copy number 2 to number_1 

3. copy number_1 from (temporary variable) to number_2

so example:

number_1 = 10

number_2 = 12

Step 1. temporary variable = 10

Step 2.number_1 = 12

Step3.number_2 = 10(from temporary  variable) 

number_1 = 12

and 

number_2 =10

Logic 2:

Note: This is more programmer oriented logic

1.number_1 = number_1 + number_2 ---> [1]

2.number_2 = number_1 - number_2 => using [1]: number_1 + number_2 - number_2 == number_1 --> [2]

3.number_1 = number_1 - number2 => using [2] and [1]:  number_1 +number_2 - number_1 == number_2 

example

number_1 = 10, number_2 = 12

1,number_1 = 10 + 12 = 22

2.number_2 = 22 - 12 = 10(10 + 12 - 12)

3.number_1 = 22 - 10 = 12(10 + 12 - (22 - 12))==>(34-22)==>(12)

number_1 = 12 ,number_2 = 12

Lets Code now

#1. Python

# swapping number logic
num1 = int(input('enter first number:\n'))
num2 = int(input('enter first number:\n'))
print(f'numbers before swap a:{num1} and b:{num2} ')
# Logic is used here
temp = num1
num1 = num2
num2 = temp
print(f'\nnumbers after swap a:{num1} and b:{num2} ')
#This is second Logic
num1 = int(input('enter first number:\n'))
num2 = int(input('enter first number:\n'))
print(f'numbers before swap a:{num1} and b:{num2} ')
num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2
print(f'\nnumbers after swap a:{num1} and b:{num2} ')

#2.C++

#include <iostream>
using namespace std;

int main()
{
    int num1, num2, temp;

    cin >> num1 >> num2;
    cout << "Before swapping num1 = " << num1 << ", num2 = " << num2  << endl;
    //Logic is used here
    temp = num1;
    num1 = num2;
    num2 = temp;

    cout << "\nAfter swapping num1 = " << num1 << ", num2 = " << num2 << endl;
    //here is second Logic
    cout<<"\nTry with Second Logic:\n"<<endl;

    cin >> num1 >> num2;

    cout << "Before swapping num1 = " << num1 << ", num2 = " << num2  << endl;
    //Logic is used here
    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    
    cout << "\nAfter swapping num1 = " << num1 << ", num2 = " << num2 << endl;

    return 0;
}

# C

#include<stdio.h>

int main(){
    int num1 ,num2,temp;
    printf("enter number1 and number2:\n");
    scanf("%d%d",&num1,&num2);
    printf("numbers before swap are num1 :%d num2:%d",num1,num2);
    // logic used here
    temp = num1;
    num1 = num2;
    num2 = temp;
    
    printf("\nnumbers after swap are num1 :%d num2:%d\n",num1,num2);
    //Second Logic
    printf("Try with the second Logic...\n");
    
    printf("enter number1 and number2:\n");
    scanf("%d%d",&num1,&num2);
    printf("numbers before swap are num1 :%d num2:%d",num1,num2);

    // logic used here
    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;
    
    printf("\nnumbers after swap are num1 :%d num2:%d",num1,num2);


}

Friday, October 30, 2020

Hello World

 Hello World!!

Dear Readers,

Today I would share simple hello world programs from popular computer languages, like Python, C ,

Java, C++ . This blog is meant to express the simplicity and strength of Python programming language

1. Python 

# Hello world in Python 
print 'hello world!'

2. C

/* hello world in c */
#include <stdio.h>

int main() {
  printf("Goodbye, World!");
  return 0;
}

3. Java

// Hello World in Java
public class Main {
    public static void main(String[] args){
        System.out.println("Hello World!");
    }
}

4. C++

// Hello world in C++
#include<iostream>
using namespace std;

int main(){
cout<<"Hello World!"<< std::endl;
return 0;
}

Thursday, October 29, 2020

Different languages

 Dear Readers,

Todays Blog would be a brief introduction about MAJOR programming languages :

Types of Programming Languages

The different types of programming languages are discussed below.

Types of Programming Paradigms

The importance of different Programming Languages

Python Language

Python is powerful... and fast plays well with others runs everywhere is friendly & easy to learn is Open. Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs.


WHY TO LEARN PYTHON:

  • Web and Internet Development
  • Database Access
  • Desktop GUIs
  • Scientific & Numeric
  • Education
  • Network Programming
  • Software & Game Development
Disadvantages:
  • Speed. Python is slower than C or C++. 
  • Mobile Development. Python is not a very good language for mobile development . 
  • Memory Consumption. Python is not a good choice for memory intensive tasks. 
  • Database Access. Python has limitations with database access . 
  • Runtime Errors.
Python Language


    

Java Language

The Java language is a multi platform language that’s particularly helpful in networking. Of course, mostly this language is used on the web with Java applets. However, this language is used to design cross platform programs, Since it similar to C++ in structure and syntax. For C++ programmers, Java language is very easy to learn and it offers some advantages provided by object oriented  programming. Like reusability and it can be difficult to write efficient code in Java. But, nowadays the speed of the Java language has increased and 1.5 version offers some good features for easy program making.


Why Learn Java:

  • Java is a platform-independent language. We can write Java code in one platform and run it in another platform
  • Java is a general-purpose language with a wide range of applications. It's used for developing mobile and desktop applications, big data processing, embedded systems, and so on.
  • Java is an object-oriented programming language. It helps in code reusability. 
Disadvantages:
  • Java is slow and has a poor performance. Java is memory-consuming and significantly slower than native languages such as C or C++. 
  • Java provides not so attractive look and feels of the GUI. 
  • Java provides no backup facility.
  • Java requires significant memory space. 
  • Verbose and Complex codes.


          Java Language

          Java Language


          C++ Language

          The C++ language has an object oriented structure which is used in large projects. Programmers can collaborate one program into different parts or even one individual work on each part of the program. The structure of object oriented also permit code to be reused many times. This language is an efficient language. But, many programmers will disagree

          WHY TO LEARN C++:

          • C++ is used to develop games, desktop apps, operating systems, browsers, and so on because of its performance.
          • After learning C++, it will be much easier to learn other programming languages like Java, Python, etc.
          • C++ helps you to understand the internal architecture of a computer, how computer stores and retrieves information.
          Disadvantages :
          • It has no security.
          • Complex in a very large high-level program.
          • Used for platform specific application commonly.
          • For a particular operating system or platform, the library set has usually chosen that locks.
          • When C++ used for web applications complex and difficult to debug.
          • C++ can't support garbage collection.
          C++ Language

          C++ Language

          C Language

          The C language is a  basic programming language and it is a very popular language, particularly used in game programming, Because C language includes the additional packing of the C++, Every programmer uses this language because it makes programs faster . However the value of this language gives the reusability of C++ to get the slight increase in performance with C language.

          Why Learn C Programming :

          • C helps you to understand the internal architecture of a computer, how computer stores and retrieves information.
          • After learning C, it will be much easier to learn other programming languages like Java, Python, etc.
          • Opportunity to work on open source projects. Some of the largest open-source projects such as Linux kernel, Python interpreter, SQLite database, etc. are written in C programming.

          Disadvantages:

          • Concept of OBJECT ORIENTED PROGRAMMING. C is a very vast language, but it does not support the concept of OOPs (Inheritance, Polymorphism, Encapsulation, Abstraction, Data Hiding). ...
          • Run-time checking. 
          • Concept of namespace. 
          • Lack of Exception Handling. 
          • Constructor or destructor.
          • Low level of abstraction.
          C Language

          C Language

          Fortran Language

          Fortran language is a number crunching language and still it is used by scientists. This language allows different sizes of variables up to the memory limit in the machine. This language is suitable for engineers, who have to calculate values with high precision. Program in Fortran is inflexible and sometimes it makes difficult to read.

          WHY TO LEARN FORTRAN:

          •  used for such projects as the design of bridges and aeroplane structures
          •  it is used for factory automation control, for storm drainage design
          •  used for the analysis of scientific data 

          Disadvantages :

          • Lack of inherent parallelism. 
          • Lack of dynamic storage. 
          • Lack of numeric portability. 
          • Lack of user-defined data structures. 
          • Lack of explicit recursion. 
          • Reliance on unsafe storage and sequence association features.
          Fortran Language

          Fortran Language


          Photo Credits:

          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...