[MarsRover]

MarsRover()

Function Definition: MarsRover(Head = 4, Front Left = 1, Front Right = 7, Back Left = 2, Back Right = 6)

Parameters

NameTypeDescriptionExpected ValuesDefault Value
HeadintServo Port Number at which the Head Servo Motor is connected. 1-84
Front LeftintServo Port Number at which the Front Left Servo Motor is connected. 1-81
Front RightintServo Port Number at which the Front Right Servo Motor is connected. 1-87
Back LeftintServo Port Number at which the Back Left Servo Motor is connected. 1-82
Back RightintServo Port Number at which the Back Right Servo Motor is connected. 1-86

Description

The function initializes the Mars Rover object in Python and maps the 5 servos to the specified pins.

By default the following configuration is added:

  1. Head Servo – 4
  2. Front Left Servo – 1
  3. Front Right Servo – 5
  4. Back Left Servo – 2
  5. Back Right Servo – 6

Example

Learn about soil moisture sensors and how they work to measure the moisture level in the soil.
introduction

A soil moisture sensor is a valuable tool used to determine the moisture content in the soil, crucial for efficient gardening, farming, and agricultural practices. This analog sensor generates varying output values depending on the moisture level present in the soil. Typically, it operates as a two-pin circuit, with these pins responsible for powering up the sensor module. To obtain soil moisture readings, a voltage divider circuit is employed on the negative pin of the sensor, resulting in a signal pin that provides the moisture level data. Alternatively, some sensor modules come with a controller circuit that automatically converts the 2-pin connection into a 3-pin output, simplifying the process of accessing moisture values.

Below is a simple circuit diagram and code to get you started with monitoring soil moisture using an Arduino board. By following these steps, you can create your own moisture monitoring system with ease. Let’s begin!

 

Soil Moisture Sensor Hookup Guide - SparkFun LearnAuslese™ Detection Module Soil Moisture Sensor (Pack of 1Pcs) : Amazon.in: Industrial & Scientific

circuit diagram

Code

  1. Go to my variables and create a variable and name it “moisture level.” Set its initial value to 0.
  2. Add a “forever” loop from the control palette.
  3. Inside the forever loop, add a “set () to ()” block using the “my variable” category. Set the variable “moisture level” to the output value of the next block.
  4. From the Quarky palette, add the “map () from ()-() to ()-()” block. Replace the placeholder “0” with the map block.
  5. From the Sensors palette of Quarky, insert the “read analog sensor () at ()” block in place of “50”, and change the data range from 0-4095 to 0-100, as shown below. 0 stands for 100 percent moisture and 100 means completely dry
  6. Add an “if-else” block from the controls palette. Use it to check whether the value of the sensor is greater than 50% or not.
  7. If the value is greater than 50%, activate the buzzer connected to pin D2 otherwise the buzzer must remain off.
  8. Finally, add the “when flag clicked” block at the start of the script to initiate the monitoring process.

Script

 

With these steps, your script is complete, and you can now monitor the soil moisture effectively using the soil moisture sensor and Arduino board. Happy gardening and farming!

Output

 

 

 

Read More
Learn how to handle exceptions in Python without specifying a specific exception type. This comprehensive tutorial explores the use of a generic except block for robust error management.

Introduction:

Exception handling is a fundamental aspect of Python programming to manage errors gracefully. In this tutorial, we delve into handling exceptions without specifying a particular exception type. We demonstrate the use of a generic except block to catch any unanticipated exceptions. With a practical example, you’ll gain valuable insights into managing unforeseen errors in your Python code.

Code:

print("Handling exceptions without naming them")
try:
 numerator=50
 denom=int(input("Enter the denominator"))
 quotient=(numerator/denom)
 print("Division performed successfully")
except ValueError:
 print("Only INTEGERS should be entered")
except:
 print(" OOPS.....SOME EXCEPTION RAISED")

Logic:

  1. Display the message “Handling exceptions without naming them” to indicate the purpose of the code.
  2. The try block is introduced to encapsulate the code that may raise exceptions during execution.
  3. The variable numerator is set to 50. The input is converted to an integer using int() and stored in the denom variable.
  4. If the user enters a valid integer value for the denominator, the program proceeds to calculate the quotient (numerator/denom). The message “Division performed successfully” is printed to indicate the successful division.
  5. If the user enters a non-integer value (e.g., a string) for the denominator, a ValueError occurs during the conversion.
  6. If any other unanticipated exception occurs (not a ValueError), the generic except block catches it.
  7. The except block is executed with the message “OOPS…..SOME EXCEPTION RAISED,” providing a generic response for any unhandled exceptions.

Output:

>>Handling exceptions without naming them

>>Enter the denominator: 5

>>Division performed successfully

>>Enter the denominator: abc

>>Only INTEGERS should be entered

>>Enter the denominator: 0

>>OOPS…..SOME EXCEPTION RAISED

Read More
Learn how to interface a flex sensor with Quarky, the versatile microcontroller, to detect bending or flexing.
INTRODUCTION

The flex sensor is an ingenious device employing carbon on a plastic strip to serve as a variable resistor. As the sensor bends in one direction, its resistance varies accordingly. The more it bends, the higher the resistance becomes. This unique property makes it an ideal choice for applications where detecting bending or flexing is necessary.

In this example, we will be interfacing a flex sensor with Quarky and based on the change in its resistance we’ll be controlling the movement of our servomotor.

Circuit Diagram

 

Code

  1. Open Pictoblox and create a new file.
  2. Select Quarky from the board menu
  3. Create a variable called “sensor value” and set it to 0
  4. Add a “forever” block from the control palette.
  5. Inside the “forever” block, set “sensor value” to read analog sensor at A1.
  6. To convert this range to 0-180 for controlling the servo motor, use the “map” block from the Quarky palette and insert the sensor value in place of 50.
  7. Create another variable as “Servo angle”, Set the mapped value as the value of our new variable.
  8. connect servo at port servo 1 and fed variable servo angle as for the servo motor.
  9. Finally, add a “when flag clicked” event to complete the script and initiate the servo control with the flex sensor.

Script

OUTPUT

 

Output GIFs are need to be updated

 

 

Read More
Learn how to interface a joystick with Quarky, the versatile microcontroller, to control the movement of Quarky Robot in different directions.
Introduction

A joystick is an input device used to control the movement or actions of a computer, video game console, or other electronic device. In gaming, joysticks are often used to control the movement of characters or vehicles in a virtual environment. They provide analog input, meaning the degree of movement can vary based on how far the handle is pushed in a particular direction. In aviation and flight simulation, joysticks are commonly used to simulate the control of aircraft, providing pitch, roll, and yaw inputs. Some advanced joysticks also come with additional features such as throttle controls, programmable buttons, and force feedback to enhance the gaming or simulation experience. below is a simple animation of a joystick.

 

 

In this example, we’ll be interfacing a joystick with Quarky and try to find different directions for our robot by moving the joystick along the x and y axis let’s begin!!

Circuit Diagram

 

 

connection

JoyStick       Quarky

GND                          GND

5V                                  V

VarX                             A1

VarY                              A2

this is logic we will be using

Code

Remember that whenever we are moving the joystick in any direction, the value of both X and Y axis changes simultaneously, so we will be defining a range for both the X-axis and Y-axis so that when their values lie under this range our system must be able to decide the direction as forward,backward, left or right. based on the ranges and logic.

  1. Connect JoyStick as per the above connections.
  2. Open pictoblx and create a new file.
  3. Select Quarky from the board menu.
  4. Go to my blocks and create a new block as “forward”
  5. From controls palette, add if-than block with under forward block.
  6. From operators palette insert AND operator in if block.
  7. Again from operator palette, add grater then operator and first space of the AND block.
  8.  From Sensor palette of Quarky, choose the block “read analog sensor () at pin()” select joystick X from the dropdown and A1 from the dropdowns. change the value from 50 to 4000
  9. Again from the operator palette drag less then operator and insert in second space if the AND operator.
  10. From sensor palette of Quarky, insert read analog sensor () at pin (). in first space of the less than operator and change the value from 50 to 4100.
  11. Copy this if block and paste it inside the existing if block.
  12. this time change joystick X to joystick Y and pin from A1 to A2, as shown below.
  13. this time change the range for y from 1800  to 900 in first and second  space of grater than and less than operator respectively.
  14. From looks palette add say block in if block and inside the say block add join block from operators.
  15. replace apple with “forward >> ” and in place of banana add another join block.
  16.  This time in place of apple type “x = ” and again add join operator from operators palette in place of banana.
  17. In place of apple add “read analog sensor () at pin () ” from sensor palette. choose joystick X and A1 from dropdowns, Add another join block in place of banana.
  18.  this time in replace appl with “ y = ” and banana with “read analog  sensor () at () ”  block and choose joystick Y and A2 from the dropdowns.
  19. Now from display palette of Quarky,  drag “display matrix as ()” .
  20. Click on drop down and create a forward arrow on display.
  21. from Controls palette and wait for 0.25 seconds.
  22. create 3 more blocks for backwards, left and right prospectively. for backward.
  23.  Left
  24. Right
  25. Now let’s start writing the main script. from events palette add when flag clicked.
  26. From control palette add a forever block.
  27. finally, add all the blocks that you have created inside the forever block.

By following all the above steps, you will be able to control the robotic car in any direction you want.

Output

 

Read More
Joystick Is Basically Input Device That Will Be Used TO Control The Robotics And It Has Been Also Used In Gaming.  The Joystick Are Different Types And Uses In Different Purposes.
Introduction

Joystick Is Basically Input Device That Will Be Used TO Control The Robotics And It Has Been Also Used In Gaming.  The Joystick Are Different Types And Uses In Different Purposes. The Above Images Shows The Pins That Will Be Used For Interfacing With Hardware. We Know About The First Two Pin That Is Basic Pins Which Is Used In Every Hardware. That Is +5V And Another Is Ground. Another Three Pins Are Input And Output Pins. The VRx And VRy Are The Input Pin And SW Is The Output Pines Will Briefly Understand About The Interfacing Joystick With Arduino.

 

Circuit Diagram

 

Code

  1. Open PictoBlox and create a new file.
  2. Change the scripting mode from “stage” mode to “upload” mode.
  3. Click on the extension button and add the communication extension.
  4. From the Arduino palette, drag the “when Arduino starts up” block into the scripting area.
  5. click on communication extensions and drag  “set serial () baud rate to () ”  into the scripting area.
  6. Set the baud rate to 9600.
  7. From the controls palette, add the “forever” block.
  8. add all the blocks that you have created inside the forever block
  9. From controls palette, define forward block.

  • from the control pallet select AND  block
  • Again from the operator palette drag less then operator and insert in second space if the AND operator.
  • From sensor palette of Quarky, insert read analog sensor () at pin (). in first space of the less than operator and change the value from 0 to 100.

  • his time change joystick X to joystick Y and pin from A1 to A2, as shown below.
  • Add all these blocks
  • for backward
  • for right

  • for left

Output

Read More
Discover the resilience of Python's finally clause in this detailed guide. Learn how to handle exceptions while ensuring critical cleanup tasks. Explore a practical example that demonstrates the power of the finally clause in enhancing your Python programming skills.

Introduction:

Effective exception handling is vital for reliable Python code. In this guide, we delve into the finally clause, a potent construct for ensuring code cleanup regardless of exceptions. You’ll see how to manage division errors, including division by zero and non-integer inputs, all while executing essential tasks with the finally clause.

Code:

print("Handling exception using try...except...else...finally")
try:
  numerator=50
  denom=int(input("Enter the denominator: "))
  quotient=(numerator/denom)
  print("Division performed successfully")
except ZeroDivisionError:
  print("Denominator as ZERO is not allowed")
except ValueError:
  print("Only INTEGERS should be entered")
else:
  print("The result of division operation is ", quotient)
finally:
  print("OVER AND OUT")

Logic:

  1. Display “Handling exception using try…except…else…finally” to clarify the code’s intent.
  2. The try block contains code that may trigger exceptions during execution.
  3. Set numerator to 50.
  4. Prompt the user to enter the denominator using input.
  5. Convert the input to an integer and store it in denom.
  6. If a valid non-zero integer is given, calculate the quotient (numerator/denom).
  7. Print “Division performed successfully” to signify a successful division.
  8. If the user enters 0 as the denominator, a ZeroDivisionError occurs during the division operation.
  9. The except ZeroDivisionError block gracefully handles this specific exception Display “Denominator as ZERO is not allowed” to inform the user that division by zero is prohibited.
  10. If the user inputs a non-integer value (e.g., a string) for the denominator, a ValueError occurs during conversion.Display “Only INTEGERS should be entered” to convey that only integer values are accepted.
  11. If no exceptions arise (i.e., the try block executes without errors), the else block is executed. Inside the else block, print “The result of the division operation is” along with the calculated quotient, showcasing the successful division.
  12. The finally block is executed regardless of whether exceptions occurred. Inside the finally block, print “OVER AND OUT” to signal the completion of essential cleanup tasks.

Output:

>>Handling exception using try…except…elsefinally

>>Enter the denominator: 5

>>Division performed successfully

>>The result of the division operation is 10.0

>>OVER AND OUT

Read More
Enhance your Python programming skills by mastering the art of exception recovery using the finally clause. Join us in exploring a practical example that combines exception handling with code cleanup, ensuring your code remains robust and reliable.

Introduction:

Exception handling is a vital aspect of writing reliable Python code. In this guide, we delve into the powerful finally clause, which allows you to recover from exceptions while ensuring essential code cleanup. Through a practical example, you’ll learn how to handle division errors gracefully and execute necessary post-exception tasks.

Code:

print("Practicing for try block")
try:
  numerator=50
  denom=int(input("Enter the denominator"))
  quotient=(numerator/denom)
  print("Division performed successfully")
except ZeroDivisionError:
  print("Denominator as ZERO is not allowed")
else:
  print("The result of division operation is ", quotient)
finally:
  print("OVER AND OUT")

Logic:

  1. Display “Practicing for try block” to set the context for the code.
  2. The try block encapsulates code that may raise exceptions during execution.
  3. Initialize numerator to 50.
  4. Prompt the user to input the denominator using the input function.
  5. Convert the input to an integer and store it in denom.
  6. If a valid non-zero integer is entered, calculate the quotient (numerator/denom).
  7. Print “Division performed successfully” to signify a successful division.
  8. If the user enters 0 as the denominator, a ZeroDivisionError occurs during the division operation.
  9. The except ZeroDivisionError block gracefully handles this specific exception. Display “Denominator as ZERO is not allowed” to inform the user that division by zero is not permitted.
  10. If no exceptions arise (i.e., the try block executes without errors), the else block is executed.
  11. The finally block is executed regardless of whether exceptions occurred.

Output:

>>Practicing for try block Enter the denominator: 5

>>Division performed successfully

>>The result of division operation is 10.0

>>OVER AND OUT

Read More
Learn to navigate and control file objects using the seek() and tell() methods in Python. In this guide, we explore file manipulation techniques that enhance your understanding of file positioning and data extraction. Dive into practical examples and strengthen your Python programming skills today

Introduction:

File manipulation is a crucial skill for programmers working with data and files. In this tutorial, we delve into the seek() and tell() methods in Python, which allow you to navigate and extract data from files with precision. Through a practical example, you’ll learn how to move a file object, set its position, and retrieve content efficiently.

Code:

print("Learning to move the file object")
fobject = open("testfile.txt", "r+")
str = fobject.read()
print(str)
print("Initially, the position of the file object is: ", fobject.tell())

# Seek back to the beginning of the file before reading again
fobject.seek(0)
print("Now the file object is at the beginning of the file: ", fobject.tell())
fobject.seek(10)
print("We are moving to the 10th byte position from the beginning of the file")
print("The position of the file object is at", fobject.tell())
str = fobject.read()
print(str)

fobject.close()

Logic:

  1. Display “Learning to move the file object” to set the context for the code.
  2. Open the file “testfile.txt” in read and write mode (“r+”), and assign the file object to fobject.
  3. Read the entire content of the file using the read() method and store it in the variable str.
  4. Print the content of the file (str).
  5. Use the tell() method to determine the current position of the file object and print it as “Initially, the position of the file object is: “.
  6. Use the seek(0) method to move the file object’s position back to the beginning of the file.
  7. Print the new position of the file object using the tell() method, indicating “Now the file object is at the beginning of the file: “.
  8. Use the seek(10) method to move the file object’s position to the 10th byte from the beginning of the file.
  9. Print the new position of the file object using the tell() method as “We are moving to the 10th byte position from the beginning of the file”.
  10. Read the content from the current position of the file object using the read() method and store it in the variable str.
  11. Print the content extracted from the file (str).
  12. Close the file using the close() method

Output:

>>Learning to move the file object

>>roll_numbers = [1, 2, 3, 4, 5, 6]

>> Initially, the position of the file object is: 33

>> Now the file object is at the beginning of the file: 0

> We are moving to the 10th byte position from the beginning of the file

>> The position of the file object is at 10 >> rs = [1, 2, 3, 4, 5, 6]

Read More
Discover the power of pickling in Python for secure data storage. In this guide, we explore the pickle module, its functions, and its application in serializing and deserializing complex data structures. Unlock the potential of preserving data across sessions with ease.

Introduction:

In the realm of data storage, the Python pickle module plays a crucial role. This tutorial delves into pickling, a process that converts Python objects into a byte stream for secure storage or transmission. We’ll explore a practical example of pickling data, shedding light on how to serialize and deserialize complex structures using this versatile module.

Code:

import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()

Logic:

  1. Import the pickle module to enable data pickling.
  2. Create a list named listvalues containing various data types (integer, string, character, and integer).
  3. Open a file named “mybinary.dat” in binary write mode (“wb”) and assign the file object to fileobject.
  4. Use the pickle.dump() function to pickle (serialize) the listvalues into the file fileobject.
  5. Close the file using the close() method to ensure proper resource management.

Output:

The code snippet itself doesn’t generate any visible output. However, it successfully pickles the listvalues data into the “mybinary.dat” file using the pickle.dump() function. This process involves converting the Python data structure (in this case, the list) into a byte stream that can be stored in a file.

Read More
Learn how to create and write data to text files in Python effortlessly. Explore a detailed tutorial on text file manipulation, covering file creation, data input, and user interaction. Master the art of persistent data storage using practical examples.

Introduction:

Text file manipulation is a fundamental skill for Python programmers. In this tutorial, we provide a comprehensive guide on creating text files and writing data to them. Through a step-by-step example, you’ll learn how to interact with users to input data and populate a text file, enhancing your Python programming capabilities.

Code:

# program to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
 data= input("Enter data to save in the text file: ")
 fileobject.write(data)
 ans=input("Do you wish to enter more data?(y/n): ")
 if ans=='n': break
fileobject.close()

Logic:

  1. Open a file named “practice.txt” in write mode (“w+”) and assign the file object to fileobject.
  2. Enter a while loop that continues indefinitely until the user decides to stop.
  3. Prompt the user to enter data they wish to save in the text file using the input() function, and store the input in the variable data.
  4. Write the data to the file using the write method of the fileobject.
  5. Prompt the user whether they want to enter more data using the input function and store the answer in the variable ans.
  6. If the user’s input is ‘n’, exit the loop using the break statement.
  7. Close the file using the close() method to save changes and release resources.

Output:

>> Enter data to save in the text file: python
>>Do you wish to enter more data?(y/n): y
>>Enter data to save in the text file: i love
>>Do you wish to enter more data?(y/n): n

Read More
Discover the art of reading and displaying data from text files in Python. Explore an in-depth tutorial on file reading, covering opening files, reading lines, and user interaction. Learn to efficiently access and present file data through practical examples.

Introduction:

Effectively reading and displaying data from text files is a vital skill for any Python developer. In this tutorial, we delve into file reading techniques, guiding you through opening files, reading lines, and user interactions. Through a step-by-step example, you’ll grasp how to access and present file data in an organized manner.

Code:

# program to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
 data= input("Enter data to save in the text file: ")
 fileobject.write(data)
 ans=input("Do you wish to enter more data?(y/n): ")
 if ans=='n': break
fileobject=open("practice.txt","r")
str = fileobject.readline()
while str: 
 print(str)
 str=fileobject.readline()
fileobject.close() 

Logic:

  1. Create a file named “practice.txt” in write mode (“w+”) and assign the file object to fileobject.
  2. Use a while loop to repeatedly
  3. Prompt the user to input data they want to save in the text file using the input() function, and store the input in the variable data.
  4. Write the data to the file using the write method of fileobject.
  5. Ask the user whether they want to enter more data using the input() function and store the answer in the variable ans.
  6. If the user’s input is ‘n’, exit the loop using the break statement.
  7. Close the file using the close() method to save changes and release resources.
  8. Open the file “practice.txt” in read mode (“r”) and assign the file object to fileobject
  9. Use a while loop to read lines from the file using the readline() method.
  10. Initialize the variable str with the content of the first line.
  11. While str has content (not an empty line), print the content of str.
  12. Read the next line using readline and assign it to str
  13. Close the file using the close() method.

Output:

         >>Enter data to save in the text file: i love

>>Do you wish to enter more data?(y/n): y

>>Enter data to save in the text file: python

>>Do you wish to enter more data?(y/n): n

>>i lovepython

Read More
Discover the world of binary file handling in Python through a comprehensive tutorial. Learn how to perform essential operations on binary files using the pickle module, including data writing and reading. Dive into practical examples and enhance your Python programming skills today.

Introduction:

Binary file manipulation is a key skill for programmers dealing with data storage and retrieval. In this tutorial, we delve into binary file operations in Python, showcasing how to write and read employee records. By leveraging the pickle module, you’ll explore practical examples that demonstrate data serialization and deserialization, allowing you to store and retrieve complex data structures efficiently.

Code:

# Program to write and read employee records in a binary file
import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
 print("RECORD No.", recno)
 eno=int(input("\tEmployee number : "))
 ename=input("\tEmployee Name : ")
 ebasic=int(input("\tBasic Salary : "))
 allow=int(input("\tAllowances : "))
 totsal=ebasic+allow
 print("\tTOTAL SALARY : ", totsal)
 edata=[eno,ename,ebasic,allow,totsal]
 pickle.dump(edata,bfile)
 ans=input("Do you wish to enter more records (y/n)? ")
 recno=recno+1
 if ans.lower()=='n':
    print("Record entry OVER ")
    print()
    break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
# Reading the employee records from the file using load() module
print("Now reading the employee records from the file")
print()
readrec=1
try:
  with open("empfile.dat","rb") as bfile:
    while True:
      edata=pickle.load(bfile)
      print("Record Number : ",readrec)
      print(edata)
      readrec=readrec+1
except EOFError:
 pass
bfile.close()

Logic:

  1. Display “WORKING WITH BINARY FILES” to set the context for the code.
  2. Open a file named “empfile.dat” in binary append mode (“ab”) and assign the file object to bfile.
  3. Initialize recno as 1 to keep track of the record number.
  4. Display the current record number (recno).
  5. Prompt the user to input employee data, including employee number, name, basic salary, and allowances.
  6. Calculate the total salary as the sum of basic salary and allowances.
  7. Create a list named edata containing the employee data.
  8. Use the pickle.dump() function to serialize and write edata to the binary file.
  9. Prompt the user whether they want to enter more records. If the answer is ‘n’, exit the loop.
  10. Retrieve the size of the binary file using the tell() method and print it.
  11. Close the binary file using the close() method.
  12. Begin reading the employee records from the binary file using the load() function of the pickle module
  13. Open the “empfile.dat” file in binary read mode (“rb”)
  14. Load data from the file using pickle.load() and assign it to edata.
  15. Print the record number (readrec) and the loaded employee data.
  16. Increment readrec by 1.
  17. Handle the EOFError exception to stop reading when all records have been read.
  18. close the binary file.

Output:

>>WORKING WITH BINARY FILES

>>Enter Records of Employees

>>RECORD No. 1

>>Employee number : 2
Employee Name : shad
Basic Salary : 12000
Allowances : 1200
TOTAL SALARY : 13200

>>Do you wish to enter more records (y/n)? y

>>RECORD No. 2

>>Employee number : 5
Employee Name : anand
Basic Salary : 12000
Allowances : 1300
TOTAL SALARY : 13300

>>Do you wish to enter more records (y/n)? n

>>Record entry OVER

>>Size of binary file (in bytes): 241

>>Now reading the employee records from the file

>>Record Number : 1

>>[2, ‘shad’, 12000, 1200, 13200]

>>Record Number : 2

>>[5, ‘anand’, 12000, 1300, 13300]

 

Read More
Learn how to efficiently retrieve data using unpickling in Python. In this guide, we explore the process of unpickling, which involves deserializing data from binary files. Discover how the pickle module streamlines data retrieval with practical examples and deepen your Python programming skills.

Introduction:

Data retrieval is a vital aspect of programming, and Python’s pickle module simplifies the process through unpickling. This tutorial dives into the art of unpickling, explaining how to extract serialized data from binary files. By demonstrating the process with practical examples, you’ll gain insights into how to effectively retrieve stored data using Python.

Code:

import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)

Logic:

  1. Display “The data that were stored in file are: ” to set the context for the output.
  2. Open the binary file “mybinary.dat” in binary read mode (“rb”) and assign the file object to fileobject.
  3. Use the pickle.load() function to unpickle (deserialize) data from the binary file and assign it to the variable objectvar.
  4. Close the binary file using the close() method.
  5. Print the content of objectvar.

Output:

>>The data that were stored in file are:

>>[1, ‘Geetika’, ‘F’, 26]

Read More
Discover how to effortlessly manage text files in Python. Learn the art of writing and reading data to and from files, streamlining your data storage and retrieval processes. Explore practical examples and boost your Python programming skills today.

Introduction:

Text file handling is a core skill for programmers managing data. In this tutorial, we dive into writing and reading data to and from text files. Through a step-by-step example, you’ll grasp how to create, write, and read text files using Python. Enhance your programming prowess with these essential techniques.

Code:

fobject=open("testfile.txt","w") # creating a data file
sentence=input("Enter the contents to be written in the file: ")
fobject.write(sentence) # Writing data to the file
fobject.close() # Closing a file
print("Now reading the contents of the file: ")
fobject=open("testfile.txt","r")
#looping over the file object to read the file
for str in fobject: 
  print(str)
fobject.close()

Logic:

  1. Open a file named “testfile.txt” in write mode (“w”) and assign the file object to fobject.
  2. Prompt the user to input a sentence to be written to the file using the input() function, and store the input in the variable sentences.
  3. Write the content of the sentence variable to the file using the write() method of the fobject.
  4. Close the file using the close() method to save changes and release resources.
  5. Display “Now reading the contents of the file: ” to set the context for the output.
  6. Open the “testfile.txt” file in read mode (“r”) and assign the file object to fobject.
  7. Loop over the lines of the file using a for loop and the file object fobject. For each line, print the content of the line.
  8. Close the file using the close() method.

Output:

>>Enter the contents to be written in the file: happy

>>Now reading the contents of the file:

>>happy

Read More
Learn how to effectively display stack elements in Python. Explore the display function designed to showcase the current elements within a stack. Dive into practical examples and enhance your understanding of stack data structures through visualization.

Introduction:

Visualizing the contents of a stack is essential for understanding how stack data structures work. In this tutorial, we introduce the display function, which enables the visualization of stack elements. By providing a hands-on example, you’ll gain insight into printing stack elements in reverse order, improving your grasp of Python stack operations.

Code:

def display(glassStack):
  x=len(glassStack)
  print("Current elements in the stack are: ")
  for i in range(x-1,-1,-1):
     print(glassStack[i])
# First, create a glassStack list
glassStack = [1, 2, 3, 4]

# Call the display function to print the elements in the stack
display(glassStack)

Logic:

  1. Define the display function with a parameter named glassStack, representing the stack to be displayed.
  2. Calculate the length of the glassStack using the len() function and assign it to x.
  3. Print a message indicating “Current elements in the stack are:” to set the context for the output.
  4. Use a for loop to iterate through the elements of the glassStack in reverse order (from the last element to the first):
  5. Initialize i with the value x-1.
  6. Loop until i is greater than or equal to 0.
  7. Print the element at index i of the glassStack.
  8. Decrement i by 1 in each iteration.
  9. Create a list named glassStack with initial elements [1,2,3,4].
  10. Call the display function, passing the glassStack list as an argument, to print the elements in reverse order

Output:

>>Current elements in the stack are:

>>4

>>3

>>2

>>1

Read More
Dive into implementing a stack in Python, an essential data structure. Explore the isEmpty function designed to determine if a stack is empty. Learn through practical examples how stack operations can be streamlined using Python, and enhance your programming skills.

Introduction:

Understanding stack data structures is crucial for various applications. In this tutorial, we explore the implementation of a stack in Python and introduce the isEmpty function, which helps assess whether a stack is empty or not. By providing practical examples, you’ll delve into the core concepts of stack operations and gain valuable insights into managing data using Python.

Code:

def isEmpty(glassStack):
    return len(glassStack) == 0

glassStack = []
print(isEmpty(glassStack))  # Output: True

glassStack = [1, 2, 3]
print(isEmpty(glassStack))  # Output: False

Logic:

  1. Define the isEmpty function with a parameter named glassStack, representing the stack to be checked.
  2. Return True if the length of the glassStack is 0 (indicating an empty stack), otherwise return False.
  3. Create an empty list named glassStack.
  4. Call the isEmpty function with the glassStack list as an argument and print the result. The expected output is True, indicating an empty stack.
  5. Assign elements [1,2,3] to the glassStack list.
  6. Call the isEmpty function with the glassStack list as an argument and print the result. The expected output is False, indicating a non-empty stack.

Output:

>> True

>>False

 

Read More
Explore the opPop function in Python, designed to remove and return the top element from a stack. Discover the power of stack operations using practical examples. Learn how to handle underflow scenarios and streamline your programming skills.

Introduction:

Manipulating stack elements is a crucial skill in programming. In this tutorial, we delve into the opPop function, which facilitates the removal of the top element from a stack. Through practical examples, you’ll learn how to utilize this function to pop elements and handle underflow situations, enhancing your understanding of stack data structures in Python.

Code:

def isEmpty(glassStack):
    return len(glassStack) == 0

def opPop(glassStack):
    if isEmpty(glassStack):
        print('underflow')
        return None
    else:
        return glassStack.pop()

# Test the opPop function
glassStack = [1, 2, 3, 4]
result = opPop(glassStack)
print(result)  # Output: 4
print(glassStack)  # Output: [1, 2, 3] (the last element 4 is removed)

empty_stack = []
result_empty = opPop(empty_stack)
print(result_empty)  # Output: underflow

Logic:

  1. Define the isEmpty function with a parameter named glassStack, which returns True if the stack is empty (length is 0) and False otherwise.
  2. Define the opPop function with a parameter named glassStack
  3. Check if the stack is empty using the isEmpty function.
  4. If the stack is empty, print ‘underflow’, indicating that there is no element to pop, and return None.
  5. If the stack is not empty, use the pop() method to remove and return the top element of the stack.
  6. Initialize a glassStack list with elements [1,2,3,4].
  7. Call opPop(glassStack) and print the returned value. The expected output is 4.
  8. Print the updated glassStack list after the pop operation, which should now be [1,2,3].
  9. Initialize an empty empty_stack list.
  10. Call opPop(glassStack) and print the returned value. The expected output is ‘underflow’.

Output:

>>4

>>[1, 2, 3]

>>underflow

Read More
Master stack operations in Python through this comprehensive guide. Learn essential stack functions like opPush, opPop, isEmpty, size, top, and more. Explore practical examples showcasing stack management, element addition, removal, and visualization.

Introduction:

Stack operations are fundamental in computer science and programming. In this tutorial, we delve into various stack operations implemented in Python. From adding and removing elements to checking stack status and displaying contents, you’ll gain a solid understanding of stack manipulation. Through hands-on examples, you’ll enhance your Python programming skills and grasp the essence of stack data structures.

Code:

def isEmpty(glassStack):
    return len(glassStack) == 0

def opPush(glassStack, element):
    glassStack.append(element)

def size(glassStack):
    return len(glassStack)

def opPop(glassStack):
    if isEmpty(glassStack):
        print('underflow')
        return None
    else:
        return glassStack.pop()

def top(glassStack):
    if isEmpty(glassStack):
        print('Stack is empty')
        return None
    else:
        x = len(glassStack)
        return glassStack[x - 1]

def display(glassStack):
    x = len(glassStack)
    print("Current elements in the stack are:")
    for i in range(x - 1, -1, -1):
        print(glassStack[i])

# Initialize the stack
glassStack = list()

# add elements to stack
element = 'glass1'
print("Pushing element ", element)
opPush(glassStack, element)

element = 'glass2'
print("Pushing element ", element)
opPush(glassStack, element)

# display number of elements in stack
print("Current number of elements in stack is", size(glassStack))

# delete an element from the stack
element = opPop(glassStack)
print("Popped element is", element)

# add a new element to the stack
element = 'glass3'
print("Pushing element ", element)
opPush(glassStack, element)

# display the last element added to the stack
print("Top element is", top(glassStack))

# display all elements in the stack
display(glassStack)

# delete all elements from the stack
while True:
    item = opPop(glassStack)
    if item is None:
        print("Stack is empty now")
        break
    else:
        print("Popped element is", item)

Logic:

  1. Define the isEmpty function to check if a stack is empty.
  2. Define the opPush function to add an element to the stack.
  3. Define the size function to calculate the number of elements in the stack.
  4. Define the opPop function to remove and return the top element from the stack.
  5. Define the top function to retrieve the top element from the stack.
  6. Define the display function to print all elements in the stack.
  7. Initialize an empty glassStack list.
  8. Use the opPush function to add elements to the stack.
  9. Utilize the size function to display the number of elements in the stack.
  10. Employ the opPop function to remove an element from the stack and print it.
  11. Use the opPush function again to add a new element to the stack.
  12. Utilize the top function to display the top element.
  13. Use the display function to print all elements in the stack.
  14. Use a loop to empty the stack using the opPop function.

Output:

>>Pushing element glass1

>>Pushing element glass2

>>Current number of elements in stack is 2

>>Popped element is glass2

>>Pushing element glass3

>>Top element is glass3

>>Current elements in the stack are:

>>glass3

>>glass1

>>Popped element is glass3

>>Popped element is glass1

>>Stack is empty now

Read More
Discover the Python top function's role in obtaining the top element of a stack. Explore implementation details and practical examples showcasing stack element retrieval. Enhance your understanding of stack data structures through clear explanations and hands-on demonstrations.

Introduction:

The top function in Python plays a crucial role in accessing the top element of a stack without removing it. In this tutorial, we delve into the implementation and usage of the top function, which ensures efficient stack element retrieval. Through practical examples and explanations, you’ll gain insights into managing and navigating stack data structures using Python.

Code:

def isEmpty(glassStack):
    return len(glassStack) == 0

def top(glassStack):
    if isEmpty(glassStack):
        print('Stack is empty')
        return None
    else:
        x = len(glassStack)
        element = glassStack[x - 1]
        return element

# Test the top function
glassStack = [1, 2, 3, 4]
result = top(glassStack)
print(result)  # Output: 4

empty_stack = []
result_empty = top(empty_stack)
print(result_empty)  # Output: Stack is empty

Logic:

  1. Define the isEmpty function to check if a stack is empty.
  2. Define the top function with a parameter named glassStack to retrieve the top element of the stack.
  3. Check if the stack is empty using the isEmpty function.
  4. If the stack is empty, print ‘Stack is empty’ and return None.
  5. If the stack is not empty, calculate the length of the glassStack and assign it to x.
  6. Access the top element of the stack by retrieving glassStack[x-1] and return it
  7. Initialize a glassStack list with elements [1,2,3,4].
  8. Call the top function with the glassStack list as an argument and print the returned value. The expected output is 4.
  9. Initialize an empty empty_stack list.
  10. Call the top function with the empty_stack  list as an argument and print the returned value. The expected output is ‘Stack is empty’.

Output:

>>4

>>Stack is empty

Read More
Dive into the world of Python queues with this comprehensive guide. Discover the implementation of essential queue operations like enqueue and dequeue. Explore practical examples showcasing how to manage queues effectively, along with insights into queue sizes and emptiness checks.

Introduction:

Queues play a pivotal role in managing data structures. This tutorial delves into the implementation of queues in Python, covering key operations like enqueue and dequeue. Through real-world examples, you’ll learn how to create, manipulate, and efficiently manage queues, enhancing your Python programming skills along the way.

Code:

def isEmpty(myQueue):
    return len(myQueue) == 0

def enqueue(myQueue, element):
    myQueue.append(element)

def dequeue(myQueue):
    if isEmpty(myQueue):
        print('Queue is empty')
        return None
    else:
        return myQueue.pop(0)

def size(myQueue):
    return len(myQueue)

# Initialize the queue
myQueue = list()

# each person to be assigned a code as P1, P2, P3,...
element = input("Enter person’s code to enter in the queue: ")
enqueue(myQueue, element)

element = input("Enter person’s code for insertion in the queue: ")
enqueue(myQueue, element)

print("Person removed from the queue is:", dequeue(myQueue))
print("Number of people in the queue is:", size(myQueue))

element = input("Enter person’s code to enter in the queue: ")
enqueue(myQueue, element)

element = input("Enter person’s code to enter in the queue: ")
enqueue(myQueue, element)

element = input("Enter person’s code to enter in the queue: ")
enqueue(myQueue, element)

print("Now we are going to remove remaining people from the queue")
while not isEmpty(myQueue):
    print("Person removed from the queue is", dequeue(myQueue))
print("queue is empty")

Logic:

  1. Define the isEmpty function to check if a queue is empty.
  2. Define the enqueue function to add an element to the queue.
  3. Define the dequeue function to remove and return the front element from the queue.
  4. Define the size function to calculate the number of elements in the queue.
  5. Initialize an empty myQueue list.
  6. Use the enqueue function to add elements (person’s codes) to the queue.
  7. Use the dequeue function to remove a person from the front of the queue and print their code.
  8. Use the size function to display the number of people in the queue.
  9. Continue adding elements to the queue.
  10. Use a loop to remove remaining people from the queue using the dequeue function.

Output:

>>Enter person’s code to enter in the queue: P1

>>Enter person’s code for insertion in the queue: P2

>>Person removed from the queue is: P1

>>Number of people in the queue is: 1

>>Enter person’s code to enter in the queue: P3

>>Enter person’s code to enter in the queue: P4

>>Enter person’s code to enter in the queue: P5

>>Now we are going to remove remaining people from the queue

>>Person removed from the queue is P2

>>Person removed from the queue is P3

>>Person removed from the queue is P4

>>Person removed from the queue is P5

>>queue is empty

Read More
Explore the world of Python deques through this comprehensive guide. Discover how to implement essential deque operations like insertion, retrieval, and deletion. Dive into practical examples showcasing effective deque management and gain insights into different use cases for deques.

Introduction:

Python deques (double-ended queues) offer versatile data structure capabilities. In this tutorial, you’ll delve into deque implementation, covering key operations such as insertion, retrieval, and deletion. Through practical examples and explanations, you’ll learn how to create and manage deques effectively, enhancing your Python programming skills.

Code:

def insertFront(myDeque, element):
    myDeque.insert(0, element)

def getFront(myDeque):
    if not isEmpty(myDeque):
      return myDeque[0]
      print("Queue underflow")
      return None

def getRear(myDeque):
    if not isEmpty(myDeque):
      return myDeque[len(myDeque) - 1]
      print("Queue underflow")
      return None

def insertRear(myDeque, element):
    myDeque.append(element)

def isEmpty(myDeque):
    return len(myDeque) == 0

def deletionRear(myDeque):
    if not isEmpty(myDeque):
      return myDeque.pop()
      print("Queue underflow")
      return None

def deletionFront(myDeque):
    if not isEmpty(myDeque):
      return myDeque.pop(0)
      print("Queue underflow")
      return None

def main():
    dQu = list()
    choice = int(input('Enter 1 to use as normal queue, 2 otherwise: '))
    if choice == 1:
        element = input("Data for insertion at rear: ")
        insertRear(dQu, element)
        element = getFront(dQu)
        if element is not None:
          print("Data at the beginning of queue is", element)
        element = input("Data for insertion at rear: ")
        insertRear(dQu, element)
        data = deletionFront(dQu)
        if data is not None:
          print('Data removed from front of queue is', data)
        data = deletionFront(dQu)
        if data is not None:
          print('Data removed from front of queue is', data)
    else:
        element = input("Data for insertion at front: ")
        insertFront(dQu, element)
        element = getRear(dQu)
        if element is not None:
          print("Data at the end of queue is", element)
        element = input("Data for insertion at front: ")
        insertFront(dQu, element)
        data = deletionRear(dQu)
        if data is not None:
          print('Data removed from rear of queue is', data)
        data = deletionRear(dQu)
        if data is not None:
          print('Data removed from rear of queue is', data)

if __name__ == "__main__":
    main()

Logic:

  1. Define functions for deque operations, including insertFront, getFront, getRear, insertRear, isEmpty, deletionRear, and deletionFront.
  2. In the main function:
  3. Initialize an empty dQu list to represent the deque.
  4. Prompt the user to choose between using the deque as a normal queue or a reversed queue.
  5. Depending on the choice:
  6. Insert data at the front or rear of the deque.
  7. Retrieve and print data from the front or rear of the deque.
  8. Delete and print data from the front or rear of the deque.
  9. Call the main function if the script is executed as the main program.

Output:

>>Enter 1 to use as normal queue, 2 otherwise: 1

>>Data for insertion at rear: A

>>Data at the beginning of queue is A

>>Data for insertion at rear: B

>>Data removed from front of queue is A

>>Data removed from front of queue is B

Read More
Dive into the world of bubble sort algorithm using Python. Explore a step-by-step guide to implement bubble sort with practical examples. Learn how to efficiently sort a list of elements in ascending order using this simple yet effective sorting technique.

Introduction:

Bubble sort is a fundamental sorting algorithm that can be implemented using Python. This tutorial provides a comprehensive guide to implementing the bubble sort algorithm. Through practical examples and explanations, you’ll understand the logic behind bubble sort and how it efficiently sorts a list of elements in ascending order.

Code:

def bubble_Sort(list1):  # Number of passes
    n = len(list1)
    for i in range(n):
        for j in range(0, n-i-1): # size -i-1 because last i elements are already sorted 
            if list1[j] > list1[j+1]: # Swap element at jth position with (j+1)th position
                list1[j], list1[j+1] = list1[j+1], list1[j]

numList = [8, 7, 13, 1, -9, 4]
bubble_Sort(numList)
print("The sorted list is:")
for i in range(len(numList)):
    print(numList[i], end=" ")

Logic:

  1. Define the bubble_sort function that takes a list list1 as input.
  2. Get the length of the list n.
  3. Use nested loops to perform the bubble sort:
  4. The outer loop runs for n passes (one pass for each element).
  5. The inner loop compares adjacent elements and swaps them if necessary, effectively moving the largest element to the end of the list.
  6. The sorted list is printed after the sorting process is complete.

Output:

>The sorted list is:

>>-9 1 4 7 8 13

Read More
Explore the insertion sort algorithm using Python. Learn how to implement insertion sort step by step with practical examples. Discover an efficient sorting technique that arranges elements in ascending order, and see the algorithm in action through clear code examples.

Introduction:

Insertion sort is a classic sorting algorithm that can be effectively implemented using Python. This tutorial provides a detailed guide to implementing the insertion sort algorithm. By following practical examples and explanations, you’ll grasp the inner workings of insertion sort and how it efficiently organizes elements in ascending order.

Code:

def insertion_Sort(list3):
    n = len(list3)
    for i in range(n):  # Traverse through all elements
        temp = list3[i]  # Store the current element in a temporary variable
        j = i - 1  # Initialize the index of the previous element

        # Move elements of list3[0..i-1], that are greater than temp,
        # to one position ahead of their current position
        while j >= 0 and temp < list3[j]:
            list3[j + 1] = list3[j]  # Shift the element to the right
            j = j - 1

        # The loop above will stop when we find the correct position for temp
        # (i.e., when temp is not smaller than the element to its left).
        # Now, place temp in its correct position
        list3[j + 1] = temp

# Example usage
numList = [8, 7, 13, 1, -9, 4]
insertion_Sort(numList)

print("The sorted list is:")
for i in range(len(numList)):
    print(numList[i], end=" ")

Logic:

  1. Define the insertion_sort function that takes a list list3 as input.
  2. Get the length of the list n.
  3. Iterate through each element of the list using a loop:
  4. Store the current element in the variable temp.
  5. Initialize the index j to the previous element.
  6. Move elements greater than temp one position ahead.
  7. Place temp in its correct position in the sorted part of the list.
  8. The sorted list is printed after the sorting process is complete.

Output:

>The sorted list is:

>>-9 1 4 7 8 13

Read More
Discover the selection sort algorithm using Python. Learn how to implement selection sort step by step with practical examples. Explore an efficient sorting technique that arranges elements in ascending order, and witness the algorithm in action through clear code examples.

Introduction:

Selection sort is a simple yet effective sorting algorithm that can be implemented using Python. This tutorial provides a comprehensive guide to implementing the selection sort algorithm. Through practical examples and explanations, you’ll grasp the inner workings of selection sort and how it efficiently organizes elements in ascending order.

Code:

def selection_Sort(list2):
    n = len(list2)
    for i in range(n):  # Traverse through all list elements
        min = i
        for j in range(i + 1, len(list2)):  # The left elements are already sorted in previous passes
            if list2[j] < list2[min]:
                min = j
        if min != i:  # Next smallest element is found
            list2[min], list2[i] = list2[i], list2[min]

numList = [8, 7, 13, 1, -9, 4]
selection_Sort(numList)
print("The sorted list is:")
for i in range(len(numList)):
    print(numList[i], end=" ")

Logic:

  1. Define the selection_sort function that takes a list list2 as input.
  2. Get the length of the list n.
  3. Iterate through each element of the list using an outer loop:
  4. Initialize min as the current index i.
  5. Iterate through the remaining unsorted portion of the list using an inner loop.
  6. Find the index of the minimum element in the unsorted portion.
  7. Swap the minimum element with the element at index i if necessary.
  8. The sorted list is printed after the sorting process is complete.

Output:

>>The sorted list is:

>>-9 1 4 7 8 13

Read More
Discover the binary search algorithm using Python. Learn how to implement binary search step by step, and witness its efficiency in finding elements within a sorted list. Explore this powerful search technique and its practical application in Python programming.

Introduction:

Binary search is a highly efficient search algorithm used to find a specific element within a sorted list. This tutorial provides a comprehensive guide to implementing the binary search algorithm in Python. You’ll learn the step-by-step process of binary search, its underlying logic, and how it quickly locates elements in a sorted list.

Code:

def binarySearch(list, key):
    # Initialize the pointers for the search range.
    first = 0
    last = len(list) - 1

    # Perform binary search while the search range is valid.
    while first <= last:
        # Calculate the index of the middle element in the current search range.
        mid = (first + last) // 2

        # If the middle element is equal to the key, the key is found at index 'mid'.
        if list[mid] == key:
            return mid

        # If the key is greater than the middle element, search the right half of the list.
        elif key > list[mid]:
            first = mid + 1

        # If the key is smaller than the middle element, search the left half of the list.
        elif key < list[mid]:
            last = mid - 1

    # If the key is not found within the loop, return -1 to indicate that it's not present in the list.
    return -1

list1 = []  # Create an empty list

# Ask the user to enter elements in ascending order, stop when they enter -999.
print("Create a list by entering elements in ascending order")
print("Press enter after each element, press -999 to stop")
num = int(input())
while num != -999:
    list1.append(num)
    num = int(input())

# Ask the user to enter the key they want to search for.
n = int(input("Enter the key to be searched: "))

# Call the binarySearch function with the list and key as arguments.
pos = binarySearch(list1, n)

# Check the result of the binarySearch function and print appropriate messages.
if pos != -1:
    print(n, "is found at position", pos + 1)
else:
    print(n, "is not found in the list")

Logic:

  1. Define the binarySearch function that takes a list list and a search key as input.
  2. Initialize the search range pointers first and last to the beginning and end of the list, respectively.
  3. Perform binary search while the search range is valid (first is less than or equal to last).
  4. Calculate the index of the middle element using integer division.
  5. Compare the middle element with the search key.
  6. If they are equal, return the index mid indicating the key’s position.
  7. If the key is greater, adjust the search range to the right half of the list.
  8. If the key is smaller, adjust the search range to the left half of the list.
  9. If the key is not found within the loop, return -1 to indicate its absence in the list.

Output:

>>Create a list by entering elements in ascending order

>>Press enter after each element, press –999 to stop

>>1

>>3

>>5

>>7

>>9

>>11

>>13

>>15

>>-999

>>Enter the key to be searched: 7

>>7 is found at position 4

Read More
Learn how to perform linear search in Python to find an element in a list. Understand the logic, implementation, and output of the linear search algorithm.

Introduction:

This Python code demonstrates the implementation of the linear search algorithm. Linear search is a simple searching algorithm that sequentially checks each element in a list until a match is found or the entire list has been searched. It’s a straightforward method but might not be efficient for large datasets.

Code:

def linearSearch(list, key):
    # function to perform the search
    for index in range(0, len(list)):
        if list[index] == key:  # key is present
            return index + 1  # position of key in list
    return None  # key is not in list
# end of function

list1 = []  # Create an empty list
maximum = int(input("How many elements in your list? "))
print("Enter each element and press enter: ")
for i in range(0, maximum):
    n = int(input())
    list1.append(n)  # append elements to the list
print("The List contents are:", list1)
key = int(input("Enter the number to be searched:"))
position = linearSearch(list1, key)
if position is None:
    print("Number", key, "is not present in the list")
else:
    print("Number", key, "is present at position", position)

Logic:

  1. The linearSearch function takes a list and a key as its parameters.
  2. It iterates through each element in the list and compares it with the key.
  3. If a match is found, the function returns the position (index + 1) of the key in the list.
  4. If no match is found after checking all elements, the function returns None to indicate that the key is not present in the list.
  5. The user is prompted to enter the number of elements in the list and the elements themselves.
  6. The linearSearch function is called to search for the user-provided key in the list.
  7. The program outputs whether the key is present in the list and its position if found.

Output:

>>How many elements in your list? 5

>>Enter each element and press enter:

>>12

>>45

>>8

>>3

>>67

>>The List contents are: [12, 45, 8, 3, 67]

>>Enter the number to be searched: 8

>>Number 8 is present at position 3

Read More
Explore the implementation of a hash table search in Python using a hash function. Understand the logic, example usage, and output of the hash table search algorithm.

Introduction:

This Python code demonstrates the use of a hash table to perform a search for an element using a hash function. A hash table is a data structure that stores key-value pairs and provides fast retrieval of values based on their keys. In this example, we use a simple hash function to map keys to positions in the hash table.

Code:

# Function to check if a key is present in the hash table
def hashFind(key, hashTable):
    if (hashTable[key % 10] == key):  # key is present
        return key % 10 + 1  # return the position
    else:
        return None  # key is not present
# end of function

# Create hashTable with 10 empty positions
hashTable = [None, None, None, None, None, None, None, None, None, None]
print("We have created a hashTable of 10 positions:")
print(hashTable)

# Given list
L = [34, 16, 2, 93, 80, 77, 51]
print("The given list is", L)

# Apply the hash function and populate the hash table
for i in range(0, len(L)):
    hashTable[L[i] % 10] = L[i]

# Print the contents of the hash table
print("The hash table contents are:")
for i in range(0, len(hashTable)):
    print("hashindex=", i, ", value =", hashTable[i])

# Ask the user to enter the number they want to search for
key = int(input("Enter the number to be searched:"))
position = hashFind(key, hashTable)

# Check the result of the hashFind function and print appropriate messages
if position is None:
    print("Number", key, "is not present in the hash table")
else:
    print("Number", key, "present at", position, "position")

Logic:

  1. The hashFind function takes a key and a hash table as its parameters.
  2. It calculates the hash index for the key using the modulo operation (key % 10) to map the key to a position in the hash table.
  3. It then checks if the key at the calculated hash index in the hash table matches the given key.
  4. If a match is found, the function returns the position (hash index + 1) of the key in the hash table.
  5. If no match is found, the function returns None to indicate that the key is not present in the hash table.
  6. The user is prompted to enter a list of numbers, and the hash table is populated using the hash function.
  7. The contents of the hash table are printed.
  8. The user is asked to enter the number they want to search for.
  9. The hashFind function is called to search for the user-provided key in the hash table.
  10. The program outputs whether the key is present in the hash table and its position if found.

Output:

>>We have created a hashTable of 10 positions:

>>[None, None, None, None, None, None, None, None, None, None]

>>The given list is [34, 16, 2, 93, 80, 77, 51]

>>The hash table contents are: hashindex= 0 , value = 80

>>hashindex= 1 , value = 51

>>hashindex= 2 , value = 2

>>hashindex= 3 , value = 93

>>hashindex= 4 , value = 34

>>hashindex= 5 , value = 16

>>hashindex= 6 , value = 77

>>hashindex= 7 , value = None

>>hashindex= 8 , value = None

>>hashindex= 9 , value = None

>>Enter the number to be searched: 93

>>Number 93 present at 4 position

Read More
Create a code that calculates mean of a list of floating point values. It adds up all the numbers and divides by the total count of elements.

Introduction:

This code defines a Python function that calculates the mean of a list of floating point values. The function takes one parameter – a list containing floating point values. It then adds all the numbers in the list and divides the total by the number of elements to compute the mean value. Finally, it prints the calculated mean.

Code:

#Function to calculate mean
#The requirements are listed below:
#1. The function should have 1 parameter (list containing floating point values)
#2. To calculate mean by adding all the numbers and dividing by total number of elements
 
def myMean(myList): #function to compute means of values in list 
 total = 0
 count = 0 
 for i in myList:
  total = total + i #Adds each element i to total
  count = count + 1 #Counts the number of elements
 mean = total/count #mean is calculated
 print("The calculated mean is:",mean) 
myList = [1.3,2.4,3.5,6.9]
#Function call with list "myList" as an argument
myMean(myList)

Logic:

  1. The function iterates through each element in the list and adds it to a running total.
  2. It also keeps track of the count of elements.
  3. After iterating through all the elements, it divides the total by the count to compute the mean value.
  4. The mean is then printed as output.

Output:

>> The calculated mean is: 3.5250000000000004

Read More
This Python code calculates the factorial of a given number using a for loop and displays the result

Brief Introduction:

This Python code calculates the factorial of a given number using a for loop and displays the result.

Code:

#Function to calculate factorial
#The requirements are listed below:
 #1. The function should accept one integer argument from user.
 #2. Calculate factorial. For example:
 #3. Display factorial
def calcFact(num):
 fact = 1
 for i in range(num,0,-1):
  fact = fact * i
 print("Factorial of",num,"is",fact)
 
num = int(input("Enter the number: "))
calcFact(num)

Logic:

  1. The code defines a function named ‘calcFact’ that accepts one integer argument ‘num’.
  2. It initializes a variable ‘fact’ to 1.
  3. Then, it runs a for loop starting from ‘num’ and decreasing by 1 each time.
  4. Inside the loop, it updates the ‘fact’ variable by multiplying it with the current iteration value.
  5. Finally, it prints the factorial of the input number by displaying the value of ‘num’ and ‘fact’.

Output:

The code prompts the user to enter a number, calculates the factorial of the input number using the ‘calcFact’ function, and displays the factorial as “Factorial of [num] is [fact]”.

Enter the number: 10

>> Factorial of 10 is 3628800

 

Read More
This code takes a first name and last name as input and combines them using the + operator to form a full name, which is then displayed.

Introduction:

This Python code demonstrates a simple function that accepts a first name and a last name as parameters. It then concatenates the first name and last name using the + operator and a space to create a full name. Finally, it displays the full name using the print() function.

Code:

#Function to display full name
#The requirements are listed below:
 #1. The function should have 2 parameters to accept first name and 
 #last name.
 #2. Concatenate names using + operator with a space between first 
 #name and last name.
 #3. Display full name.
def fullname(first,last): 
#+ operator is used to concatenate strings
 fullname = first + " " + last 
 print("Hello",fullname) 
#function ends here
first = input("Enter first name: ")
last = input("Enter last name: ")
#function call 
fullname(first,last)

Logic:

  1. Define a function called “fullname” that accepts two parameters: “first” for the first name and “last” for the last name.
  2. Inside the function, concatenate the first name, a space, and the last name using the + operator. Store the result in a variable called “fullname”.
  3.  Use the print() function to display the full name with a greeting.
  4.  Outside the function, prompt the user to enter their first name and last name using the input() function and store the values.

Output:

The output of this code will be “Hello [Full Name]”. The full name will be displayed by concatenating the first name and last name entered by the user using the + operator with a space between them. The greeting “Hello” will be displayed before the full name.

Enter first name: STEM

Enter last name: Learners

>> Hello STEM Learners

Read More
All articles loaded
No more articles to load
Table of Contents
[PythonExtension]