├── firstProgram.py
├── for_loop.py
├── intro.txt
├── range.py
├── set.py
├── loop.py
├── pattern_priting_2.py
├── pattern_printing_1.py
├── __pycache__
└── string.cpython-311.pyc
├── substrings.py
├── Type_Conversion.py
├── tuple.py
├── two_number_sum.py
├── break_continue.py
├── funstions.py
├── function_2.py
├── .idea
├── vcs.xml
├── .gitignore
├── misc.xml
├── inspectionProfiles
│ └── profiles_settings.xml
├── modules.xml
└── Learning_Python.iml
├── input_taking.py
├── conditional_statement.py
├── match_case.py
├── try_except.py
├── fileIo.py
├── disctionary.py
├── listandMethods.py
├── arthematic_operators.py
├── while_loop.py
├── main.py
├── dattype.py
├── string.py
├── ifelse_ladder.py
├── functions.py
├── comparison_operators.py
├── comments_in_python.py
├── opps.py
├── list.py
├── mini_calculator.py
├── for_loop_2.py
├── rockPaperScissors.py
├── README.md
├── setOne.py
├── setThree.py
├── setTwo.py
└── setFour.py
/firstProgram.py:
--------------------------------------------------------------------------------
1 | print("Hello World")
2 |
--------------------------------------------------------------------------------
/for_loop.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | for i in range(10):
4 | print(i);
--------------------------------------------------------------------------------
/intro.txt:
--------------------------------------------------------------------------------
1 | My name is Shubham Bhati. I am from Ujjain(M.P)
--------------------------------------------------------------------------------
/range.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | numbners = range(5);
4 |
5 | print(numbners);
--------------------------------------------------------------------------------
/set.py:
--------------------------------------------------------------------------------
1 | set = {1,56,2,3,60,23,34};
2 |
3 | for el in set:
4 | print(el);
--------------------------------------------------------------------------------
/loop.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | i = 1;
4 |
5 | while i <= 10:
6 | print(i);
7 | i+=1;
--------------------------------------------------------------------------------
/pattern_priting_2.py:
--------------------------------------------------------------------------------
1 |
2 | i = 10;
3 |
4 | while i >= 0:
5 | print(i * "* ");
6 | i -= 1;
--------------------------------------------------------------------------------
/pattern_printing_1.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | i = 1;
4 |
5 | while i <= 10:
6 | print(i * "* ");
7 | i += 1;
--------------------------------------------------------------------------------
/__pycache__/string.cpython-311.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Learning_Python/HEAD/__pycache__/string.cpython-311.pyc
--------------------------------------------------------------------------------
/substrings.py:
--------------------------------------------------------------------------------
1 | name = 'Shubham'
2 |
3 | print(name)
4 |
5 | print(name[0:2])
6 |
7 | for i in range(len(name)):
8 | print(name[0:i])
9 |
--------------------------------------------------------------------------------
/Type_Conversion.py:
--------------------------------------------------------------------------------
1 | age = input("what is your age ? ");
2 |
3 | new_age = int(age) + 2;
4 |
5 |
6 | print("your age after two year is " + str(new_age));
--------------------------------------------------------------------------------
/tuple.py:
--------------------------------------------------------------------------------
1 | tple = (1,3,5,2,10);
2 |
3 | print(tple.index(5));
4 |
5 | print(tple.count(10))
6 |
7 | tple2 = "a","i","e","o","u";
8 |
9 | print(tple2);
--------------------------------------------------------------------------------
/two_number_sum.py:
--------------------------------------------------------------------------------
1 | first = input("enter first number : ");
2 | second = input("enter second number : ");
3 |
4 | sum = int(first) + int(second);
5 |
6 | print(sum);
--------------------------------------------------------------------------------
/break_continue.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | list = [1,4,5,7,82,10];
4 |
5 | for el in list:
6 | if el >= 30:
7 | break;
8 | print(el);
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/funstions.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 |
4 | print(dir(math))
5 |
6 |
7 |
8 | def greeting(name):
9 | print("hello "+name);
10 |
11 |
12 |
13 | greeting("shubham");
--------------------------------------------------------------------------------
/function_2.py:
--------------------------------------------------------------------------------
1 | def print_sum(f,s):
2 | print(f+s);
3 |
4 |
5 |
6 | print_sum(2,5);
7 |
8 |
9 | def print_sum_2(f,s=4):
10 | print(f+s);
11 |
12 | print_sum_2(6);
13 |
14 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/input_taking.py:
--------------------------------------------------------------------------------
1 | name = input("What is your name ? ")
2 | age = input("Your age ? ")
3 | city = input("City ? ")
4 |
5 | print("Name is "+name);
6 | print("Age is "+age);
7 | print("City is "+city);
8 |
--------------------------------------------------------------------------------
/conditional_statement.py:
--------------------------------------------------------------------------------
1 | age = 18;
2 |
3 | if age > 18:
4 | print("Eligible for vote");
5 | elif age == 18:
6 | print("welcome eligible for vote");
7 | else :
8 | print("Not eligible for vote");
--------------------------------------------------------------------------------
/match_case.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | a = 3
4 |
5 | match a:
6 | case 3:
7 | print("a is 3")
8 | case 2:
9 | print("a is 2")
10 | case _:
11 | print("anything")
12 |
13 |
14 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/try_except.py:
--------------------------------------------------------------------------------
1 | try:
2 | f = int(input("Enter your age : "))
3 | if(f<=0):
4 | print("Age is lees than 1")
5 | else:
6 | print("Hello your age is :"+str(f))
7 | except:
8 | print("Invalid age")
9 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/fileIo.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | intro = "My name is Shubham Bhati. I am from Ujjain(M.P)"
4 |
5 | with open("intro.txt","w") as h:
6 | h.write(intro)
7 |
8 |
9 | with open("intro.txt","r") as j:
10 | g = j.read()
11 | print(g)
--------------------------------------------------------------------------------
/disctionary.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | student = {
4 | "marks" : 70,
5 | "city" : "Ujjain",
6 | "Course" : "Java Backend Development"
7 |
8 | }
9 | student["state"] = "Madhya Pradesh"
10 |
11 |
12 | print(student["marks"])
13 | print(student)
--------------------------------------------------------------------------------
/listandMethods.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | l1 = [1,5,7,1,8,20,"Shubham",4,5,7,5]
4 |
5 | print(l1)
6 | l1.remove('Shubham')
7 |
8 | print(l1)
9 |
10 | print(l1.count(5))
11 |
12 |
13 | print(l1.sort())
14 | l1.append("last")
15 |
16 |
17 | print(l1)
--------------------------------------------------------------------------------
/arthematic_operators.py:
--------------------------------------------------------------------------------
1 | print(5+10);
2 |
3 | print(10-5);
4 |
5 | print(3*3);
6 |
7 | print(2/5);
8 |
9 | print(2 // 5);
10 |
11 | print(4%3);
12 |
13 | print(5 ** 2);
14 |
15 | i = 5;
16 |
17 | i += 2;
18 |
19 | print(i);
20 |
21 |
22 |
--------------------------------------------------------------------------------
/while_loop.py:
--------------------------------------------------------------------------------
1 | i = 10
2 |
3 | while(i>=0):
4 | print(i)
5 | i-=1
6 |
7 | print("000000000000000000000000")
8 |
9 | j = 9
10 |
11 | while(j<=20):
12 | print(j)
13 | if(j%2==0):
14 | break
15 | j+=1
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | print("Hello World");
2 |
3 | ''''
4 | print("Hello World");
5 | print("Hello World");
6 | print("Hello World");
7 | print("Hello World");
8 | print("Hello World");
9 | print("Hello World");
10 | print("Hello World");
11 | print("Hello World");
12 | print("Hello World");
13 | ''''
--------------------------------------------------------------------------------
/dattype.py:
--------------------------------------------------------------------------------
1 | name = "Shubham"
2 | age = 23
3 | hieght = 224.0
4 | Indian = True
5 |
6 | name = "Bhati"
7 | age = 21
8 |
9 |
10 | print(name)
11 | print(hieght)
12 | print(Indian)
13 | print(age)
14 |
15 | person = "Tony Stark"
16 | age = 51
17 | is_genius = True
18 |
19 | name = input("Name")
--------------------------------------------------------------------------------
/string.py:
--------------------------------------------------------------------------------
1 | name = "Shubham Bhati";
2 | name = name.upper();
3 | print(name);
4 | name = name.lower();
5 | print(name.lower());
6 |
7 | present = name.find('u');
8 | print(present);
9 |
10 | print(name.replace("bhati","bhatiya"));
11 |
12 | print(name);
13 |
14 | print('b' in name);
15 | print('z' in name);
--------------------------------------------------------------------------------
/ifelse_ladder.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | age = int(input("Enter your age : "))
4 |
5 |
6 | if(age <= 0):
7 | print("Invalid age")
8 | elif(age <= 10):
9 | print("kid")
10 | elif(age <= 16):
11 | print("teen")
12 | elif(age <= 18):
13 | print("boy")
14 | else:
15 | print("Matured")
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/functions.py:
--------------------------------------------------------------------------------
1 |
2 | def sayHello(name):
3 | print("Hello "+name)
4 |
5 |
6 |
7 | sayHello("Shubham")
8 |
9 |
10 | def table(num):
11 | for i in range(11):
12 | print(str(num) + " * " + str(i+1) + " = " + str((i+1) * num))
13 |
14 | print("------------")
15 |
16 | table(6)
17 |
18 | table(4)
--------------------------------------------------------------------------------
/comparison_operators.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | print(3 > 2);
4 |
5 | print(3 < 2);
6 |
7 | print(3 <= 2);
8 |
9 | print(3 >= 2);
10 |
11 | print(3 == 2);
12 |
13 | print(3 == 3);
14 |
15 | print(3 != 2);
16 |
17 | print(3 > 2 or 3 < 2);
18 |
19 | print(3 > 2 and 3 < 2);
20 |
21 | print(not 2 > 3);
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/.idea/Learning_Python.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/comments_in_python.py:
--------------------------------------------------------------------------------
1 | # her is the first comment
2 |
3 |
4 | # taking input input
5 | f = input("first number ");
6 | s = input("second number ");
7 |
8 | # calculating the sum
9 | # we have to do type conversion becuase
10 | # by defualt in python it take all things in string format
11 | sum = int(f)+int(s);
12 |
13 | # printing the sum
14 | print(sum);
15 |
16 |
--------------------------------------------------------------------------------
/opps.py:
--------------------------------------------------------------------------------
1 |
2 | class Student:
3 | def __init__(self,name,rollNO):
4 | self.name = name
5 | self.rollNO = rollNO
6 |
7 | def getName(self):
8 | print(self.name)
9 |
10 | def getRoll(self):
11 | print(self.rollNO)
12 |
13 |
14 |
15 |
16 |
17 |
18 | st1 = Student("Shubham",1001)
19 |
20 | st2 = Student("Aman",3002)
21 |
22 | st1.getRoll()
23 | st2.getRoll()
24 |
--------------------------------------------------------------------------------
/list.py:
--------------------------------------------------------------------------------
1 | list = [23,26,2,5,10,39];
2 |
3 |
4 | print((list))
5 |
6 | print(list[3]);
7 |
8 | print(list[-1]);
9 |
10 | print(list[0:3]);
11 |
12 | for s in list:
13 | print(s);
14 |
15 | list.append(5);
16 |
17 | list.insert(0,100);
18 |
19 | print(100 in list);
20 |
21 | print(900 in list)
22 |
23 | print((len(list)));
24 |
25 | print(list)
26 |
27 |
28 | i = 0;
29 |
30 | while i < len(list):
31 | print(list[i]);
32 | i+=1
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/mini_calculator.py:
--------------------------------------------------------------------------------
1 | first = input("enter first number : ");
2 | first = int(first);
3 | operator = input("enter opearation (+, -, %, /, *) : ");
4 | second = input("enter second number : ");
5 | second = int(second);
6 |
7 | if(operator == "+"):
8 | print(first+second);
9 |
10 | elif(operator == "-"):
11 | print(first-second);
12 |
13 | elif(operator == "*"):
14 | print(first*second);
15 |
16 | elif(operator == "/"):
17 | print(first/second);
18 |
19 | elif(operator == "%"):
20 | print(first%second);
21 |
22 | else:
23 | print("invalid operation");
--------------------------------------------------------------------------------
/for_loop_2.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | # for i in range(6):
4 | # print(i)
5 |
6 |
7 | set = {1,2,3,8,39,103,7,29,49,9}
8 |
9 |
10 | list = [1,39,0,30,20,40,192,503,5]
11 |
12 | dist = {1:"Shubham",
13 | 2:"Aman",
14 | 3:"Chinmay",
15 | 4:"Vivek"
16 | }
17 |
18 |
19 | l = len(dist)
20 |
21 | print(l)
22 |
23 | for i in range(len(dist)):
24 | print(dist.get(i+1))
25 |
26 |
27 | t = (1,3,5,6,8,9,0)
28 |
29 | for i in t:
30 | print(i)
31 | print("----------------")
32 | s = {1,2,2,3,3,4,5,5,6,3,2,2,6}
33 |
34 | for j in s:
35 | print(j)
--------------------------------------------------------------------------------
/rockPaperScissors.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 |
4 | def determine_winner(player_choice, computer_choice):
5 | if player_choice == computer_choice:
6 | return "It's a tie!"
7 | elif (
8 | (player_choice == "rock" and computer_choice == "scissors") or
9 | (player_choice == "paper" and computer_choice == "rock") or
10 | (player_choice == "scissors" and computer_choice == "paper")
11 | ):
12 | return "You win!"
13 | else:
14 | return "Computer wins!"
15 |
16 |
17 | def play_game():
18 | choices = ["rock", "paper", "scissors"]
19 | player_choice = input("Enter your choice (rock/paper/scissors): ").lower()
20 | if player_choice not in choices:
21 | print("Invalid choice. Please choose rock, paper, or scissors.")
22 | return
23 |
24 | computer_choice = random.choice(choices)
25 | print(f"Computer chose: {computer_choice}")
26 |
27 | result = determine_winner(player_choice, computer_choice)
28 | print(result)
29 |
30 |
31 | # Main loop
32 | while True:
33 | play_game()
34 | play_again = input("Do you want to play again? (yes/no): ").lower()
35 | if play_again != "yes":
36 | print("Thanks for playing!")
37 | break
38 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Learning Python Repository 🐍
2 |
3 | Welcome to the Learning Python repository! 🚀 This repository is your playground for learning and practicing Python programming through a collection of scripts that cover a wide range of topics.
4 |
5 |
6 | 
7 |
8 |
9 | ## Table of Contents
10 |
11 | - [Introduction](#introduction)
12 | - [Scripts](#scripts)
13 | - [Type Conversion](#type-conversion)
14 | - [Arithmetic Operators](#arithmetic-operators)
15 | - [Break and Continue](#break-and-continue)
16 | - [Comments in Python](#comments-in-python)
17 | - [Comparison Operators](#comparison-operators)
18 | - [Conditional Statements](#conditional-statements)
19 | - ... (and so on for all the scripts)
20 | - [Contributing](#contributing)
21 |
22 | ## Introduction 🌟
23 |
24 | Are you new to Python programming? Or are you a Pythonista looking to sharpen your skills? You're in for a treat! 🎉 This repository is all about hands-on learning, featuring a collection of scripts that focus on specific Python concepts. Whether you're just starting out or you're a seasoned coder, these scripts will help you grasp essential Python topics.
25 |
26 | ## Scripts 📜
27 |
28 | Here's a list of the scripts available in this repository, organized by topics:
29 |
30 | ### Type Conversion 🔄
31 | File: [Type_Conversion.py](Type_Conversion.py)
32 |
33 | This script takes you on a journey through the world of data type conversion in Python. Learn how to gracefully transform variables from one type to another – like turning a number into a string! 🧙♂️
34 |
35 | ### Arithmetic Operators ➗
36 | File: [arthematic_operators.py](arthematic_operators.py)
37 |
38 | Uncover the magic of arithmetic operators in Python! 🧮 Dive into addition, subtraction, multiplication, division, and more. This script is your gateway to mathematical wonders in code. 🔢
39 |
40 | ### Break and Continue ⏩
41 | File: [break_continue.py](break_continue.py)
42 |
43 | Navigate the twists and turns of loops with the power of `break` and `continue` statements. 🔄 Learn to steer loops your way with these handy tools, and conquer even the trickiest loops! 🎢
44 |
45 | ### Comments in Python 💬
46 | File: [comments_in_python.py](comments_in_python.py)
47 |
48 | Unlock the secret language of your code with comments! 🕵️♀️ This script teaches you how to add comments to your Python script, making your intentions crystal clear. Write code that speaks! 🗣️
49 |
50 | ### Comparison Operators 🧐
51 | File: [comparison_operators.py](comparison_operators.py)
52 |
53 | Step into the realm of comparisons with Python's trusty operators. 🕵️♂️ Learn how to interrogate your data using `==`, `!=`, `>`, `<`, `>=`, and `<=`, and make your code a true detective story! 🕵️♀️
54 |
55 | ### Conditional Statements 🌦️
56 | File: [conditional_statement.py](conditional_statement.py)
57 |
58 | Get ready for decision-making magic with Python's conditional statements! 🚦 Learn to choose paths in your code using `if`, `elif`, and `else`, and master the art of code direction. 🛤️
59 |
60 | ... (and so on for all the scripts)
61 |
62 | ## Contributing 🤝
63 |
64 | Join the Python party! 🎈 Contributions to this repository are not just welcome, they're celebrated! If you're itching to add more scripts, polish existing ones, or squash bugs, don't hesitate to create a pull request. By contributing, you're spreading the Python love! ❤️
65 |
66 | ## 📬 Contact
67 |
68 | If you want to contact me, you can reach me through below handles.
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 | Happy coding! 🐍💻
80 |
81 |
82 |
83 |
84 |
85 |
--------------------------------------------------------------------------------
/setOne.py:
--------------------------------------------------------------------------------
1 | # # S1 D3 Assignment - Set 1
2 |
3 | # ## Set 1
4 |
5 | # 1. **Hello, World!**: Write a Python program that prints "Hello, World!" to the console.
6 | # - *Input*: None
7 | # - *Output*: "Hello, World!"
8 | print("Hello, World!");
9 |
10 |
11 | # 2. **Data Type Play**: Create variables of each data type (integer, float, string, boolean, list, tuple, dictionary, set) and print their types and values.
12 | # - *Input*: None
13 | # - *Output*: "Type of variable1: , value: 10..."
14 | name = "Shubham";
15 | print(name,type(name))
16 |
17 | age = 23;
18 | print(age,type(age))
19 |
20 | salary = 70000.70;
21 | print(salary,type(salary))
22 |
23 | indian = True;
24 | print(indian,type(indian))
25 |
26 | my_list = [1, 2, 3, 4, 5]
27 | print(my_list,type(my_list))
28 |
29 | my_dict = {"name": "Aman", "age": 20, "city": "Indore"}
30 | print(my_dict,type(my_dict))
31 |
32 | my_set = {1, 2, 3, 4, 5}
33 | print(my_set,type(my_set))
34 |
35 |
36 |
37 |
38 |
39 | # 3. **List Operations**: Write a Python program to create a list of numbers from 1 to 10, and then add a number, remove a number, and sort the list.
40 | # - *Input*: None
41 | # - *Output*: "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20]..."
42 | list =[1,2,32,5,51,78,7,8,9,10]
43 | list.append(40)
44 | list.remove(5)
45 | list.sort();
46 | print(list)
47 |
48 |
49 | # 4. **Sum and Average**: Write a Python program that calculates and prints the sum and average of a list of numbers.
50 | # - *Input*: [10, 20, 30, 40]
51 | # - *Output*: "Sum: 100, Average: 25.0"
52 | list = [10,20,30,40];
53 | print(sum(list));
54 | print(sum(list)/len(list));
55 |
56 |
57 |
58 |
59 | # 5. **String Reversal**: Write a Python function that takes a string and returns the string in reverse order.
60 | # - *Input*: "Python"
61 | # - *Output*: "nohtyP"
62 | str2 = "shubham";
63 | print(str2[::-1]);
64 |
65 |
66 |
67 | # 6. **Count Vowels**: Write a Python program that counts the number of vowels in a given string.
68 | # - *Input*: "Hello"
69 | # - *Output*: "Number of vowels: 2"
70 |
71 | def count_vowels(input_string):
72 | vowels = "aeiouAEIOU"
73 | count = 0
74 |
75 | for char in input_string:
76 | if char in vowels:
77 | count += 1
78 |
79 | return count
80 |
81 | input_string = "Hello"
82 | num_vowels = count_vowels(input_string)
83 | print(f"Number of vowels: {num_vowels}")
84 |
85 |
86 | # 7. **Prime Number**: Write a Python function that checks whether a given number is a prime number.
87 | # - *Input*: 13
88 | # - *Output*: "13 is a prime number."
89 |
90 | def is_prime(number):
91 | if number < 2:
92 | return False
93 | elif number == 2:
94 | return True
95 |
96 |
97 | for i in range(2, int(number**0.5) + 1):
98 | if number % i == 0:
99 | return False
100 |
101 | return True
102 |
103 |
104 | input_number = 13
105 | if is_prime(input_number):
106 | print(f"{input_number} is a prime number.")
107 | else:
108 | print(f"{input_number} is not a prime number.")
109 |
110 |
111 |
112 | # 8. **Factorial Calculation**: Write a Python function that calculates the factorial of a number.
113 | # - *Input*: 5
114 | # - *Output*: "Factorial of 5 is 120."
115 |
116 | def factorial(number):
117 | if number < 0:
118 | return "Factorial is not defined for negative numbers."
119 | elif number == 0 or number == 1:
120 | return 1
121 | else:
122 | result = 1
123 | for i in range(2, number + 1):
124 | result *= i
125 | return result
126 |
127 | input_number = 5
128 | factorial_result = factorial(input_number)
129 | print(f"Factorial of {input_number} is {factorial_result}.")
130 |
131 |
132 | # 9. **Fibonacci Sequence**: Write a Python function that generates the first n numbers in the Fibonacci sequence.
133 | # - *Input*: 5
134 | # - *Output*: "[0, 1, 1, 2, 3]"
135 |
136 | def fibonacci_sequence(n):
137 | sequence = [0, 1]
138 |
139 | if n == 1:
140 | return [0]
141 | elif n == 2:
142 | return sequence
143 |
144 | for i in range(2, n):
145 | next_number = sequence[-1] + sequence[-2]
146 | sequence.append(next_number)
147 |
148 | return sequence
149 |
150 | input_n = 5
151 | fibonacci_result = fibonacci_sequence(input_n)
152 | print(fibonacci_result)
153 |
154 |
155 |
156 | # 10. **List Comprehension**: Use list comprehension to create a list of the squares of the numbers from 1 to 10.
157 | # - *Input*: None
158 | # - *Output*: "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]"
159 |
160 | squares_list = [i**2 for i in range(1, 11)]
161 | print(squares_list)
162 |
163 |
--------------------------------------------------------------------------------
/setThree.py:
--------------------------------------------------------------------------------
1 | # # S1 D3 Assignment - Set 3
2 |
3 | # 1. **Tuple Unpacking**: Create a list of tuples, each containing a name and an age. Then, use tuple unpacking to iterate through the list and print each name and age.
4 | # - *Input*: [("John", 25), ("Jane", 30)]
5 | # - *Output*: "John is 25 years old. Jane is 30 years old."
6 |
7 | data = [("John", 25), ("Jane", 30)]
8 |
9 | for name, age in data:
10 | print(f"{name} is {age} years old.")
11 |
12 |
13 |
14 |
15 |
16 | # 2. **Dictionary Manipulation**: Create a dictionary with keys as names and values as ages. Write functions to add a new name-age pair, update the age of a name, and delete a name from the dictionary.
17 | # - *Input*: Add "John": 25, Update "John": 26, Delete "John"
18 | # - *Output*: "{}, {'John': 26}, {}"
19 |
20 | def add_name_age(dictionary, name, age):
21 | dictionary[name] = age
22 |
23 | def update_age(dictionary, name, new_age):
24 | if name in dictionary:
25 | dictionary[name] = new_age
26 |
27 | def delete_name(dictionary, name):
28 | if name in dictionary:
29 | del dictionary[name]
30 |
31 | ages_dict = {}
32 | add_name_age(ages_dict, "John", 25)
33 | update_age(ages_dict, "John", 26)
34 | delete_name(ages_dict, "John")
35 |
36 | print(ages_dict)
37 |
38 |
39 | # 3. **Two Sum Problem**: Given an array of integers and a target integer, find the two integers in the array that sum to the target.
40 | # - *Input*: [2, 7, 11, 15], target = 9
41 | # - *Output*: "[0, 1]"
42 |
43 | def two_sum(nums, target):
44 | num_to_index = {}
45 |
46 | for index, num in enumerate(nums):
47 | complement = target - num
48 | if complement in num_to_index:
49 | return [num_to_index[complement], index]
50 | num_to_index[num] = index
51 |
52 | return None
53 |
54 | nums = [2, 7, 11, 15]
55 | target = 9
56 | result = two_sum(nums, target)
57 | print(result)
58 |
59 |
60 | # 4. **Palindrome Check**: Write a Python function that checks whether a given word or phrase is a palindrome.
61 | # - *Input*: "madam"
62 | # - *Output*: "The word madam is a palindrome."
63 |
64 | def is_palindrome(word):
65 | cleaned_word = word.lower().replace(" ", "")
66 | return cleaned_word == cleaned_word[::-1]
67 |
68 | input_word = "madam"
69 | if is_palindrome(input_word):
70 | print(f"The word {input_word} is a palindrome.")
71 | else:
72 | print(f"The word {input_word} is not a palindrome.")
73 |
74 |
75 | # 5. **Selection Sort**: Implement the selection sort algorithm in Python.
76 | # - *Input*: [64, 25, 12, 22, 11]
77 | # - *Output*: "[11, 12, 22, 25, 64]"
78 |
79 | def selection_sort(arr):
80 | n = len(arr)
81 | for i in range(n):
82 | min_index = i
83 | for j in range(i + 1, n):
84 | if arr[j] < arr[min_index]:
85 | min_index = j
86 | arr[i], arr[min_index] = arr[min_index], arr[i]
87 |
88 | input_array = [64, 25, 12, 22, 11]
89 | selection_sort(input_array)
90 | print(input_array)
91 |
92 |
93 |
94 | # 6. **Implement Stack using Queue**: Use Python's queue data structure to implement a stack.
95 | # - *Input*: push(1), push(2), pop(), push(3), pop(), pop()
96 | # - *Output*: "1, None, 3, None, None"
97 |
98 | from queue import Queue
99 |
100 | class StackUsingQueue:
101 | def __init__(self):
102 | self.queue1 = Queue()
103 | self.queue2 = Queue()
104 |
105 | def push(self, item):
106 | self.queue1.put(item)
107 |
108 | def pop(self):
109 | while self.queue1.qsize() > 1:
110 | self.queue2.put(self.queue1.get())
111 | popped_item = self.queue1.get()
112 | self.queue1, self.queue2 = self.queue2, self.queue1
113 | return popped_item
114 |
115 | stack = StackUsingQueue()
116 | stack.push(1)
117 | stack.push(2)
118 | print(stack.pop())
119 | stack.push(3)
120 | print(stack.pop())
121 | print(stack.pop())
122 |
123 |
124 |
125 | # 7. **FizzBuzz**: Write a Python program that prints the numbers from 1 to 100, but for multiples of three, print "Fizz" instead of the number, for multiples of five, print "Buzz", and for multiples of both three and five, print "FizzBuzz".
126 | # - *Input*: None
127 | # - *Output*: "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16,..."
128 |
129 | for num in range(1, 101):
130 | if num % 3 == 0 and num % 5 == 0:
131 | print("FizzBuzz")
132 | elif num % 3 == 0:
133 | print("Fizz")
134 | elif num % 5 == 0:
135 | print("Buzz")
136 | else:
137 | print(num)
138 |
139 |
140 |
141 |
142 | # 1. **File I/O**: Write a Python program that reads a file, counts the number of words, and writes the count to a new file.
143 | # - *Input*: A text file named "input.txt" with the content "Hello world"
144 | # - *Output*: A text file named "output.txt" with the content "Number of words: 2"
145 |
146 | with open("input.txt", "r") as file:
147 | content = file.read()
148 | word_count = len(content.split())
149 |
150 | with open("output.txt", "w") as file:
151 | file.write(f"Number of words: {word_count}")
152 |
153 |
154 |
155 | # 2. **Exception Handling**: Write a Python function that takes two numbers as inputs and returns their division, handling any potential exceptions (like division by zero).
156 | # - *Input*: 5, 0
157 | # - *Output*: "Cannot divide by zero."
158 |
159 | def divide_numbers(a, b):
160 | try:
161 | result = a / b
162 | return result
163 | except ZeroDivisionError:
164 | return "Cannot divide by zero."
165 |
166 | numerator = 5
167 | denominator = 0
168 | result = divide_numbers(numerator, denominator)
169 | print(result)
170 |
--------------------------------------------------------------------------------
/setTwo.py:
--------------------------------------------------------------------------------
1 | # # S1 D3 Assignment - Set 2
2 |
3 | # ### Problem **1: Print the following pattern**
4 |
5 | # Write a program to print the following number pattern using a loop.
6 |
7 | # ```
8 | # 1
9 | # 1 2
10 | # 1 2 3
11 | # 1 2 3 4
12 | # 1 2 3 4 5
13 | # ```
14 |
15 | def print_number_pattern(rows):
16 | for i in range(1, rows + 1):
17 | for j in range(1, i + 1):
18 | print(j, end=" ")
19 | print()
20 |
21 |
22 | rows = 5
23 | print_number_pattern(rows)
24 |
25 |
26 | # ### Problem **2: Display numbers from a list using loop**
27 |
28 | # Write a program to display only those numbers from a [list](https://pynative.com/python-lists/) that satisfy the following conditions
29 |
30 | # - The number must be divisible by five
31 | # - If the number is greater than 150, then skip it and move to the next number
32 | # - If the number is greater than 500, then stop the loop
33 |
34 | # **Given**:
35 |
36 | # ```
37 | # numbers = [12, 75, 150, 180, 145, 525, 50]
38 | # ```
39 |
40 | # **Expected output:**
41 |
42 | # ```
43 | # 75
44 | # 150
45 | # 145
46 | # ```
47 | def display_numbers(numbers):
48 | for num in numbers:
49 | if num % 5 == 0 and num <= 500:
50 | if num > 150:
51 | continue
52 | print(num)
53 | else:
54 | break
55 |
56 |
57 | numbers = [12, 75, 150, 180, 145, 525, 50]
58 | display_numbers(numbers)
59 |
60 |
61 | # ### Problem **3: Append new string in the middle of a given string**
62 |
63 | # Given two strings, `s1` and `s2`. Write a program to create a new string `s3` by appending `s2` in the middle of `s1`.
64 |
65 | # **Given**:
66 |
67 | # ```
68 | # s1 = "Ault"
69 | # s2 = "Kelly"
70 | # ```
71 |
72 | # **Expected Output**:
73 |
74 | # ```
75 | # AuKellylt
76 | # ```
77 |
78 | def append_middle(s1, s2):
79 | middle_index = len(s1) // 2
80 | s3 = s1[:middle_index] + s2 + s1[middle_index:]
81 | return s3
82 |
83 |
84 | s1 = "Ault"
85 | s2 = "Kelly"
86 | result = append_middle(s1, s2)
87 | print(result)
88 |
89 |
90 | # ### Problem **4: Arrange string characters such that lowercase letters should come first**
91 |
92 | # Given string contains a combination of the lower and upper case letters. Write a program to arrange the characters of a string so that all lowercase letters should come first.
93 |
94 | # **Given**:
95 |
96 | # ```
97 | # str1 = PyNaTive
98 | # ```
99 |
100 | # **Expected Output**:
101 |
102 | # ```
103 | # yaivePNT
104 | # ```
105 |
106 | def arrange_lowercase_first(input_str):
107 | return ''.join(sorted(input_str, key=lambda x: (x.isupper(), x)))
108 |
109 |
110 | str1 = "PyNaTive"
111 | result = arrange_lowercase_first(str1)
112 | print(result)
113 |
114 |
115 | # ### Problem **5: Concatenate two lists index-wise**
116 |
117 | # Write a program to add two lists index-wise. Create a new list that contains the 0th index item from both the list, then the 1st index item, and so on till the last element. any leftover items will get added at the end of the new list.
118 |
119 | # **Given**:
120 |
121 | # ```
122 | # list1 = ["M", "na", "i", "Ke"]
123 | # list2 = ["y", "me", "s", "lly"]
124 | # ```
125 |
126 | # **Expected output:**
127 |
128 | # ```
129 | # ['My', 'name', 'is', 'Kelly']
130 | # ```
131 |
132 | def concatenate_lists_indexwise(list1, list2):
133 | return [x + y for x, y in zip(list1, list2)]
134 |
135 |
136 | list1 = ["M", "na", "i", "Ke"]
137 | list2 = ["y", "me", "s", "lly"]
138 | result = concatenate_lists_indexwise(list1, list2)
139 | print(result)
140 |
141 |
142 | # ### Problem **6: Concatenate two lists in the following order**
143 |
144 | # ```
145 | # list1 = ["Hello ", "take "]
146 | # list2 = ["Dear", "Sir"]
147 | # ```
148 |
149 | # **Expected output:**
150 |
151 | # ```
152 | # ['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir']
153 | # ```
154 | list1 = ["Hello ", "take "]
155 | list2 = ["Dear", "Sir"]
156 |
157 | result = [x + y for x in list1 for y in list2]
158 |
159 | print(result)
160 |
161 |
162 | # ### Problem **7: Iterate both lists simultaneously**
163 |
164 | # Given a two Python list. Write a program to iterate both lists simultaneously and display items from list1 in original order and items from list2 in reverse order.
165 |
166 | # **Given**
167 |
168 | # ```
169 | # list1 = [10, 20, 30, 40]
170 | # list2 = [100, 200, 300, 400]
171 | # ```
172 |
173 | # **Expected output:**
174 |
175 | # ```
176 | # 10 400
177 | # 20 300
178 | # 30 200
179 | # 40 100
180 | # ```
181 |
182 | l = [10, 20, 30, 40]
183 | l2 = [100, 200, 300, 400]
184 |
185 | zipl = zip(l, l2[::-1])
186 |
187 |
188 | for num, num2 in zipl:
189 | print(num, num2)
190 |
191 |
192 | # ### Problem **8: Initialize dictionary with default values**
193 |
194 | # In Python, we can initialize the keys with the same values.
195 |
196 | # **Given**:
197 |
198 | # ```
199 | # employees = ['Kelly', 'Emma']
200 | # defaults = {"designation": 'Developer', "salary": 8000}
201 | # ```
202 |
203 | # **Expected output:**
204 |
205 | # ```
206 | # {'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma': {'designation': 'Developer', 'salary': 8000}}
207 | # ```
208 | employees = ['Kelly', 'Emma']
209 | defaults = {"designation": 'Developer', "salary": 8000}
210 | details = {employee: defaults.copy() for employee in employees}
211 |
212 | print(details)
213 |
214 |
215 | # ### Problem **9: Create a dictionary by extracting the keys from a given dictionary**
216 |
217 | # Write a Python program to create a new dictionary by extracting the mentioned keys from the below dictionary.
218 |
219 | # **Given dictionary**:
220 |
221 | # ```
222 | # sample_dict = {
223 | # "name": "Kelly",
224 | # "age": 25,
225 | # "salary": 8000,
226 | # "city": "New york"}
227 |
228 | # # Keys to extract
229 | # keys = ["name", "salary"]
230 | # ```
231 |
232 | # **Expected output:**
233 |
234 | # ```
235 | # {'name': 'Kelly', 'salary': 8000}
236 | # ```
237 |
238 | sample_dict = {
239 | "name": "Kelly",
240 | "age": 25,
241 | "salary": 8000,
242 | "city": "New york"}
243 |
244 | # Keys to extract
245 | keys = ["name", "salary"]
246 |
247 | ans = {"name": sample_dict.get("name"),
248 | "salery" : sample_dict.get("salary")
249 | }
250 |
251 | print(ans)
252 |
253 |
254 |
255 | # ### Problem **10: Modify the tuple**
256 |
257 | # Given a nested tuple. Write a program to modify the first item (22) of a list inside the following tuple to 222
258 |
259 | # **Given**:
260 |
261 | # ```
262 | # tuple1 = (11, [22, 33], 44, 55)
263 | # ```
264 |
265 | # **Expected output:**
266 |
267 | # tuple1: (11, [222, 33], 44, 55)
268 |
269 |
270 | tuple1 = (11, [22, 33], 44, 55)
271 |
272 | tuple1[1][0]=222
273 |
274 | print(tuple1)
--------------------------------------------------------------------------------
/setFour.py:
--------------------------------------------------------------------------------
1 | # # S1 D4 Assignment - Set 4
2 |
3 | # 1. **Anagram Check**: Write a Python function that checks whether two given words are anagrams.
4 | # - *Input*: "cinema", "iceman"
5 | # - *Output*: "True"
6 |
7 | def is_anagram(word1, word2):
8 | return sorted(word1) == sorted(word2)
9 |
10 | word1 = "cinema"
11 | word2 = "iceman"
12 | print(is_anagram(word1, word2))
13 |
14 |
15 |
16 | # 2. **Bubble Sort**: Implement the bubble sort algorithm in Python.
17 | # - *Input*: [64, 34, 25, 12, 22, 11, 90]
18 | # - *Output*: "[11, 12, 22, 25, 34, 64, 90]"
19 |
20 | def bubble_sort(arr):
21 | n = len(arr)
22 | for i in range(n):
23 | for j in range(0, n-i-1):
24 | if arr[j] > arr[j+1]:
25 | arr[j], arr[j+1] = arr[j+1], arr[j]
26 |
27 | input_array = [64, 34, 25, 12, 22, 11, 90]
28 | bubble_sort(input_array)
29 | print(input_array)
30 |
31 |
32 |
33 | # 3. **Longest Common Prefix**: Given a list of strings, find the longest common prefix.
34 | # - *Input*: ["flower","flow","flight"]
35 | # - *Output*: "fl"
36 | def longest_common_prefix(strs):
37 | if not strs:
38 | return ""
39 | common_prefix = strs[0]
40 | for word in strs[1:]:
41 | while word.find(common_prefix) != 0:
42 | common_prefix = common_prefix[:-1]
43 | return common_prefix
44 |
45 | input_strings = ["flower", "flow", "flight"]
46 | result = longest_common_prefix(input_strings)
47 | print(result)
48 |
49 |
50 |
51 | # 4. **String Permutations**: Write a Python function to calculate all permutations of a given string.
52 | # - *Input*: "abc"
53 | # - *Output*: "['abc', 'acb', 'bac', 'bca', 'cab', 'cba']"
54 |
55 | from itertools import permutations
56 |
57 | def string_permutations(s):
58 | return ["".join(p) for p in permutations(s)]
59 |
60 | input_string = "abc"
61 | permutations_list = string_permutations(input_string)
62 | print(permutations_list)
63 |
64 |
65 |
66 | # 5. **Implement Queue using Stack**: Use Python's stack data structure to implement a queue.
67 | # - *Input*: enqueue(1), enqueue(2), dequeue(), enqueue(3), dequeue(), dequeue()
68 | # - *Output*: "1, None, 3, None, None"
69 |
70 | class QueueUsingStack:
71 | def __init__(self):
72 | self.stack1 = []
73 | self.stack2 = []
74 |
75 | def enqueue(self, item):
76 | self.stack1.append(item)
77 |
78 | def dequeue(self):
79 | if not self.stack2:
80 | while self.stack1:
81 | self.stack2.append(self.stack1.pop())
82 | if self.stack2:
83 | return self.stack2.pop()
84 | else:
85 | return None
86 |
87 | queue = QueueUsingStack()
88 | queue.enqueue(1)
89 | queue.enqueue(2)
90 | print(queue.dequeue())
91 | queue.enqueue(3)
92 | print(queue.dequeue())
93 | print(queue.dequeue())
94 |
95 |
96 |
97 | # 6. **Missing Number**: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
98 | # - *Input*: [3, 0, 1]
99 | # - *Output*: "2"
100 |
101 | def missing_number(nums):
102 | n = len(nums)
103 | total_sum = n * (n + 1) // 2
104 | actual_sum = sum(nums)
105 | return total_sum - actual_sum
106 |
107 | input_nums = [3, 0, 1]
108 | result = missing_number(input_nums)
109 | print(result)
110 |
111 |
112 |
113 | # 7. **Climbing Stairs**: You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
114 | # - *Input*: 3
115 | # - *Output*: "3"
116 |
117 | def climb_stairs(n):
118 | if n <= 2:
119 | return n
120 | prev_1, prev_2 = 1, 2
121 | for i in range(3, n+1):
122 | curr = prev_1 + prev_2
123 | prev_1, prev_2 = prev_2, curr
124 | return prev_2
125 |
126 | steps = 3
127 | ways = climb_stairs(steps)
128 | print(ways)
129 |
130 |
131 |
132 | # 8. **Invert Binary Tree**: Invert a binary tree (mirroring it).
133 | # - *Input*: A binary tree
134 | # - *Output*: Inverted binary tree
135 |
136 | class TreeNode:
137 | def __init__(self, val=0, left=None, right=None):
138 | self.val = val
139 | self.left = left
140 | self.right = right
141 |
142 | def invert_tree(root):
143 | if not root:
144 | return None
145 | root.left, root.right = invert_tree(root.right), invert_tree(root.left)
146 | return root
147 |
148 |
149 |
150 |
151 |
152 | # 9. **Power of Two**: Given an integer, write a function to determine if it is a power of two.
153 | # - *Input*: 16
154 | # - *Output*: "True"1
155 |
156 | def is_power_of_two(n):
157 | if n <= 0:
158 | return False
159 | return (n & (n - 1)) == 0
160 |
161 | num = 16
162 | print(is_power_of_two(num))
163 |
164 |
165 | # 10. **Contains Duplicate**: Given an array of integers, find if the array contains any duplicates.
166 | # - *Input*: [1, 2, 3, 1]
167 | # - *Output*: "True"
168 |
169 | def contains_duplicate(nums):
170 | return len(nums) != len(set(nums))
171 |
172 | input_nums = [1, 2, 3, 1]
173 | print(contains_duplicate(input_nums))
174 |
175 |
176 | # 11. **Binary Search**: Write a function that implements binary search on a sorted array.
177 | # - *Input*: [1, 2, 3, 4, 5, 6], target = 4
178 | # - *Output*: "3"
179 |
180 | def binary_search(nums, target):
181 | left, right = 0, len(nums) - 1
182 | while left <= right:
183 | mid = (left + right) // 2
184 | if nums[mid] == target:
185 | return mid
186 | elif nums[mid] < target:
187 | left = mid + 1
188 | else:
189 | right = mid - 1
190 | return -1
191 |
192 | sorted_nums = [1, 2, 3, 4, 5, 6]
193 | target = 4
194 | index = binary_search(sorted_nums, target)
195 | print(index)
196 |
197 |
198 | # 12. **Depth First Search (DFS)**: Implement DFS for a graph in Python.
199 | # - *Input*: A graph
200 | # - *Output*: Vertices visited in DFS order
201 |
202 |
203 | class Graph:
204 | def __init__(self):
205 | self.graph = {}
206 |
207 | def add_edge(self, vertex, edge):
208 | if vertex in self.graph:
209 | self.graph[vertex].append(edge)
210 | else:
211 | self.graph[vertex] = [edge]
212 |
213 | def dfs(self, start):
214 | visited = set()
215 | stack = [start]
216 | while stack:
217 | vertex = stack.pop()
218 | if vertex not in visited:
219 | print(vertex, end=" ")
220 | visited.add(vertex)
221 | stack.extend(self.graph[vertex])
222 |
223 |
224 |
225 | # 13. **Breadth First Search (BFS)**: Implement BFS for a graph in Python.
226 | # - *Input*: A graph
227 | # - *Output*: Vertices visited in BFS order
228 | # 14. **Quick Sort**: Implement quick sort in Python.
229 | # - *Input*: [10, 7, 8, 9, 1, 5]
230 | # - *Output*: "[1, 5, 7, 8, 9, 10]"
231 |
232 | from collections import deque
233 |
234 | class Graph:
235 | def __init__(self):
236 | self.graph = {}
237 |
238 | def add_edge(self, vertex, edge):
239 | if vertex in self.graph:
240 | self.graph[vertex].append(edge)
241 | else:
242 | self.graph[vertex] = [edge]
243 |
244 | def bfs(self, start):
245 | visited = set()
246 | queue = deque([start])
247 | while queue:
248 | vertex = queue.popleft()
249 | if vertex not in visited:
250 | print(vertex, end=" ")
251 | visited.add(vertex)
252 | queue.extend(self.graph[vertex])
253 |
254 |
255 |
256 |
257 | # 15. **Single Number**: Given a non-empty array of integers, every element appears twice except for one. Find that single one.
258 | # - *Input*: [4,1,2,1,2]
259 | # - *Output*: "4"
260 |
261 | def single_number(nums):
262 | result = 0
263 | for num in nums:
264 | result ^= num
265 | return result
266 |
267 | input_nums = [4, 1, 2, 1, 2]
268 | result = single_number(input_nums)
269 | print(result)
270 |
271 |
272 | # 16. **Palindrome Linked List**: Given a singly linked list, determine if it is a palindrome.
273 | # - *Input*: [1,2,2,1]
274 | # - *Output*: "True"
275 |
276 |
277 | class ListNode:
278 | def __init__(self, val=0, next=None):
279 | self.val = val
280 | self.next = next
281 |
282 | def is_palindrome(head):
283 | values = []
284 | current = head
285 | while current:
286 | values.append(current.val)
287 | current = current.next
288 | return values == values[::-1]
289 |
290 |
291 |
292 |
--------------------------------------------------------------------------------