6 |
7 |
8 | ### This repository aims to help code beginners with their first successful pull request and open-source contribution. :partying_face:
9 |
10 | :star: Feel free to use this project to make your first contribution to an open-source project on GitHub. Practice making your first pull request to a public repository before doing the real thing!
11 |
12 | :star: Make sure to grab some cool swags during Hacktoberfest by getting involved in the open-source community.
13 |
14 | ### This repository is open to all members of the GitHub community. Any member can contribute to this project! The only thing which you need to keep in mind is that it should be genuine PR :grin:
15 |
16 | ## What is Hacktoberfest? :thinking:
17 | A month-long celebration from October 1st to October 31st presented by [Digital Ocean](https://hacktoberfest.digitalocean.com/) and [DEV Community](https://dev.to/) collaborated with [GitHub](https://github.com/blog/2433-celebrate-open-source-this-october-with-hacktoberfest) to get people involved in [Open Source](https://github.com/open-source). Create your very first pull request to any public repository on GitHub and contribute to the open-source developer community.
18 |
19 | [https://hacktoberfest.digitalocean.com/](https://hacktoberfest.digitalocean.com/)
20 |
21 | ## Rules :fire:
22 | To qualify for the __official limited edition Hacktoberfest shirt__, you must register [here](https://hacktoberfest.digitalocean.com/) and make four Pull Requests (PRs) between October 1-31, 2022 (in any time zone). PRs can be made to any public repo on GitHub, not only the ones with issues labeled Hacktoberfest. This year, the __first 40,000__ participants who complete the challenge will earn a T-shirt.
23 |
--------------------------------------------------------------------------------
/Sets.py:
--------------------------------------------------------------------------------
1 | #set :- {1,2,3,4}-unique and unordered
2 | '''
3 | Sets are initialized using curly braces {} or set() in python.
4 | A python set is basically an unordered collection of unique values, i.e. it will
5 | automatically remove duplicate values from the set.
6 | '''
7 | set1 = {1,2,3}
8 | print('set : ',set1)
9 | set2 = set(['tea','coffee','colddrink','soda','tea','Coffee'])
10 | print('set : ',set2)
11 | dup_set={1,1,1,1,1,2,2,2,4,4,56,5,5,4,6,4,56,4,4,5,4,5}
12 | print(dup_set)
13 |
14 | #using the add() method we can add single element in the set
15 | dup_set.add(456)
16 | print(dup_set)
17 |
18 | #using the update() method we can add multiple elements in the set
19 | dup_set.update(['water','drink','coca'])
20 | print(dup_set)
21 |
22 | #deleting an element within the set
23 | dup_set.remove(1)
24 | # dup_set.remove(1)#IF ELEMETN IS NOT PRESENT IN THE SET THEN remove() method raise an error
25 | print('after deleting : ', dup_set)
26 |
27 | #discard method does not raise an error
28 | dup_set.discard(2)
29 | dup_set.discard(12)#doesn't raise an error
30 | print("after discarding", dup_set)
31 |
32 |
33 | #OPERATORS IN THE SETS
34 | """
35 | | (Union)->Returns all the unique elements in both the sets.
36 | & (Intersection) -> Returns all the elements common to both the sets.
37 | - (Difference)-> Returns the elements that are unique to the first set
38 | ^(Symmetric Difference) -> Returns all the elements not common to both the sets.
39 |
40 | """
41 | set_A={1,5,2,84,2,4,5}
42 | print('Set A : ', set_A)
43 |
44 | set_B ={2,5,32,4,2,8,5,6}
45 | print('Set B : ', set_B)
46 |
47 | #intersection of two sets
48 | print('Intersection : ',set_A&set_B)
49 |
50 | #union of two sets
51 | print('Union : ', set_A|set_B)
52 |
53 | #difference of two sets
54 | print('Difference :', set_A-set_B)#consider only unique in first set(not consider common with other sets )
55 |
56 | #symetric difference of two sets
57 | print("Symetric Difference : ",set_A^set_B)#neglact the common in both sets
--------------------------------------------------------------------------------
/Sorting_List.py:
--------------------------------------------------------------------------------
1 |
2 | #Sorting list in lexicographic order
3 | example_list = ['pineapple','banana','vaaabbbcc','apple','grapes','orange']
4 | print('before Sorting : ',example_list)
5 | example_list.sort()
6 | print('after Sorting : ', example_list)
7 |
8 | #sorting list in ascending order
9 | example=[3,5,7,21,5,6,78,4,1,0,4]
10 | print('before Sorting :',example)
11 | example.sort()
12 | print('Sort in Ascending order : ', example)
13 |
14 | #sorting list in descending order
15 | example2=[3,5,7,21,5,6,78,4,1,0,4]
16 | print('before Sorting :',example2)
17 | example2.sort(reverse=True)
18 | print('Sort in descending order : ', example2)
19 |
--------------------------------------------------------------------------------
/Sple_Exception.py:
--------------------------------------------------------------------------------
1 | def divid(a , divisor):
2 | try:
3 | return a/divisor
4 | except ZeroDivisionError as e:
5 | print('Divisor never be Zero !! Error Divide Terminating')
6 | finally:
7 | print('$$$$ divide successful $$$$')
8 |
9 | print(divid(34,1))
10 | print('program end.')
--------------------------------------------------------------------------------
/Standard_Function.py:
--------------------------------------------------------------------------------
1 | #1 print()
2 | var = 'hello learners'
3 | print(var)
4 | print('This is line no.',4 )
5 | print(123486)
6 | a=[3,5,74,7]
7 | print(a)
8 | a='hello, '
9 | b='rishabh '
10 | print(a+b+'yadav')
11 |
12 | #2 input()
13 | a = input() #number input in a
14 | print('this is a = {}'.format(a))
15 | a=input()
16 | print(a)
17 | myName=input()
18 | print('Hello, {}'.format(myName))
19 |
20 | #3 len()-The len() function is used find the length(number of elements)
21 | # of any python container like string, list, dictionary, tuple, etc.
22 | a='hello '
23 | print(len(a))
24 | b="good boy"#for string
25 | print(len(b))
26 | a=[4,5,74,3,4]#for list
27 | print(len(a))
28 | a=('x','y','z')#for tuples
29 | print(a)
30 | print(len(a))
31 |
32 |
33 | #4 ord() - The ord() function in Python will return an
34 | #integer that represents the Unicode Character passed into it.
35 | #It takes a single character as a parameter.
36 |
37 | print(ord('a'))
38 | print(ord('b'))
39 | print(ord('A'))
40 | print(ord('$'))
--------------------------------------------------------------------------------
/Star.py:
--------------------------------------------------------------------------------
1 | from turtle import *
2 |
3 | drawing_area = Screen()
4 | drawing_area.setup(width=750, height=500)
5 | shape('triangle')
6 |
7 |
8 | def draw_triangle(length=150):
9 | for i in range(3):
10 | forward(length)
11 | left(120)
12 |
13 |
14 | for i in range(40):
15 | draw_triangle()
16 | right(10)
17 |
18 | done()
--------------------------------------------------------------------------------
/Starting.py:
--------------------------------------------------------------------------------
1 | print("Starting python .........")
--------------------------------------------------------------------------------
/StringManuplation.py:
--------------------------------------------------------------------------------
1 | #Escapes sequences in string
2 | print('this is used to \n new line')
3 | print('this is used to \t tab escape')
4 | print('this is ued to print backslash \\')
5 | print('your\'s is written like this ')
6 |
7 |
8 |
9 | #multiple string
10 | a ='''\nthis hwo
11 | you
12 | can do
13 | this .
14 | using this you can write multiple lines
15 | as '''
16 | print(a)
17 |
18 | #String indexing
19 |
20 | print('\n')
21 | # p y t h o n
22 | # 0 1 2 3 4 5
23 | # -6 -5 -4 -3 -2 -1
24 | p = 'python'
25 | print(p[0],p[2],p[4],p[5])
26 | print(p[-1],p[-2],p[-4],p[-6])
27 |
28 | # String slicing
29 | print(p[-6:-4])
30 | print(p[2:6])
31 | print(p[3:-1])
32 |
33 | # Case Conversion Functions
34 | first_name ='rishabh'
35 | #1 upper
36 | print('upper case - ',first_name.upper())
37 | last_name = 'YaDav'
38 | #2 lower
39 | print('lower case - ',last_name.lower())
40 | print('first name is lower or not - ',first_name.islower())
41 | print('last name is upper or not - ',last_name.isupper())
42 | print('first name is lower or not - ',first_name.upper().islower())
43 | print('last name is upper or not - ',last_name.upper().isupper())
44 |
45 | #string join() and split() function
46 | temp_list = ['hello','how ,are ,you']
47 | s=' '.join(temp_list)
48 | print(s)
49 | newlist = s.split(',')
50 | print(newlist)
51 |
52 | first = "first"
53 | second = "second"
54 | s = "Sunday is the {} day of the week, whereas Monday is the {} day of the week".format(first, second)
55 | print(s)
56 |
--------------------------------------------------------------------------------
/StringTemplate.py:
--------------------------------------------------------------------------------
1 | from string import Template
2 |
3 | nam = "Rishabh yadav"
4 | t = Template('hello ! $w ')
5 |
6 | print(t.substitute(w = nam))
--------------------------------------------------------------------------------
/String_demonstration_1.py:
--------------------------------------------------------------------------------
1 | # IN this we will see how to produce different output with same string
2 | s = "Bamboozled"
3 | # extract B a
4 | print(s[0], s[1]) # using normal indexing
5 | print(s[-10], s[-9]) # using negative indexing
6 | # extract e d
7 | print(s[8], s[9]) # using normal indexing
8 | print(s[-2], s[-1]) # using negative indexing
9 | # extract mboozled
10 | print(s[2:10]) # specifying from start to end
11 | print(s[2:]) # specifying from and not giving end
12 | print(s[-8:]) # using negative indexing
13 | # extract Bamboo
14 | print(s[0:6]) # using normal indexing
15 | print(s[:6]) #not speciying the first caharcter by speciying the last
16 | print(s[-10:-4])
17 | print(s[:-4])
18 | #reverse Bamboozled
19 | print(s[::-1])#this will reverse the Bamboozled
20 | print(s[0:10:1])
21 | print(s[0:10:2])#this will print after 2 character
22 | print(s[0:10:3])
23 | print(s[0:10:4])
24 | s=s+"Hype!"#concating the hype
25 | print(s)
26 | s=s[:6]+"Monger"+s[-1] #how to add any word in between
27 | print(s)
28 |
--------------------------------------------------------------------------------
/String_slicing.py:
--------------------------------------------------------------------------------
1 | str1 = "Lokesh is learning python"
2 | print(str1)
3 | # print(str1[:6]) print "Lokesh" because it's starting default value is 0
4 |
5 | # print(str1[0:]) print "Lokesh" because it's Last default value is string length
6 | # print(str1[:]) print complete string becuse starting default value is 0 and last value is string length
7 |
8 | # print(str1[1]) print o because index start from 0
9 |
10 | # print(len(str1)) print string length
11 |
12 | # print(str1[0:6]) print Lokesh and in this 0 is included and 6 is exclude it will go from 0 - (n-1), so we have to give 1 extra index
13 |
14 | # print(str1[0:25]) print complete string
15 |
16 | # print(str1[0:6:2]) print "Lks" because first it will go from[0:6] that is lokesh and then[0:6:2] means leave multiple of two or every second character.
17 |
--------------------------------------------------------------------------------
/Text repetition N number.py:
--------------------------------------------------------------------------------
1 | import pyautogui as pg
2 | import time
3 | time.sleep(10)
4 |
5 | for i in range(10): #range defines no of times
6 | pg.write('Enter your text')
7 | pg.press('Enter')
8 |
--------------------------------------------------------------------------------
/Time_difference.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from time import process_time
3 | pylist=[i for i in range(100)]
4 | start=process_time()
5 | pylist=[i+5 for i in pylist]
6 | end=process_time()
7 | print("Time taken by python list:",end-start)
8 | pyarray=np.array(pylist)
9 | start1=process_time()
10 | pyarray=pyarray+5
11 | end1=process_time()
12 | print("Time taken by numpy array:",end1-start1)
13 |
--------------------------------------------------------------------------------
/Tuples.py:
--------------------------------------------------------------------------------
1 | #Tuples in python
2 | '''
3 | Tuples are entities in Python that work almost similar to that of lists, but differ in the
4 | main feature from lists, is in that they are inmutable.
5 | They are initialized by writing the elements of the tuple with (), separated by
6 | commas.
7 | '''
8 |
9 | #Defining and initializing a tuple name - example
10 | example = ('first','second','third','fourth')
11 | # example[1]="pahela" #This is not supported by tuple
12 | print(example)
13 | print(example[0])
14 | print(example[3])
15 | print(example[1:3])#print the indexno.-1 , indexno.-2
16 |
17 |
18 | #type converting between tuple ,lists and strings
19 | demo_list = list(example)
20 | print('Tuple converted into list -> ',demo_list)
21 |
22 | demo_tuple = tuple(demo_list)
23 | print('List converted into tuple : ',demo_tuple)
24 |
25 | list_string = list('rishabh')
26 | tuple_string = tuple('rishabh')
27 | print(list_string)
28 | print(tuple_string)
--------------------------------------------------------------------------------
/Type_Casting.py:
--------------------------------------------------------------------------------
1 | """
2 | TYPE CASTING - Two types
3 | 1. Implicit type casting--->: In implicit type casting, the python compiler
4 | internally typecasts one variable into another type without the external
5 | action of the user.
6 |
7 | Example:-
8 |
9 | """
10 | int_num=4
11 | float_num=7.9
12 | ans = int_num+float_num
13 | print('Int num type =',type(int_num))
14 | print('ans num type = ',type(ans))
15 | #ans is automatic typed casted
16 | # into float type for greater precision
17 | print('Float num type = ',type(float_num))
18 |
19 |
20 | #Explicit Type Casting: In explicit type casting, the user
21 | # explicitly forces the compiler to convert a variable
22 | # from one type to another. The different ways of
23 | # explicit typecasting are given below:
24 |
25 | #1.)Integer to String or Float:
26 | """
27 | To typecast an integer into a string type,
28 | we use the str() method. Similarly, to typecast
29 | it into a float type, we use the float() method.
30 | For example:
31 | """
32 |
33 | var = 123
34 | print("this is string-"+str(var))
35 | var = 23
36 | print(float(var))
37 |
38 | #2.) Float to integer
39 |
40 | f=56.39
41 | print(int(f))
42 |
43 |
--------------------------------------------------------------------------------
/Variable_AssignMulti_val_c3.py:
--------------------------------------------------------------------------------
1 | #Many value to multiple variable
2 | x , y, z = "mohan","shyam","Hari"
3 | print(x)
4 | print(y)
5 | print(z)
6 | print()
7 | print()
8 | x , y, z = "mohan",5.9,2
9 | print(x)
10 | print(y)
11 | print(z)
12 | print()
13 | print()
14 | #One value to multiple vaiable
15 | x = y =z = "ram"
16 | print(x)
17 | print(y)
18 | print(z)
19 |
20 |
21 | #Unpack a Collection
22 | #If you have a collection of values in a list, tuple etc.
23 | # Python allows you to extract the values into variables.
24 | # This is called unpacking.
25 |
26 | #Example
27 |
28 | fruits = ["mango", 14 , "orange",45 , "apple",1]
29 | m,w,o,ow,a,aw=fruits
30 | print(m)
31 | print(w)
32 | print(o)
33 | print(ow)
34 | print(a)
35 | print(aw)
--------------------------------------------------------------------------------
/Variable_GlobalVariable.py:
--------------------------------------------------------------------------------
1 | x = "awesome"#x is global variable
2 | def myfunction():
3 | print("This is value of Global Variable : "+ x)
4 | print()
5 |
6 |
7 | myfunction()
8 | print()
9 |
10 | g = "awesome"#global variable
11 | def myfun():
12 | g="fantastic"#Value of g is changed at local level
13 | print("Python is "+ g)
14 |
15 | myfun()
16 | print("Python is : "+ g)#global value printed
17 | print()
18 | print()
19 |
20 | #Global keyword
21 | #To create a global variable inside a function, you can use the global keyword.
22 |
23 | #Example
24 | def fun1():
25 | global x
26 | x = "fantastic "
27 |
28 | fun1()
29 | print("Python is "+ x )
30 | print()
31 |
32 | #Example
33 | #To change the value of a global variable inside a function,
34 | # refer to the variable by using the global keyword:
35 | x="fantastic"
36 | def fun1():
37 | global x
38 | x = "awesome "
39 |
40 | fun1()
41 | print("Python is "+ x )
42 |
--------------------------------------------------------------------------------
/Variable_c1.py:
--------------------------------------------------------------------------------
1 | from tkinter import DoubleVar
2 | from tokenize import Double
3 |
4 |
5 | x = 5 # this is int type value
6 | y= "Rishabh" # this is string type value
7 | z = 5.4 # this float type value
8 | print("INT value - ", x)
9 | print ("String value - ", y)
10 | print ( "Float value - ",z)
11 |
12 |
13 | #Expilict type casting the data types
14 | x = float(5) #float type data - 5.0
15 | y=int(2) #int type data - 2
16 | z = str("yadav")#str type data - yadav
17 |
18 | print("INT value - ", y)
19 | print ("String value - ", z)
20 | print ( "Float value - ",x)
21 |
22 |
23 |
24 | """
25 | Get the Type
26 | You can get the data type of a variable with the type() function.
27 | """
28 |
29 | x = 4
30 | y= "str"
31 | # is same as
32 | z='str'
33 |
34 | print(type(x))
35 | print(type(y))
36 | print(z)
37 | print (type(z))
38 |
39 | """
40 | Case-Sensitive
41 | Variable names are case-sensitive.
42 | """
43 |
44 | A = 'rishabh yadav'
45 | a = 'rakesh singh'
46 | # a doesn't overwrite A means a and A both are different
47 | print(A)
48 | print(a)
49 |
--------------------------------------------------------------------------------
/Variable_names_c2.py:
--------------------------------------------------------------------------------
1 | """
2 | Variable Names
3 | A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:
4 | A variable name must start with a letter or the underscore character
5 | A variable name cannot start with a number
6 | A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
7 | Variable names are case-sensitive (age, Age and AGE are three different variables)
8 | """
9 | #Legal variable names:
10 |
11 | myvar = "Mohan"
12 | my_var = "Mohan"
13 | _my_var = "Mohan"
14 | myVar = "Mohan"
15 | MYVAR = "Mohan"
16 | myvar2 = "Mohan"
17 |
18 | """
19 | Illegal variable names:
20 |
21 | 2myvar = "John"
22 | my-var = "John"
23 | my var = "John"
24 |
25 |
26 | """
27 |
28 | """
29 |
30 | Multi Words Variable Names
31 | Variable names with more than one word can be difficult to read.
32 |
33 | There are several techniques you can use to make them more readable:
34 | """
35 | #Camel Case
36 | #Each word, except the first, starts with a capital letter:
37 |
38 | myVariableName = "Mohan"
39 |
40 | #Pascal Case
41 | #Each words starts with capital letter ;
42 |
43 | MyVariableName="Mohan"
44 |
45 | #snake case
46 | #Each word is seperated by underscore charchater
47 |
48 | my_variable_name="Mohan"
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/Variables_print_c4.py:
--------------------------------------------------------------------------------
1 | #print(x) print is used to variable x
2 | x = "I am Starting learning Python "
3 | print(x)
4 |
5 | a="I "
6 | b='am '
7 | c='starting '
8 | d='learning '
9 | e = 'python '
10 | print (a+b+c+d+e)
11 |
12 | print("I "+"am "+"Starting "+"learning " +"Python ")
13 |
14 | v1=5
15 | v2 = 'rakesh'
16 | print(v1,v2);
17 | print('mohan', 45)
18 | #You can't print like this -
19 | #print(v1+v2)
20 |
21 | v0,v1=6,8
22 | print(v0+v1)
23 | print (6+8)
24 |
--------------------------------------------------------------------------------
/addvolumfrendfunc.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std;
4 | class Cuboid;
5 | class Sphere
6 | {
7 | private:
8 | int radius;
9 | double volume;
10 |
11 | public:
12 | void Acceptdata()
13 | {
14 | cout << "Enter the radius:";
15 | cin >> radius;
16 | }
17 | void CalculateVolume()
18 | {
19 | volume = 4 / 3.0 * 3.14 * radius * radius * radius;
20 | }
21 | void Display()
22 | {
23 | cout << "The volume of Sphere is :" << volume << endl;
24 | }
25 | friend void AddVolume(Sphere sph, Cuboid cbd);
26 | };
27 |
28 | class Cuboid
29 | {
30 | private:
31 | int length, breadth, height;
32 | double volume;
33 |
34 | public:
35 | void AcceptData()
36 | {
37 | cout << "Enter the length:";
38 | cin >> length;
39 | cout << "Enter the breadth:";
40 | cin >> breadth;
41 | cout << "Enter the height:";
42 | cin >> height;
43 | }
44 | void CalculateVolume()
45 | {
46 | volume = length * breadth * height;
47 | }
48 | void Display()
49 | {
50 | cout << "The volume of Sphere is:" << volume << endl;
51 | }
52 | };
53 |
--------------------------------------------------------------------------------
/balanced_paranthesis.py:
--------------------------------------------------------------------------------
1 | """
2 | To check the paranthesis balance.
3 | Example:
4 |
5 | Test: {[]{()}}
6 | Output: Balanced
7 |
8 | Test: ((()
9 | Output: Unbalanced
10 | """
11 |
12 | def is_paranthesis_balanced(expression):
13 | open_tup = tuple('({[')
14 | close_tup = tuple(')}]')
15 |
16 | map = dict(zip(open_tup, close_tup))
17 | queue = []
18 |
19 | for i in expression:
20 | if i in open_tup:
21 | queue.append(map[i])
22 | elif i in close_tup:
23 | if not queue or i!=queue.pop():
24 | return "Unbalanced"
25 | if not queue:
26 | return "Balanced"
27 | else:
28 | return "Unbalanced"
29 |
30 | # Driver code
31 | print("{[]{()}}", "->", is_paranthesis_balanced("{[]{()}}"))
32 | print("((()", "->", is_paranthesis_balanced("((()"))
--------------------------------------------------------------------------------
/basicDoublyLinkedlist.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | class Node{
4 | public:
5 | int data;
6 | Node* next;
7 | Node* prev;
8 | Node(int data)
9 | {
10 | this->data=data;
11 | this->next=NULL;
12 | this->prev=NULL;
13 | }
14 |
15 | ~Node()
16 | {
17 | int value=this->data;
18 | if(this->next!=NULL)
19 | {
20 | delete next;
21 | // this->next=NULL;
22 | }
23 | cout<<"Memory is free for : "<prev=temp;
36 | temp->next=head;
37 | head=temp;
38 | }
39 | }
40 | void insertAtTail(Node* &tail,Node* &head,int d)
41 | {
42 | if(tail==NULL)
43 | {
44 | Node* temp=new Node(d);
45 | tail=temp;
46 | head=temp;
47 | }
48 | else{
49 | Node* temp=new Node(d);
50 | tail->next=temp;
51 | temp->prev=tail;
52 | tail=temp;
53 | }
54 | }
55 | void insertAtPosition(Node* & tail,Node* &head,int position,int d)
56 | {
57 | if(position==1)
58 | {
59 | insertAtHead(tail,head,d);
60 | return;
61 | }
62 | int cnt=1;
63 | Node* temp=head;
64 | while(cntnext;
67 | cnt++;
68 | }
69 | if(temp->next==NULL)
70 | {
71 | insertAtTail(tail,head,d);
72 | return;
73 | }
74 | Node* nodeToInsert=new Node(d);
75 | nodeToInsert->next=temp->next;
76 | temp->next->prev=nodeToInsert;
77 | temp->next=nodeToInsert;
78 | nodeToInsert->prev=temp;
79 | }
80 | void deleteAtPosition(Node*& head,int position)
81 | {
82 | if(position==1)
83 | {
84 | Node* temp=head;
85 | temp->next->prev=NULL;
86 | head=head->next;
87 | temp->next=NULL;
88 | delete temp;
89 | }
90 | else{
91 | Node* previous=NULL;
92 | Node* curr=head;
93 | int cnt=1;
94 | while(cntnext;
98 | cnt++;
99 | }
100 | curr->prev=NULL;
101 | previous->next=curr->next;
102 | curr->next=NULL;
103 | delete curr;
104 | }
105 | }
106 | void print(Node* &head)
107 | {
108 | Node*temp=head;
109 | while(temp!=NULL)
110 | {
111 | cout<data<<" ";
112 | temp=temp->next;
113 | }
114 | cout<
2 | using namespace std;
3 |
4 | int main(){
5 | stacks;
6 | s.push(1);
7 | s.push(2);
8 | s.push(3);
9 | s.push(4);
10 | s.push(5);
11 | s.push(6);
12 | while(!s.empty())
13 | {
14 | cout<
2 | using namespace std;
3 |
4 | int binarysearch(int n, int arr[], int key)
5 | {
6 | int l = 0;
7 | int r = n - 1;
8 | int mid = (l + r) / 2;
9 | while (l <= r)
10 | {
11 | int mid = (l + r) / 2;
12 | if (key == arr[mid])
13 | {
14 | return mid;
15 | }
16 | else if (key < arr[mid])
17 | {
18 | r = mid - 1;
19 | }
20 | else if (key > arr[mid])
21 | {
22 | l = mid + 1;
23 | }
24 | }
25 | return -1;
26 | }
27 |
28 | int main()
29 | {
30 | int n;
31 | cin >> n;
32 | int arr[n];
33 | for (int i = 0; i < n; i++)
34 | {
35 | cin >> arr[i];
36 | }
37 | int key;
38 | cin >> key;
39 | cout << binarysearch(n, arr, key);
40 | return 0;
41 | }
--------------------------------------------------------------------------------
/bucketSort.py:
--------------------------------------------------------------------------------
1 | # Python3 program to sort an array
2 | # using bucket sort
3 | def insertionSort(b):
4 | for i in range(1, len(b)):
5 | up = b[i]
6 | j = i - 1
7 | while j >= 0 and b[j] > up:
8 | b[j + 1] = b[j]
9 | j -= 1
10 | b[j + 1] = up
11 | return b
12 |
13 | def bucketSort(x):
14 | arr = []
15 | slot_num = 10 # 10 means 10 slots, each
16 | # slot's size is 0.1
17 | for i in range(slot_num):
18 | arr.append([])
19 |
20 | # Put array elements in different buckets
21 | for j in x:
22 | index_b = int(slot_num * j)
23 | arr[index_b].append(j)
24 |
25 | # Sort individual buckets
26 | for i in range(slot_num):
27 | arr[i] = insertionSort(arr[i])
28 |
29 | # concatenate the result
30 | k = 0
31 | for i in range(slot_num):
32 | for j in range(len(arr[i])):
33 | x[k] = arr[i][j]
34 | k += 1
35 | return x
36 |
37 | # Driver Code
38 | x = [0.897, 0.565, 0.656,
39 | 0.1234, 0.665, 0.3434]
40 | print("Sorted Array is")
41 | print(bucketSort(x))
42 |
43 | # This code is contributed by
44 | # Oneil Hsiao
45 |
--------------------------------------------------------------------------------
/buzz num.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | int main()
3 | {
4 | int n=0;
5 | printf("enter a num");
6 | scanf("%d",&n);
7 | if(n%7==0 or n%10==7)
8 | {
9 | printf("buzz num");
10 | }
11 | else
12 | {
13 | printf("not buzz");
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/calculator.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "metadata": {},
7 | "outputs": [
8 | {
9 | "name": "stdout",
10 | "output_type": "stream",
11 | "text": [
12 | "Select operation.\n",
13 | "1.Add\n",
14 | "2.Subtract\n",
15 | "3.Multiply\n",
16 | "4.Divide\n"
17 | ]
18 | }
19 | ],
20 | "source": [
21 | "def add(x, y):\n",
22 | " return x + y\n",
23 | "\n",
24 | "# This function subtracts two numbers\n",
25 | "def subtract(x, y):\n",
26 | " return x - y\n",
27 | "\n",
28 | "# This function multiplies two numbers\n",
29 | "def multiply(x, y):\n",
30 | " return x * y\n",
31 | "\n",
32 | "# This function divides two numbers\n",
33 | "def divide(x, y):\n",
34 | " return x / y\n",
35 | "\n",
36 | "\n",
37 | "print(\"Select operation.\")\n",
38 | "print(\"1.Add\")\n",
39 | "print(\"2.Subtract\")\n",
40 | "print(\"3.Multiply\")\n",
41 | "print(\"4.Divide\")\n",
42 | "\n",
43 | "while True:\n",
44 | " # take input from the user\n",
45 | " choice = input(\"Enter choice(1/2/3/4): \")\n",
46 | "\n",
47 | " # check if choice is one of the four options\n",
48 | " if choice in ('1', '2', '3', '4'):\n",
49 | " num1 = float(input(\"Enter first number: \"))\n",
50 | " num2 = float(input(\"Enter second number: \"))\n",
51 | "\n",
52 | " if choice == '1':\n",
53 | " print(num1, \"+\", num2, \"=\", add(num1, num2))\n",
54 | "\n",
55 | " elif choice == '2':\n",
56 | " print(num1, \"-\", num2, \"=\", subtract(num1, num2))\n",
57 | "\n",
58 | " elif choice == '3':\n",
59 | " print(num1, \"*\", num2, \"=\", multiply(num1, num2))\n",
60 | "\n",
61 | " elif choice == '4':\n",
62 | " print(num1, \"/\", num2, \"=\", divide(num1, num2))\n",
63 | " \n",
64 | " # check if user wants another calculation\n",
65 | " # break the while loop if answer is no\n",
66 | " next_calculation = input(\"Let's do next calculation? (yes/no): \")\n",
67 | " if next_calculation == \"no\":\n",
68 | " break\n",
69 | " \n",
70 | " else:\n",
71 | " print(\"Invalid Input\")\n"
72 | ]
73 | }
74 | ],
75 | "metadata": {
76 | "kernelspec": {
77 | "display_name": "Python 3.9.7 64-bit",
78 | "language": "python",
79 | "name": "python3"
80 | },
81 | "language_info": {
82 | "codemirror_mode": {
83 | "name": "ipython",
84 | "version": 3
85 | },
86 | "file_extension": ".py",
87 | "mimetype": "text/x-python",
88 | "name": "python",
89 | "nbconvert_exporter": "python",
90 | "pygments_lexer": "ipython3",
91 | "version": "3.9.7"
92 | },
93 | "orig_nbformat": 4,
94 | "vscode": {
95 | "interpreter": {
96 | "hash": "be195e74ed175410d6540ba025da5c4406bdff32be56f2bbb5032c9081165736"
97 | }
98 | }
99 | },
100 | "nbformat": 4,
101 | "nbformat_minor": 2
102 | }
103 |
--------------------------------------------------------------------------------
/cf mainik and array.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hariom20singh/python-learning-codes/820f8e22c4c66183ab4aca54cfcafe1a0792e057/cf mainik and array.bin
--------------------------------------------------------------------------------
/check prime or not.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | int main()
4 | {
5 | int n;
6 | cin>>n;
7 | for (int i=2; i<=n; i++){
8 | if (n%i==0){
9 | cout<<" it is prime "<< endl;
10 | break;
11 | }
12 | if (n%i!=0){
13 | cout<<"it is not a prime"< a[i + 1]):
20 | a[i], a[i + 1] = a[i + 1], a[i]
21 | swapped = True
22 |
23 | # if nothing moved, then array is sorted.
24 | if (swapped == False):
25 | break
26 |
27 | # otherwise, reset the swapped flag so that it
28 | # can be used in the next stage
29 | swapped = False
30 |
31 | # move the end point back by one, because
32 | # item at the end is in its rightful spot
33 | end = end-1
34 |
35 | # from right to left, doing the same
36 | # comparison as in the previous stage
37 | for i in range(end-1, start-1, -1):
38 | if (a[i] > a[i + 1]):
39 | a[i], a[i + 1] = a[i + 1], a[i]
40 | swapped = True
41 |
42 | # increase the starting point, because
43 | # the last stage would have moved the next
44 | # smallest number to its rightful spot.
45 | start = start + 1
46 |
47 |
48 | # Driver code
49 | a = [5, 1, 4, 2, 8, 0, 2]
50 | cocktailSort(a)
51 | print("Sorted array is:")
52 | for i in range(len(a)):
53 | print("% d" % a[i])
54 |
--------------------------------------------------------------------------------
/compherension.py:
--------------------------------------------------------------------------------
1 | #List compherension
2 | a = [1,2,3,4,5]
3 | print('List A : ',a)
4 | #b is store the multiply of 2 with a 's list element
5 | b=[i*2 for i in a]
6 | print('List B: ',b)
7 |
8 | #set compherension
9 | set_A = {4,5,2,4,2,5,4,6,8,2}
10 | #set_B is store the square of element in set_A
11 | set_B={i**2 for i in set_A}
12 | print('Set A : ',set_A)
13 | print('Set B : ',set_B)
14 |
15 |
16 | # Dict Comprehension:
17 | # It is a shorter syntax to create a new dictionary using values of an existing
18 | # dictionary.
19 | a = {'Hello':'World', 'First': 1}
20 | # b stores elements of a in value-key pair format
21 | b = {val: k for k , val in a.items()}
22 | print(b)
--------------------------------------------------------------------------------
/compressed_img.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hariom20singh/python-learning-codes/820f8e22c4c66183ab4aca54cfcafe1a0792e057/compressed_img.jpg
--------------------------------------------------------------------------------
/cycleSort.py:
--------------------------------------------------------------------------------
1 | # Python program to implement cycle sort
2 |
3 | def cycleSort(array):
4 | writes = 0
5 |
6 | # Loop through the array to find cycles to rotate.
7 | for cycleStart in range(0, len(array) - 1):
8 | item = array[cycleStart]
9 |
10 | # Find where to put the item.
11 | pos = cycleStart
12 | for i in range(cycleStart + 1, len(array)):
13 | if array[i] < item:
14 | pos += 1
15 |
16 | # If the item is already there, this is not a cycle.
17 | if pos == cycleStart:
18 | continue
19 |
20 | # Otherwise, put the item there or right after any duplicates.
21 | while item == array[pos]:
22 | pos += 1
23 | array[pos], item = item, array[pos]
24 | writes += 1
25 |
26 | # Rotate the rest of the cycle.
27 | while pos != cycleStart:
28 |
29 | # Find where to put the item.
30 | pos = cycleStart
31 | for i in range(cycleStart + 1, len(array)):
32 | if array[i] < item:
33 | pos += 1
34 |
35 | # Put the item there or right after any duplicates.
36 | while item == array[pos]:
37 | pos += 1
38 | array[pos], item = item, array[pos]
39 | writes += 1
40 |
41 | return writes
42 |
43 | # driver code
44 | arr = [1, 8, 3, 9, 10, 10, 2, 4 ]
45 | n = len(arr)
46 | cycleSort(arr)
47 |
48 | print("After sort : ")
49 | for i in range(0, n) :
50 | print(arr[i], end = ' ')
51 |
52 |
--------------------------------------------------------------------------------
/cyclic sort.java:
--------------------------------------------------------------------------------
1 | // java program to check implement cycle sort
2 | import java.util.*;
3 | public class MissingNumber {
4 | public static void main(String[] args)
5 | {
6 | int[] arr = { 3, 2, 4, 5, 1 };
7 | int n = arr.length;
8 | System.out.println("Before sort :");
9 | System.out.println(Arrays.toString(arr));
10 | CycleSort(arr, n);
11 |
12 | }
13 |
14 | static void CycleSort(int[] arr, int n)
15 | {
16 | int i = 0;
17 | while (i < n) {
18 |
19 | int correctpos = arr[i] - 1;
20 | if (arr[i] < n && arr[i] != arr[correctpos]) {
21 |
22 | swap(arr, i, correctpos);
23 | }
24 | else {
25 |
26 | i++;
27 | }
28 | }
29 | System.out.println("After sort : ");
30 | System.out.print(Arrays.toString(arr));
31 |
32 |
33 | }
34 |
35 | static void swap(int[] arr, int i, int correctpos)
36 | {
37 |
38 | int temp = arr[i];
39 | arr[i] = arr[correctpos];
40 | arr[correctpos] = temp;
41 | }
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/deleating_of_node.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std;
4 |
5 | struct node
6 | {
7 | int data;
8 | struct node *next;
9 | };
10 |
11 | void trivarsal(struct node *ptr)
12 | {
13 | while (ptr != NULL)
14 | {
15 | cout << "Element are :- " << ptr->data << endl;
16 | ptr = ptr->next;
17 | }
18 | }
19 | // case 1 --> delete at first
20 | // struct node *Deleteatfirst(struct node *head){
21 | // struct node *ptr=head;
22 | // head=head->next;
23 | // free(ptr);
24 | // return head;
25 | // }
26 |
27 | // case 2 --> deletion a element at given index
28 | // struct node *DeleteAtIndex(struct node *head,int index){
29 | // struct node *ptr=head;
30 | // struct node *q = head->next;
31 | // for(int i=0;inext;
33 | // q->next;
34 | // }
35 | // ptr->next = q->next;
36 | // free(q);
37 | // return head;
38 |
39 |
40 |
41 | // case 3 :- delete at last element
42 | struct node *DeleteAtLast(struct node *head){
43 | struct node *p = head;
44 | struct node *q = head->next;
45 | while(q->next != NULL){
46 | p= p->next;
47 | q= p->next;
48 | }
49 | p ->next = NULL;
50 | free(q);
51 | return head;
52 | }
53 |
54 |
55 | int main()
56 | {
57 | struct node *head;
58 | struct node *second;
59 | struct node *third;
60 | struct node *fourth;
61 | struct node *fifth;
62 | struct node *six;
63 | struct node *seven;
64 | struct node *eight;
65 | head = (struct node *)malloc(sizeof(struct node));
66 | second = (struct node *)malloc(sizeof(struct node));
67 | third = (struct node *)malloc(sizeof(struct node));
68 | fourth = (struct node *)malloc(sizeof(struct node));
69 | fifth = (struct node *)malloc(sizeof(struct node));
70 | six = (struct node *)malloc(sizeof(struct node));
71 | seven = (struct node *)malloc(sizeof(struct node));
72 | eight = (struct node *)malloc(sizeof(struct node));
73 |
74 | head->data = 1;
75 | head->next = second;
76 |
77 | second->data = 2;
78 | second->next = third;
79 |
80 | third->data = 3;
81 | third->next = fourth;
82 |
83 | fourth->data = 4;
84 | fourth->next =fifth;
85 |
86 | fifth->data = 5;
87 | fifth->next =six;
88 |
89 | six->data = 6;
90 | six->next =seven;
91 |
92 | seven->data = 7;
93 | seven->next =eight;
94 |
95 | eight->data = 8;
96 | eight->next = NULL;
97 |
98 | cout<<"before deletion :- "< i:
6 | # display space
7 | print(' ', end=' ')
8 | j -= 1
9 | print('*', end=' ')
10 | k = 1
11 | while k < 2 * (i - 1):
12 | print(' ', end=' ')
13 | k += 1
14 | if i == 1:
15 | print()
16 | else:
17 | print('*')
18 | i += 1
19 |
20 | i = rows - 1
21 | while i >= 1:
22 | j = rows
23 | while j > i:
24 | print(' ', end=' ')
25 | j -= 1
26 | print('*', end=' ')
27 | k = 1
28 | while k <= 2 * (i - 1):
29 | print(' ', end=' ')
30 | k += 1
31 | if i == 1:
32 | print()
33 | else:
34 | print('*')
35 | i -= 1
36 |
--------------------------------------------------------------------------------
/diamond_pattern.py:
--------------------------------------------------------------------------------
1 | n=int(input("enter the number of rows"))
2 |
3 | for i in range(n):
4 |
5 | for j in range(1,int((n/2))-i+3):
6 |
7 | print(sep=" ",end=" ")
8 |
9 | for k in range(1,i+2):
10 |
11 | print("*", end=" ")
12 |
13 |
14 |
15 | print()
16 |
17 | for i in range(n):
18 |
19 | for j in range(1,5-(int((n/2))-i+3)+2):
20 |
21 | print(sep=" ",end=" ")
22 |
23 | for k in range(1,5-i):
24 |
25 | print("*", end=" ")
26 |
27 | print()
--------------------------------------------------------------------------------
/doublyLinkedList.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data):
3 | self.item = data
4 | self.next = None
5 | self.prev = None
6 | # Class for doubly Linked List
7 | class doublyLinkedList:
8 | def __init__(self):
9 | self.start_node = None
10 | # Insert Element to Empty list
11 | def InsertToEmptyList(self, data):
12 | if self.start_node is None:
13 | new_node = Node(data)
14 | self.start_node = new_node
15 | else:
16 | print("The list is empty")
17 | # Insert element at the end
18 | def InsertToEnd(self, data):
19 | # Check if the list is empty
20 | if self.start_node is None:
21 | new_node = Node(data)
22 | self.start_node = new_node
23 | return
24 | n = self.start_node
25 | # Iterate till the next reaches NULL
26 | while n.next is not None:
27 | n = n.next
28 | new_node = Node(data)
29 | n.next = new_node
30 | new_node.prev = n
31 | # Delete the elements from the start
32 | def DeleteAtStart(self):
33 | if self.start_node is None:
34 | print("The Linked list is empty, no element to delete")
35 | return
36 | if self.start_node.next is None:
37 | self.start_node = None
38 | return
39 | self.start_node = self.start_node.next
40 | self.start_prev = None;
41 | # Delete the elements from the end
42 | def delete_at_end(self):
43 | # Check if the List is empty
44 | if self.start_node is None:
45 | print("The Linked list is empty, no element to delete")
46 | return
47 | if self.start_node.next is None:
48 | self.start_node = None
49 | return
50 | n = self.start_node
51 | while n.next is not None:
52 | n = n.next
53 | n.prev.next = None
54 | def counting_nodes(self):
55 | n = self.start_node
56 | t=0
57 | while n is not None:
58 | t=t+1
59 | n=n.next
60 | print(f"No of nodes is {t}")
61 |
62 | # Traversing and Displaying each element of the list
63 | def duplicate(self):
64 | lis2=[]
65 | n = self.start_node
66 | while n is not None:
67 | if n.item in lis2:
68 | n.prev.next=n.next
69 | else:
70 |
71 | lis2.append(n.item)
72 |
73 |
74 | n=n.next
75 | # for i in range(len(lis2)):
76 | # print(f"Element is: {lis2[i]}")
77 | self.Display()
78 |
79 | def Display(self):
80 | if self.start_node is None:
81 | print("The list is empty")
82 | return
83 | else:
84 | n = self.start_node
85 | while n is not None:
86 | print("Element is: ", n.item)
87 | n = n.next
88 | print("\n")
89 | # Create a new Doubly Linked List
90 | NewDoublyLinkedList = doublyLinkedList()
91 | # Insert the element to empty list
92 | n=int(input("Enter the no nodes\n"))
93 | lis=[]
94 | print("Enter the element\n")
95 | for i in range(n):
96 | a=int(input())
97 | lis.append(a)
98 | NewDoublyLinkedList.InsertToEmptyList(lis[0])
99 | # Insert the element at the end
100 | for i in range(1,n):
101 |
102 | NewDoublyLinkedList.InsertToEnd(lis[i])
103 |
104 |
105 | NewDoublyLinkedList.Display()
106 | # Counting the nodes
107 | NewDoublyLinkedList.counting_nodes()
108 | # Deleting last two elements
109 | NewDoublyLinkedList.delete_at_end()
110 | NewDoublyLinkedList.delete_at_end()
111 | print("After deleting element\n")
112 | # Counting the nodes
113 | NewDoublyLinkedList.counting_nodes()
114 | # Display Data
115 | NewDoublyLinkedList.Display()
116 | # removing duplicate
117 | print("\nRemoving duplicate\n")
118 | NewDoublyLinkedList.duplicate()
119 |
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/euclidGCD.py:
--------------------------------------------------------------------------------
1 | # Python code to demonstrate naive
2 | # method to compute gcd ( recursion )
3 |
4 |
5 | def hcf(a, b):
6 | if(b == 0):
7 | return a
8 | else:
9 | return hcf(b, a % b)
10 |
11 | a = 60
12 | b = 48
13 |
14 | # prints 12
15 | print("The gcd of 60 and 48 is : ", end="")
16 | print(hcf(60, 48))
17 |
--------------------------------------------------------------------------------
/factorial_of _num.py:
--------------------------------------------------------------------------------
1 | # Python 3 program to find
2 | # factorial of given number
3 | def factorial(n):
4 | if n < 0:
5 | return 0
6 | elif n == 0 or n == 1:
7 | return 1
8 | else:
9 | fact = 1
10 | while(n > 1):
11 | fact *= n
12 | n -= 1
13 | return fact
14 |
15 | # Driver Code
16 | num = 5
17 | print("Factorial of",num,"is",
18 | factorial(num))
19 |
20 |
21 |
--------------------------------------------------------------------------------
/fibonacci_numbers.py:
--------------------------------------------------------------------------------
1 | # Function for nth Fibonacci number
2 | def Fibonacci(n):
3 |
4 | # Check if input is 0 then it will
5 | # print incorrect input
6 | if n < 0:
7 | print("Incorrect input")
8 |
9 | # Check if n is 0
10 | # then it will return 0
11 | elif n == 0:
12 | return 0
13 |
14 | # Check if n is 1,2
15 | # it will return 1
16 | elif n == 1 or n == 2:
17 | return 1
18 |
19 | else:
20 | return Fibonacci(n-1) + Fibonacci(n-2)
21 |
22 | # Driver Program
23 | print(Fibonacci(9))
24 |
25 | # This code is contributed by Saket Modi
26 | # then corrected and improved by Himanshu Kanojiya
27 |
--------------------------------------------------------------------------------
/findd_Factorial.py:
--------------------------------------------------------------------------------
1 | def print_factors(x):
2 | print("The factors of",x,"are:")
3 | for i in range(1, x + 1):
4 | if x % i == 0:
5 | print(i)
6 |
7 | num = 320
8 |
9 | print_factors(num)
--------------------------------------------------------------------------------
/findurl.py:
--------------------------------------------------------------------------------
1 | # Python code to find the URL from an input string
2 | # Using the regular expression
3 | import re
4 |
5 | def Find(string):
6 |
7 | # findall() has been used
8 | # with valid conditions for urls in string
9 | regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
10 | url = re.findall(regex,string)
11 | return [x[0] for x in url]
12 |
13 | # Driver Code
14 | string = 'My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/'
15 | print("Urls: ", Find(string))
16 |
--------------------------------------------------------------------------------
/game.py:
--------------------------------------------------------------------------------
1 | i=input('Wanna play tic tac toe \n yes or no:')
2 | if i=='yes':
3 | print('so lets go!!')
4 | v=input('which character do u want,x or o?')
5 | n=v.lower()
6 | if n=='x':
7 | print('player1=',n)
8 | print('player2=o')
9 | elif n=='o':
10 | print('player1=o')
11 | print('player2=x')
12 | elif i=='no':
13 | print('thank u')
14 | if i=='yes':
15 |
16 | Win = 1
17 |
18 | Draw = -1
19 |
20 | Running = 0
21 |
22 | Stop = 1
23 | board=['-','-','-',
24 | '-','-','-',
25 | '-','-','-']
26 | print(board[0],'I',board[1],'I',board[2])
27 | print('-----------')
28 | print(board[3],'I',board[4],'I',board[5])
29 | print('-----------')
30 | print(board[6],'I',board[7],'I',board[8])
31 | def CheckPosition(v):
32 | if(board[v] == ' '):
33 |
34 | return True
35 | else:
36 | return False
37 | k=0
38 | while k<9:
39 | i= int(input('player 1:select a spot:'))
40 | if v=='x':
41 | if board[i]!='x' and board[i]!='o':
42 | board[i]=v
43 | print(board[0],'I',board[1],'I',board[2])
44 | print('-----------')
45 | print(board[3],'I',board[4],'I',board[5])
46 | print('-----------')
47 | print(board[6],'I',board[7],'I',board[8])
48 | j=int(input('player2-select a spot:'))
49 | if board[j]!='x' and board[j]!='o':
50 | board[j]='o'
51 | print(board[0],'I',board[1],'I',board[2])
52 | print('-----------')
53 | print(board[3],'I',board[4],'I',board[5])
54 | print('-----------')
55 | print(board[6],'I',board[7],'I',board[8])
56 | k=k+1
57 | else:
58 | if v=='o':
59 | if board[i]!='x' and board[i]!='o':
60 | board[i]=v
61 | print(board[0],'I',board[1],'I',board[2])
62 | print('-----------')
63 | print(board[3],'I',board[4],'I',board[5])
64 | print('-----------')
65 | print(board[6],'I',board[7],'I',board[8])
66 | j=int(input('player2-select a spot'))
67 | if board[j]!='x' and board[j]!='o':
68 | board[j]='x'
69 | print(board[0],'I',board[1],'I',board[2])
70 | print('-----------')
71 | print(board[3],'I',board[4],'I',board[5])
72 | print('-----------')
73 | print(board[6],'I',board[7],'I',board[8])
74 | k=k+1
75 |
76 |
--------------------------------------------------------------------------------
/heap.py:
--------------------------------------------------------------------------------
1 | # importing "heapq" to implement heap queue
2 | import heapq
3 |
4 | # initializing list
5 | li = [5, 7, 9, 1, 3]
6 |
7 | # using heapify to convert list into heap
8 | heapq.heapify(li)
9 |
10 | # printing created heap
11 | print ("The created heap is : ",(list(li)))
12 |
--------------------------------------------------------------------------------
/img_compress.py:
--------------------------------------------------------------------------------
1 | from PIL import Image
2 | file_path = "python-learning-codes/uncompressed_img.jpg"
3 | img = Image.open(file_path)
4 | height, width = img.size
5 | compressed = img.resize((height, width), Image.ANTIALIAS)
6 | compressed.save("python-learning-codes/compressed_img.jpg", optimize=True,quality=9)
--------------------------------------------------------------------------------
/inorder_traversal.py:
--------------------------------------------------------------------------------
1 | class Node:
2 |
3 | def __init__(self, data):
4 |
5 | self.left = None
6 | self.right = None
7 | self.data = data
8 | # Insert Node
9 | def insert(self, data):
10 |
11 | if self.data:
12 | if data < self.data:
13 | if self.left is None:
14 | self.left = Node(data)
15 | else:
16 | self.left.insert(data)
17 | elif data > self.data:
18 | if self.right is None:
19 | self.right = Node(data)
20 | else:
21 | self.right.insert(data)
22 | else:
23 | self.data = data
24 |
25 | # Print the Tree
26 | def PrintTree(self):
27 | if self.left:
28 | self.left.PrintTree()
29 | print( self.data),
30 | if self.right:
31 | self.right.PrintTree()
32 |
33 | # Inorder traversal
34 | # Left -> Root -> Right
35 | def inorderTraversal(self, root):
36 | res = []
37 | if root:
38 | res = self.inorderTraversal(root.left)
39 | res.append(root.data)
40 | res = res + self.inorderTraversal(root.right)
41 | return res
42 |
43 | root = Node(27)
44 | root.insert(14)
45 | root.insert(35)
46 | root.insert(10)
47 | root.insert(19)
48 | root.insert(31)
49 | root.insert(42)
50 | print(root.inorderTraversal(root))
--------------------------------------------------------------------------------
/lallu.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | int main()
4 | {
5 | int a=0;
6 | int b=0;
7 | int c=a-b;
8 | cout<
2 | using namespace std;
3 | void linearsearch(int arr[], int n, int key)
4 | {
5 | for (int i = 0; i < n; i++)
6 | {
7 | if (arr[i] == key)
8 | {
9 | cout << "element found at " << i;
10 | }
11 | }
12 | }
13 |
14 | int main()
15 | {
16 | int n;
17 | cout << "enter no. of array you want";
18 | cin >> n;
19 | int arr[n];
20 | cout << "enter the array :- ";
21 | for (int i = 0; i < n; i++)
22 | {
23 |
24 | cin >> arr[i];
25 | }
26 |
27 | int key;
28 | cout << "enter the key :-";
29 | cin >> key;
30 | linearsearch(arr, n, key);
31 |
32 | return 0;
33 | }
--------------------------------------------------------------------------------
/linearsearch.py:
--------------------------------------------------------------------------------
1 | def search(arr, x):
2 |
3 | for i in range(len(arr)):
4 |
5 | if arr[i] == x:
6 | return i+1
7 |
8 | return -1
9 | print("Enter the list of numbers seprated by space")
10 | arr = [int(i) for i in input().split(" ")]
11 | print("Enter the key")
12 | x = int(input())
13 |
14 | print(search(arr, x))
15 |
--------------------------------------------------------------------------------
/linkedlistinsrt.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, dataval=None):
3 | self.dataval = dataval
4 | self.nextval = None
5 |
6 | class SLinkedList:
7 | def __init__(self):
8 | self.headval = None
9 | # Print the linked list
10 | def listprint(self):
11 | printval = self.headval
12 | while printval is not None:
13 | print (printval.dataval)
14 | printval = printval.nextval
15 | def AtBegining(self,newdata):
16 | NewNode = Node(newdata)
17 |
18 | # Update the new nodes next val to existing node
19 | NewNode.nextval = self.headval
20 | self.headval = NewNode
21 |
22 | list = SLinkedList()
23 | list.headval = Node("Mon")
24 | e2 = Node("Tue")
25 | e3 = Node("Wed")
26 |
27 | list.headval.nextval = e2
28 | e2.nextval = e3
29 |
30 | list.AtBegining("Sun")
31 | list.listprint()
32 |
--------------------------------------------------------------------------------
/loops.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | # While loop
4 | x = 0
5 | while(x<5):
6 | print(x)
7 | x = x + 1
8 |
9 | # Foo loop
10 | for i in range(5,10):
11 | print(i)
12 |
13 |
--------------------------------------------------------------------------------
/mergeSort.py:
--------------------------------------------------------------------------------
1 | # Python program for implementation of MergeSort
2 |
3 | # Merges two subarrays of arr[].
4 | # First subarray is arr[l..m]
5 | # Second subarray is arr[m+1..r]
6 |
7 |
8 | def merge(arr, l, m, r):
9 | n1 = m - l + 1
10 | n2 = r - m
11 |
12 | # create temp arrays
13 | L = [0] * (n1)
14 | R = [0] * (n2)
15 |
16 | # Copy data to temp arrays L[] and R[]
17 | for i in range(0, n1):
18 | L[i] = arr[l + i]
19 |
20 | for j in range(0, n2):
21 | R[j] = arr[m + 1 + j]
22 |
23 | # Merge the temp arrays back into arr[l..r]
24 | i = 0 # Initial index of first subarray
25 | j = 0 # Initial index of second subarray
26 | k = l # Initial index of merged subarray
27 |
28 | while i < n1 and j < n2:
29 | if L[i] <= R[j]:
30 | arr[k] = L[i]
31 | i += 1
32 | else:
33 | arr[k] = R[j]
34 | j += 1
35 | k += 1
36 |
37 | # Copy the remaining elements of L[], if there
38 | # are any
39 | while i < n1:
40 | arr[k] = L[i]
41 | i += 1
42 | k += 1
43 |
44 | # Copy the remaining elements of R[], if there
45 | # are any
46 | while j < n2:
47 | arr[k] = R[j]
48 | j += 1
49 | k += 1
50 |
51 | # l is for left index and r is right index of the
52 | # sub-array of arr to be sorted
53 |
54 |
55 | def mergeSort(arr, l, r):
56 | if l < r:
57 |
58 | # Same as (l+r)//2, but avoids overflow for
59 | # large l and h
60 | m = l+(r-l)//2
61 |
62 | # Sort first and second halves
63 | mergeSort(arr, l, m)
64 | mergeSort(arr, m+1, r)
65 | merge(arr, l, m, r)
66 |
67 |
68 | # Driver code to test above
69 | arr = [12, 11, 13, 5, 6, 7]
70 | n = len(arr)
71 | print("Given array is")
72 | for i in range(n):
73 | print("%d" % arr[i],end=" ")
74 |
75 | mergeSort(arr, 0, n-1)
76 | print("\n\nSorted array is")
77 | for i in range(n):
78 | print("%d" % arr[i],end=" ")
79 |
80 |
--------------------------------------------------------------------------------
/nparray.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | #1 D array
3 | a=np.array([1,2,3,4,5])
4 | print(a)
5 | #2 D array
6 | b=np.array([[1,2,3],[4,5,6]])
7 | print(b)
8 | #array of zeroes
9 | c=np.zeros((2,3))
10 | print(c)
11 | #array of ones
12 | d=np.ones((2,3))
13 | print(d)
14 | #array of any number
15 | e=np.full((2,3),5)
16 | print(e)
17 | #identity matrix
18 | f=np.eye(3)
19 | print(f)
20 | #random matrix
21 |
22 | g=np.random.random((2,3))
23 | print(g)
24 | #random arrays in fixed range
25 | h=np.random.randint(1,10,(2,3))
26 | print(h)
27 | #convert a list to numpy array
28 | list1=[1,2,3,4,5]
29 | np_array=np.asarray(list1)
30 | print(np_array)
31 | #transpose a matrix
32 | print(np.transpose(h))
33 |
--------------------------------------------------------------------------------
/npfunction.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | #arrange function
3 |
4 | print(np.arrange(2,10))
5 | print(np.arrange(2,10,2))
6 | print(np.arrange(1,2,0.1))
7 |
8 | #linspace function
9 | print(np.linspace(1,2,10))
10 |
11 | #reshape function
12 | a=np.array([1,2,3,4,5,6,7,8,9])
13 | print(a.reshape(3,3))
14 |
15 | #dot function
16 | a=np.array([1,2,3])
17 | b=np.array([4,5,6])
18 | print(np.dot(a,b))
19 | vec_a=2+3j
20 | vec_b=4+7j
21 | print(np.dot(vec_a,vec_b))
22 |
23 | #argmin function
24 | a=np.array([1,2,3,4,5,6,7,8,9])
25 | print(np.argmin(a))
26 | #argmax function
27 | print(np.argmax(a))
28 |
29 | #mean function
30 | print(np.mean(a))
31 | #median function
32 | print(np.median(a))
33 | #standard deviation function
34 | print(np.std(a))
35 | #variance function
36 | print(np.var(a))
37 |
38 | #concatenate function
39 | a=np.array([1,2,3])
40 | b=np.array([4,5,6])
41 | print(np.concatenate((a,b)))
42 | #stack function
43 | print(np.stack((a,b)))
44 | print(np.stack((a,b),axis=1))
45 |
46 | #split function
47 | a=np.array([1,2,3,4,5,6,7,8,9])
48 | print(np.split(a,3))
49 | print(np.split(a,[3,5]))
50 |
51 | #sort function
52 | a=np.array([1,2,3,4,5,6,7,8,9])
53 | print(np.sort(a))
54 | #reverse function
55 | print(np.sort(a)[::-1])
56 |
57 | #unique function
58 | a=np.array([1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9])
59 | print(np.unique(a))
60 |
61 |
62 |
--------------------------------------------------------------------------------
/oops.py:
--------------------------------------------------------------------------------
1 | class Person(object):
2 |
3 | # __init__ is known as the constructor
4 | def __init__(self, name, idnumber):
5 | self.name = name
6 | self.idnumber = idnumber
7 |
8 | def display(self):
9 | print(self.name)
10 | print(self.idnumber)
11 |
12 | def details(self):
13 | print("My name is {}".format(self.name))
14 | print("IdNumber: {}".format(self.idnumber))
15 |
16 | # child class
17 | class Employee(Person):
18 | def __init__(self, name, idnumber, salary, post):
19 | self.salary = salary
20 | self.post = post
21 |
22 | # invoking the __init__ of the parent class
23 | Person.__init__(self, name, idnumber)
24 |
25 | def details(self):
26 | print("My name is {}".format(self.name))
27 | print("IdNumber: {}".format(self.idnumber))
28 | print("Post: {}".format(self.post))
29 |
30 |
31 | # creation of an object variable or an instance
32 | a = Employee('Rahul', 886012, 200000, "Intern")
33 |
34 | # calling a function of the class Person using
35 | # its instance
36 | a.display()
37 | a.details()
38 |
--------------------------------------------------------------------------------
/pairwise000006.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 |
5 | void maxProduct(int arr[], int n)
6 | {
7 | if (n < 2)
8 | {
9 | cout << "No pairs exists\n";
10 | return;
11 | }
12 |
13 |
14 | int a = arr[0], b = arr[1];
15 |
16 |
17 |
18 | for (int i = 0; i < n; i++)
19 | for (int j = i + 1; j < n; j++)
20 | if (arr[i] * arr[j] > a * b)
21 | a = arr[i], b = arr[j];
22 |
23 | cout << "Max product pair is {" << a << ", "
24 | << b << "}";
25 | }
26 |
27 | int main()
28 | {
29 | int arr[] = {1, 4, 3, 6, 7, 0};
30 | int n = sizeof(arr) / sizeof(arr[0]);
31 | maxProduct(arr, n);
32 | return 0;
33 | }
34 |
--------------------------------------------------------------------------------
/pancakeSort.py:
--------------------------------------------------------------------------------
1 | # Python3 program to
2 | # sort array using
3 | # pancake sort
4 |
5 | # Reverses arr[0..i] */
6 | def flip(arr, i):
7 | start = 0
8 | while start < i:
9 | temp = arr[start]
10 | arr[start] = arr[i]
11 | arr[i] = temp
12 | start += 1
13 | i -= 1
14 |
15 | # Returns index of the maximum
16 | # element in arr[0..n-1] */
17 | def findMax(arr, n):
18 | mi = 0
19 | for i in range(0,n):
20 | if arr[i] > arr[mi]:
21 | mi = i
22 | return mi
23 |
24 | # The main function that
25 | # sorts given array
26 | # using flip operations
27 | def pancakeSort(arr, n):
28 |
29 | # Start from the complete
30 | # array and one by one
31 | # reduce current size
32 | # by one
33 | curr_size = n
34 | while curr_size > 1:
35 | # Find index of the maximum
36 | # element in
37 | # arr[0..curr_size-1]
38 | mi = findMax(arr, curr_size)
39 |
40 | # Move the maximum element
41 | # to end of current array
42 | # if it's not already at
43 | # the end
44 | if mi != curr_size-1:
45 | # To move at the end,
46 | # first move maximum
47 | # number to beginning
48 | flip(arr, mi)
49 |
50 | # Now move the maximum
51 | # number to end by
52 | # reversing current array
53 | flip(arr, curr_size-1)
54 | curr_size -= 1
55 |
56 | # A utility function to
57 | # print an array of size n
58 | def printArray(arr, n):
59 | for i in range(0,n):
60 | print ("%d"%( arr[i]),end=" ")
61 |
62 | # Driver program
63 | arr = [23, 10, 20, 11, 12, 6, 7]
64 | n = len(arr)
65 | pancakeSort(arr, n);
66 | print ("Sorted Array ")
67 | printArray(arr,n)
68 |
69 |
--------------------------------------------------------------------------------
/pattern.py:
--------------------------------------------------------------------------------
1 | # Function to demonstrate printing pattern of alphabets
2 |
3 |
4 | def contalpha(n):
5 |
6 | # initializing value corresponding to 'A'
7 | # ASCII value
8 | num = 65
9 |
10 |
11 | # outer loop to handle number of rows
12 | - for i in range(0, n):
13 |
14 | # inner loop to handle number of columns
15 | # values changing acc. to outer loop
16 | for j in range(0, i+1):
17 |
18 | # explicitly converting to char
19 | ch = chr(num)
20 |
21 | # printing char value
22 | print(ch, end=" ")
23 |
24 | # incrementing at each column
25 | num = num + 1
26 |
27 | # ending line after each row
28 | print("\r")
29 |
30 | # Driver code
31 | n = 5
32 | contalpha(n)
33 |
--------------------------------------------------------------------------------
/peigonSort.py:
--------------------------------------------------------------------------------
1 | # Python program to implement Pigeonhole Sort */
2 | def pigeonhole_sort(a):
3 | # size of range of values in the list
4 | # (ie, number of pigeonholes we need)
5 | my_min = min(a)
6 | my_max = max(a)
7 | size = my_max - my_min + 1
8 |
9 | # our list of pigeonholes
10 | holes = [0] * size
11 |
12 | # Populate the pigeonholes.
13 | for x in a:
14 | assert type(x) is int, "integers only please"
15 | holes[x - my_min] += 1
16 |
17 | # Put the elements back into the array in order.
18 | i = 0
19 | for count in range(size):
20 | while holes[count] > 0:
21 | holes[count] -= 1
22 | a[i] = count + my_min
23 | i += 1
24 |
25 |
26 | a = [8, 3, 2, 7, 4, 6, 8]
27 | print("Sorted order is : ", end = ' ')
28 |
29 | pigeonhole_sort(a)
30 |
31 | for i in range(0, len(a)):
32 | print(a[i], end = ' ')
33 |
34 |
--------------------------------------------------------------------------------
/perfect.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 | int main()
4 | {
5 | int i,n;
6 | cin>>n;
7 | int sum=0;
8 | for(i=1;i<=n;i++)
9 | {
10 | if(n%i==0)
11 | {
12 | sum+=i;
13 | }
14 | }
15 | if(sum==2*n)
16 |
17 | cout<<"perfect number";
18 |
19 | else
20 | cout<<"not perfect";
21 | return 0;
22 | }
--------------------------------------------------------------------------------
/pointer_VEDANT.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | void update(int *a,int *b)
5 | {
6 | // Complete this function
7 | int x, y;
8 | // Complete this function
9 | x = *a + *b ;
10 | y = *a - *b ;
11 | *a = x;
12 | *b = abs(y);
13 |
14 | }
15 |
16 | int main()
17 | {
18 | int a, b;
19 | int *pa = &a, *pb = &b;
20 |
21 | scanf("%d %d", &a, &b);
22 | update(pa, pb);
23 | printf("%d\n%d", a, b);
24 |
25 | return 0;
26 | }
--------------------------------------------------------------------------------
/postorder_traversal.py:
--------------------------------------------------------------------------------
1 | class Node:
2 |
3 | def __init__(self, data):
4 |
5 | self.left = None
6 | self.right = None
7 | self.data = data
8 | # Insert Node
9 | def insert(self, data):
10 |
11 | if self.data:
12 | if data < self.data:
13 | if self.left is None:
14 | self.left = Node(data)
15 | else:
16 | self.left.insert(data)
17 | elif data > self.data:
18 | if self.right is None:
19 | self.right = Node(data)
20 | else:
21 | self.right.insert(data)
22 | else:
23 | self.data = data
24 |
25 | # Print the Tree
26 | def PrintTree(self):
27 | if self.left:
28 | self.left.PrintTree()
29 | print( self.data),
30 | if self.right:
31 | self.right.PrintTree()
32 |
33 | # Postorder traversal
34 | # Left ->Right -> Root
35 | def PostorderTraversal(self, root):
36 | res = []
37 | if root:
38 | res = self.PostorderTraversal(root.left)
39 | res = res + self.PostorderTraversal(root.right)
40 | res.append(root.data)
41 | return res
42 |
43 | root = Node(27)
44 | root.insert(14)
45 | root.insert(35)
46 | root.insert(10)
47 | root.insert(19)
48 | root.insert(31)
49 | root.insert(42)
50 | print(root.PostorderTraversal(root))
--------------------------------------------------------------------------------
/preorder_traversal.py:
--------------------------------------------------------------------------------
1 | class Node:
2 |
3 | def __init__(self, data):
4 |
5 | self.left = None
6 | self.right = None
7 | self.data = data
8 | # Insert Node
9 | def insert(self, data):
10 |
11 | if self.data:
12 | if data < self.data:
13 | if self.left is None:
14 | self.left = Node(data)
15 | else:
16 | self.left.insert(data)
17 | elif data > self.data:
18 | if self.right is None:
19 | self.right = Node(data)
20 | else:
21 | self.right.insert(data)
22 | else:
23 | self.data = data
24 |
25 | # Print the Tree
26 | def PrintTree(self):
27 | if self.left:
28 | self.left.PrintTree()
29 | print( self.data),
30 | if self.right:
31 | self.right.PrintTree()
32 |
33 | # Preorder traversal
34 | # Root -> Left ->Right
35 | def PreorderTraversal(self, root):
36 | res = []
37 | if root:
38 | res.append(root.data)
39 | res = res + self.PreorderTraversal(root.left)
40 | res = res + self.PreorderTraversal(root.right)
41 | return res
42 |
43 | root = Node(27)
44 | root.insert(14)
45 | root.insert(35)
46 | root.insert(10)
47 | root.insert(19)
48 | root.insert(31)
49 | root.insert(42)
50 | print(root.PreorderTraversal(root))
--------------------------------------------------------------------------------
/priorityqueue.py:
--------------------------------------------------------------------------------
1 | # A simple implementation of Priority Queue
2 | class PriorityQueue(object):
3 | def __init__(self):
4 | self.queue = []
5 |
6 | def __str__(self):
7 | return ' '.join([str(i) for i in self.queue])
8 |
9 | # for checking if the queue is empty
10 | def isEmpty(self):
11 | return len(self.queue) == 0
12 |
13 | # for inserting an element in the queue
14 | def insert(self, data):
15 | self.queue.append(data)
16 |
17 | # for popping an element based on Priority
18 | def delete(self):
19 | try:
20 | max_val = 0
21 | for i in range(len(self.queue)):
22 | if self.queue[i] > self.queue[max_val]:
23 | max_val = i
24 | item = self.queue[max_val]
25 | del self.queue[max_val]
26 | return item
27 | except IndexError:
28 | print()
29 | exit()
30 |
31 | if __name__ == '__main__':
32 | myQueue = PriorityQueue()
33 | myQueue.insert(12)
34 | myQueue.insert(1)
35 | myQueue.insert(14)
36 | myQueue.insert(7)
37 | print(myQueue)
38 | while not myQueue.isEmpty():
39 | print(myQueue.delete())
40 |
41 |
--------------------------------------------------------------------------------
/python matrix:
--------------------------------------------------------------------------------
1 | X = [[12,7],
2 | [4 ,5],
3 | [3 ,8]]
4 |
5 | result = [[0,0,0],
6 | [0,0,0]]
7 |
8 | # iterate through rows
9 | for i in range(len(X)):
10 | # iterate through columns
11 | for j in range(len(X[0])):
12 | result[j][i] = X[i][j]
13 |
14 | for r in result:
15 | print(r)
16 |
--------------------------------------------------------------------------------
/pythonDictionaries.py:
--------------------------------------------------------------------------------
1 | dict_demo ={'first':1,'second':2,'third':3}
2 | print("dictionary :",dict_demo)
3 | keylist = list(dict_demo.keys())
4 | print('keys : ',keylist)
5 | valuelist = list (dict_demo.values())
6 | print ('values : ', valuelist)
7 |
8 | # .keys() function is used to print keys of dictionary
9 | for k in dict_demo.keys():
10 | print(k)
11 |
12 | #.values() function is used to print value of dictionary
13 | for v in dict_demo.values():
14 | print(v)
15 |
16 |
17 | #print the dictionary item
18 | print('value at key[]-first ',dict_demo['first'])
19 |
20 | #update key value which is present in the dictionary
21 | print()
22 | dict = {0 : 'sunday', 1 : 'monday', 2 : 'tuesday'}
23 | # print (dict['first'].items())
24 | for item in dict.items():
25 | print(item)
26 | print()
27 | dict[2] = 'wednesday'
28 | for item in dict.items():
29 | print(item)
30 |
31 | # we can merge two dictionary into 1 dictionary using update() method
32 |
33 | dict.update(dict_demo)
34 | print(dict)
35 |
--------------------------------------------------------------------------------
/pythonprogram.py:
--------------------------------------------------------------------------------
1 | # Write a Python program to insert items into a list in sorted order.
2 | import bisect
3 | # Sample list
4 | my_list = [25, 45, 36, 47, 69, 48, 68, 78, 14, 36]
5 |
6 | print("Original List:")
7 | print(my_list)
8 | sorted_list = []
9 | for i in my_list:
10 | position = bisect.bisect(sorted_list, i)
11 | bisect.insort(sorted_list, i)
12 | print("Sorted List:")
13 | print(sorted_list)
14 |
--------------------------------------------------------------------------------
/queue.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | using namespace std;
4 |
5 | void print(queueque)
6 | {
7 | queuec=que;
8 | while(!c.empty())
9 | {
10 | cout<q;
17 | q.push('a');
18 | q.push('b');
19 | q.push('c');
20 | print(q);
21 |
22 | cout<= 0:
28 | index = arr[i] // exp1
29 | output[count[index % 10] - 1] = arr[i]
30 | count[index % 10] -= 1
31 | i -= 1
32 |
33 | # Copying the output array to arr[],
34 | # so that arr now contains sorted numbers
35 | i = 0
36 | for i in range(0, len(arr)):
37 | arr[i] = output[i]
38 |
39 | # Method to do Radix Sort
40 | def radixSort(arr):
41 |
42 | # Find the maximum number to know number of digits
43 | max1 = max(arr)
44 |
45 | # Do counting sort for every digit. Note that instead
46 | # of passing digit number, exp is passed. exp is 10^i
47 | # where i is current digit number
48 | exp = 1
49 | while max1 / exp >= 1:
50 | countingSort(arr, exp)
51 | exp *= 10
52 |
53 |
54 | # Driver code
55 | arr = [170, 45, 75, 90, 802, 24, 2, 66]
56 |
57 | # Function Call
58 | radixSort(arr)
59 |
60 | for i in range(len(arr)):
61 | print(arr[i],end=" ")
62 |
63 |
--------------------------------------------------------------------------------
/reverse_ll.py:
--------------------------------------------------------------------------------
1 | # A single node of a singly Linked List
2 | class Node:
3 | # constructor
4 | def __init__(self, data = None, next=None):
5 | self.data = data
6 | self.next = next
7 |
8 | # A Linked List class with a single head node
9 | class LinkedList:
10 | def __init__(self):
11 | self.head = None
12 |
13 | # insertion method for the linked list
14 | def insert(self, data):
15 | newNode = Node(data)
16 | if(self.head):
17 | current = self.head
18 | while(current.next):
19 | current = current.next
20 | current.next = newNode
21 | else:
22 | self.head = newNode
23 |
24 | # print method for the linked list
25 | def printLL(self):
26 | current = self.head
27 | while(current):
28 | print(current.data)
29 | current = current.next
30 |
31 | # Singly Linked List with insertion and print methods
32 | LL = LinkedList()
33 | LL.insert(3)
34 | LL.insert(4)
35 | LL.insert(5)
36 | LL.printLL()
37 |
--------------------------------------------------------------------------------
/runner_score.py:
--------------------------------------------------------------------------------
1 | score = int(input())
2 | arr= list(map(int,inpt(.split()))
3 | z=max(arr)
4 | m=-101
5 | for i in arr :
6 | if i==z :
7 | continue
8 | else :
9 | if i>m :
10 | m=i
11 | print(m)
12 |
--------------------------------------------------------------------------------
/selectionsort.py:
--------------------------------------------------------------------------------
1 | def selection_sort(input_list):
2 | for idx in range(len(input_list)):
3 | min_idx = idx
4 | for j in range( idx +1, len(input_list)):
5 | if input_list[min_idx] > input_list[j]:
6 | min_idx = j
7 | # Swap the minimum value with the compared value
8 | input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]
9 | l = [19,2,31,45,30,11,121,27]
10 | selection_sort(l)
11 | print(l)
--------------------------------------------------------------------------------
/sndkfne.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int main() {
4 |
5 | printf("Hello World");
6 |
7 | return 0 ;
8 | }
--------------------------------------------------------------------------------
/stack.py:
--------------------------------------------------------------------------------
1 | # Python program to
2 | # demonstrate stack implementation
3 | # using list
4 |
5 | stack = []
6 |
7 | # append() function to push
8 | # element in the stack
9 | stack.append('a')
10 | stack.append('b')
11 | stack.append('c')
12 |
13 | print('Initial stack')
14 | print(stack)
15 |
16 | # pop() function to pop
17 | # element from stack in
18 | # LIFO order
19 | print('\nElements popped from stack:')
20 | print(stack.pop())
21 | print(stack.pop())
22 | print(stack.pop())
23 |
24 | print('\nStack after elements are popped:')
25 | print(stack)
26 |
27 | # uncommenting print(stack.pop())
28 | # will cause an IndexError
29 | # as the stack is now empty
30 |
--------------------------------------------------------------------------------
/stack_usingLinkedlist.py:
--------------------------------------------------------------------------------
1 | # python3 program to Implement a stack
2 | # using singly linked list
3 |
4 | class Node:
5 |
6 | # Class to create nodes of linked list
7 | # constructor initializes node automatically
8 | def __init__(self, data):
9 | self.data = data
10 | self.next = None
11 |
12 |
13 | class Stack:
14 |
15 | # head is default NULL
16 | def __init__(self):
17 | self.head = None
18 |
19 | # Checks if stack is empty
20 | def isempty(self):
21 | if self.head == None:
22 | return True
23 | else:
24 | return False
25 |
26 | # Method to add data to the stack
27 | # adds to the start of the stack
28 | def push(self, data):
29 |
30 | if self.head == None:
31 | self.head = Node(data)
32 |
33 | else:
34 | newnode = Node(data)
35 | newnode.next = self.head
36 | self.head = newnode
37 |
38 | # Remove element that is the current head (start of the stack)
39 | def pop(self):
40 |
41 | if self.isempty():
42 | return None
43 |
44 | else:
45 | # Removes the head node and makes
46 | # the preceding one the new head
47 | poppednode = self.head
48 | self.head = self.head.next
49 | poppednode.next = None
50 | return poppednode.data
51 |
52 | # Returns the head node data
53 | def peek(self):
54 |
55 | if self.isempty():
56 | return None
57 |
58 | else:
59 | return self.head.data
60 |
61 | # Prints out the stack
62 | def display(self):
63 |
64 | iternode = self.head
65 | if self.isempty():
66 | print("Stack Underflow")
67 |
68 | else:
69 |
70 | while(iternode != None):
71 |
72 | print(iternode.data, end = "")
73 | iternode = iternode.next
74 | if(iternode != None):
75 | print(" -> ", end = "")
76 | return
77 |
78 |
79 | # Driver code
80 | if __name__ == "__main__":
81 | MyStack = Stack()
82 |
83 | MyStack.push(11)
84 | MyStack.push(22)
85 | MyStack.push(33)
86 | MyStack.push(44)
87 |
88 | # Display stack elements
89 | MyStack.display()
90 |
91 | # Print top element of stack
92 | print("\nTop element is ", MyStack.peek())
93 |
94 | # Delete top elements of stack
95 | MyStack.pop()
96 | MyStack.pop()
97 |
98 | # Display stack elements
99 | MyStack.display()
100 |
101 | # Print top element of stack
102 | print("\nTop element is ", MyStack.peek())
103 |
104 | # This code is contributed by Mathew George
105 |
--------------------------------------------------------------------------------
/stoogeSort.py:
--------------------------------------------------------------------------------
1 | # Python program to implement stooge sort
2 |
3 | def stoogesort(arr, l, h):
4 | if l >= h:
5 | return
6 |
7 | # If first element is smaller
8 | # than last, swap them
9 | if arr[l]>arr[h]:
10 | t = arr[l]
11 | arr[l] = arr[h]
12 | arr[h] = t
13 |
14 | # If there are more than 2 elements in
15 | # the array
16 | if h-l + 1 > 2:
17 | t = (int)((h-l + 1)/3)
18 |
19 | # Recursively sort first 2 / 3 elements
20 | stoogesort(arr, l, (h-t))
21 |
22 | # Recursively sort last 2 / 3 elements
23 | stoogesort(arr, l + t, (h))
24 |
25 | # Recursively sort first 2 / 3 elements
26 | # again to confirm
27 | stoogesort(arr, l, (h-t))
28 |
29 |
30 | # deriver
31 | arr = [2, 4, 5, 3, 1]
32 | n = len(arr)
33 |
34 | stoogesort(arr, 0, n-1)
35 |
36 | for i in range(0, n):
37 | print(arr[i], end = ' ')
38 |
--------------------------------------------------------------------------------
/timSort.py:
--------------------------------------------------------------------------------
1 | # Python3 program to perform basic timSort
2 | MIN_MERGE = 32
3 |
4 |
5 | def calcMinRun(n):
6 | """Returns the minimum length of a
7 | run from 23 - 64 so that
8 | the len(array)/minrun is less than or
9 | equal to a power of 2.
10 |
11 | e.g. 1=>1, ..., 63=>63, 64=>32, 65=>33,
12 | ..., 127=>64, 128=>32, ...
13 | """
14 | r = 0
15 | while n >= MIN_MERGE:
16 | r |= n & 1
17 | n >>= 1
18 | return n + r
19 |
20 |
21 | # This function sorts array from left index to
22 | # to right index which is of size atmost RUN
23 | def insertionSort(arr, left, right):
24 | for i in range(left + 1, right + 1):
25 | j = i
26 | while j > left and arr[j] < arr[j - 1]:
27 | arr[j], arr[j - 1] = arr[j - 1], arr[j]
28 | j -= 1
29 |
30 |
31 | # Merge function merges the sorted runs
32 | def merge(arr, l, m, r):
33 |
34 | # original array is broken in two parts
35 | # left and right array
36 | len1, len2 = m - l + 1, r - m
37 | left, right = [], []
38 | for i in range(0, len1):
39 | left.append(arr[l + i])
40 | for i in range(0, len2):
41 | right.append(arr[m + 1 + i])
42 |
43 | i, j, k = 0, 0, l
44 |
45 | # after comparing, we merge those two array
46 | # in larger sub array
47 | while i < len1 and j < len2:
48 | if left[i] <= right[j]:
49 | arr[k] = left[i]
50 | i += 1
51 |
52 | else:
53 | arr[k] = right[j]
54 | j += 1
55 |
56 | k += 1
57 |
58 | # Copy remaining elements of left, if any
59 | while i < len1:
60 | arr[k] = left[i]
61 | k += 1
62 | i += 1
63 |
64 | # Copy remaining element of right, if any
65 | while j < len2:
66 | arr[k] = right[j]
67 | k += 1
68 | j += 1
69 |
70 |
71 | # Iterative Timsort function to sort the
72 | # array[0...n-1] (similar to merge sort)
73 | def timSort(arr):
74 | n = len(arr)
75 | minRun = calcMinRun(n)
76 |
77 | # Sort individual subarrays of size RUN
78 | for start in range(0, n, minRun):
79 | end = min(start + minRun - 1, n - 1)
80 | insertionSort(arr, start, end)
81 |
82 | # Start merging from size RUN (or 32). It will merge
83 | # to form size 64, then 128, 256 and so on ....
84 | size = minRun
85 | while size < n:
86 |
87 | # Pick starting point of left sub array. We
88 | # are going to merge arr[left..left+size-1]
89 | # and arr[left+size, left+2*size-1]
90 | # After every merge, we increase left by 2*size
91 | for left in range(0, n, 2 * size):
92 |
93 | # Find ending point of left sub array
94 | # mid+1 is starting point of right sub array
95 | mid = min(n - 1, left + size - 1)
96 | right = min((left + 2 * size - 1), (n - 1))
97 |
98 | # Merge sub array arr[left.....mid] &
99 | # arr[mid+1....right]
100 | if mid < right:
101 | merge(arr, left, mid, right)
102 |
103 | size = 2 * size
104 |
105 |
106 | # Driver program to test above function
107 | if __name__ == "__main__":
108 |
109 | arr = [-2, 7, 15, -14, 0, 15, 0,
110 | 7, -7, -4, -13, 5, 8, -14, 12]
111 |
112 | print("Given Array is")
113 | print(arr)
114 |
115 | # Function Call
116 | timSort(arr)
117 |
118 | print("After Sorting Array is")
119 | print(arr)
120 |
121 |
--------------------------------------------------------------------------------
/treeSort.py:
--------------------------------------------------------------------------------
1 | # Python3 program to
2 | # implement Tree Sort
3 |
4 | # Class containing left and
5 | # right child of current
6 | # node and key value
7 | class Node:
8 |
9 | def __init__(self,item = 0):
10 | self.key = item
11 | self.left,self.right = None,None
12 |
13 |
14 | # Root of BST
15 | root = Node()
16 |
17 | root = None
18 |
19 | # This method mainly
20 | # calls insertRec()
21 | def insert(key):
22 | global root
23 | root = insertRec(root, key)
24 |
25 | # A recursive function to
26 | # insert a new key in BST
27 | def insertRec(root, key):
28 |
29 | # If the tree is empty,
30 | # return a new node
31 |
32 | if (root == None):
33 | root = Node(key)
34 | return root
35 |
36 | # Otherwise, recur
37 | # down the tree
38 | if (key < root.key):
39 | root.left = insertRec(root.left, key)
40 | elif (key > root.key):
41 | root.right = insertRec(root.right, key)
42 |
43 | # return the root
44 | return root
45 |
46 | # A function to do
47 | # inorder traversal of BST
48 | def inorderRec(root):
49 | if (root != None):
50 | inorderRec(root.left)
51 | print(root.key ,end = " ")
52 | inorderRec(root.right)
53 |
54 | def treeins(arr):
55 | for i in range(len(arr)):
56 | insert(arr[i])
57 |
58 | # Driver Code
59 | arr = [5, 4, 7, 2, 11]
60 | treeins(arr)
61 | inorderRec(root)
62 |
63 |
--------------------------------------------------------------------------------
/uncompressed_img.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hariom20singh/python-learning-codes/820f8e22c4c66183ab4aca54cfcafe1a0792e057/uncompressed_img.jpg
--------------------------------------------------------------------------------
/weather_notifications_desktop.py:
--------------------------------------------------------------------------------
1 | import os,requests
2 | from win10toast import ToastNotifier
3 | from dotenv import load_dotenv
4 | load_dotenv()
5 |
6 | n = ToastNotifier()
7 | city = input("Enter city name: ")
8 |
9 | url = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid="+os.getenv("API_key")+"&units=metric"
10 |
11 | r = requests.get(url,auth= (os.getenv("user"),os.getenv("password")))
12 | r_dict = r.json()
13 |
14 |
15 | current_temp = r_dict['main']['temp']
16 |
17 | weather_desc = r_dict['weather'][0]['description']
18 |
19 | temp = (str(current_temp))
20 |
21 | desc = str(weather_desc)
22 |
23 | result = "Current temperature is: " + temp + " Celsius in " + city+ ".\nCurrent weather condition is: " + desc
24 | n.show_toast("Live Weather update: ",
25 | result, duration = 10)
26 |
--------------------------------------------------------------------------------
/zeroSum.py:
--------------------------------------------------------------------------------
1 | n=int(input('Enter number of inputs:\n'))
2 | arr=[int(input("Enter single number and press enter: ")) for _ in range(n)]
3 |
4 | zero_sum_count=0
5 | for i in range(len(arr)):
6 | tmp=[]
7 | for j in range(i,len(arr)):
8 | tmp.append(arr[j])
9 | if sum(tmp)==0:
10 | zero_sum_count+=1
11 | print('Number of Subarrays with zero sum = ',zero_sum_count)
--------------------------------------------------------------------------------