0% found this document useful (0 votes)
22 views

Lesson 12 Logic Programming

Uploaded by

weaverjordan210
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lesson 12 Logic Programming

Uploaded by

weaverjordan210
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Lesson 11: Logic Programming in Python

Logic Programming uses facts and rules for solving the problem. That is why they are
called the building blocks of Logic Programming. A goal needs to be specified for every
program in logic programming. To understand how a problem can be solved in logic
programming, we need to know about the building blocks − Facts and Rules −
Facts
Actually, every logic program needs facts to work with so that it can achieve the given
goal. Facts basically are true statements about the program and data. For example,
Delhi is the capital of India.
Rules
Actually, rules are the constraints which allow us to make conclusions about the
problem domain. Rules basically written as logical clauses to express various facts. For
example, if we are building any game then all the rules must be defined.
Rules are very important to solve any problem in Logic Programming. Rules are
basically logical conclusion which can express the facts. Following is the syntax of rule

A∶− B1,B2,...,Bn.
Here, A is the head and B1, B2, ... Bn is the body.
For example − ancestor(X,Y) :- father(X,Y).
ancestor(X,Z) :- father(X,Y), ancestor(Y,Z).
This can be read as, for every X and Y, if X is the father of Y and Y is an ancestor of Z,
X is the ancestor of Z. For every X and Y, X is the ancestor of Z, if X is the father of Y
and Y is an ancestor of Z.

Installing Useful Packages


For starting logic programming in Python, we need to install the following two packages

Kanren
It provides us a way to simplify the way we made code for business logic. It lets us
express the logic in terms of rules and facts. The following command will help you install
kanren −
pip install kanren
SymPy
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured
computer algebra system (CAS) while keeping the code as simple as possible in order
to be comprehensible and easily extensible. The following command will help you install
SymPy −
pip install sympy

1.Count the number of digits in a Number in


Python
Write a program to count the number of digits of a given number.
Sample Input 1:
345
Sample Output 1:
3
Sample Input 2:
56
Sample Output 2:
2

Program or Solution
n = int(input())
count = 0
while n > 0:
n = n // 10
count = count + 1
print(count)

Program Explanation
if we divide a number by 10, then last digit of the same number will removed and we get
remaining digits as output. Do the same till number becomes 0 and count iteration. So the
count is number of digits of the given number .

2.Count the Number of Occurrences of digit in a


number using Python
Get a number and a digit and find occurrences of digit in the number.
Sample Input 1:
Enter the number: 2434
Enter the Digit : 4
Sample Output 1:
4 is occurred 2 times in 234
Sample Input 2:
Enter the number: 974
Enter the Digit : 3
Sample Output 2:
3 is occurred 0 times in 974

Program or Solution

num = int(input("Enter the number"))


digit = int(input("Enter a Digit"))
count = 0
n = num
while n != 0:
rem = n % 10
if rem == digit:
count+=1
n = n // 10
print("{} occured {} times in {}".format(digit,count,num))
Program Explanation
initialize count is equal to 0
calculate the remainder of a number by doing number % 10
check remainder is equal to digit, if it is equal increment the count by 1 , else divide
number by the 10 and repeat the above steps till number becomes zero.
print the count.

3.Sum of Digits of the number using Python


Get a number and sum the digits of the number.
Sample Input 1:
Enter the number: 234
Sample Output 1:
9

Program or Solution

num = int(input("enter a number"))


n = num
total = 0
while n != 0:
rem = n % 10
total = total + rem
n = n // 10
print(total)

Program Explanation
initialize total is equal to 0
calculate the remainder of a number by doing number % 10, add the remainder to total
and divide the number by the 10 and repeat the above steps till number becomes zero.
Print the total, you will get the sum of digits of the number

4.Reverse the digits of a number using Python


Get a number and reverse the digits of the number.
Sample Input 1:
Enter the number: 234
Sample Output 1:
432 is reverse of 234

Flow Chart Design


Program or Solution

num = int(input("enter a number"))


n = num
reverse = 0
while n != 0:
rem = n % 10
reverse = reverse * 10 + rem
n = n // 10
print("{} is reverse of {}".format(reverse,num))

Output

Program Explanation
initialize total is equal to 0
calculate the remainder of a number by doing number % 10, add the remainder to (total *
10) and divide the number by the 10 and repeat the above steps till number becomes zero.
Print the total, you will get the sum of digits of the number.

5.Simple Guessing Game in Python


"Simple Guessing Game"
Create a simple guessing game in which the user must guess the secret number in one
attempt. If the user correctly guessed the secret number, the system should display "your
guess is correct," otherwise it should display the message "your guess is wrong" and the
guessed number.
Hint : Basic if-else condition is enough for this.
Objective : To learn the usage of if-else conditional statement.

Program or Solution
#hashed lines are comment lines used to illustrate the program

#import the built in method randint to generate an automatic secret number

from random import randint

#Generate automatic Secret Number

secret_number = randint(1,5)

#Get a guessing number from user

guess_number = int(input("Guess the secret number between 1 and 5:"))

#check guessing number is correct or not

if secret_number == guess_number:

print("Your Guess is Correct")

else:

print("Your Guess is Wrong, the secret number is


{}".format(secret_number))

Program Explanation
Line 3: Imports the randint function from the package random
Line 5: using randint system generates a secret number
Line 7 : getting a guess from user
line 9 : check whether secret number generated by system and guessing number entered
by user are same
line 10 : if same, display "your guess is correct"
line 12 : if not same, display "your guess is wrong"

6.Multi Stage Guessing Game with Scoring Board


"Multi Stage Guessing Game and Points of every stage"
Create a three stage guessing game with point scoring in each stage the
user must guess the secret number in five attempts. Range of Secret number
should be increased at stage like 1 to 10 in stage in 1, 1 to 20 in stage 2 and
1 to 30 in stage 3. If the user correctly guessed the secret number, the
system should display "your guess is correct" and moves to next stage;
otherwise, it should tell the user whether the guessed number is higher or
lower than the secret number and proceed to the next attempt. If the user
fails to guess correctly after five attempts, the game should end with the
message "Game Over, You Lose the Game." If user successfully guessed in
all the three stages, display "You won the Game with scored points", then
points scored at each level and stops the game.

At each stage the points will be awarded to user based on following condition

Solved in points
first attempt 100
second attempt 75
third attempt 50
fourth attempt 25
fifth attempt 10

Hint : Sequence Type (list) is needed for this.


Objective : To learn the declaration and usage of list.

Program or Solution

#hashed lines are comment lines used to illustrate the program

#import the built in method randint to generate an automatic secret number

from random import randint

# initiate level or stage as 1

level = 1

#sequence type to store points

points = [100,75,50,25,10]

#sequence type to store points scored at each level


points_scored = list()

#loop for 3 stages

while level <= 3:

#complexity range for each stage

end_value = level * 10

#secret number generation

secret_number = randint(1,end_value)

#looping statement for 5 attempts at each stage

for counter in range(0,5):

#gets the guessing number as user input

guess_number = int(input("Guess the secret number between 1 and {}


({} attempts left):".format(end_value,5-counter)))

#check guessing number is correct or higher or lower

if secret_number == guess_number:

print("Your Guess is Correct, You Won the level {} with {}


points".format(level,points[counter]))

#add the point scored in this stage into the list

points_scored.append(points[counter])

level = level + 1

break

elif guess_number < secret_number:

print("Your Guess is lower than secret number")

else:

print("Your Guess is higher than secret number")

else:

print("Game Over, You Loose the Game, secret number is


{}".format(secret_number))

break

else:
print("Congratz, You Won the Game with
{} !!!".format(sum(points_scored)))

#loop to display scored points in every stage

for i in range(0,3):

print("level {} points {}".format(i+1, points_scored[i])) '''

Program Explanation
Logic is same as level 4, in addition,
points are stored using list
points_scored variable is a list which stores the points scored by user at each stage
the final for loop shows the points scored by user at each stage.

7.Python Program for Prime numbers between two


numbers
Get two inputs x and y and print all the prime numbers between x and y.
Sample Input 1 :
10 40
Sample Output 1 :
11 13 17 19 23 29 31 37

Program or Solution

#Python Program to print prime numbers between x and y


x = int(input("Enter a Number X:")) #get input x
y = int(input("Enter a Number Y:")) #get input y
#start your travel from x to y
for n in range(x,y+1):
#check which are the numbers from 2 to n/2 divides n.
#No other after n/2 divides n except n

for i in range(2,n//2+1):
if n % i == 0: #if divisible then it is not prime.
break
else: #this is else of for statement. executes after last iteration if
loop is not broken at any iteration.
print("{} ".format(n))

Program Explanation
Prime numbers are numbers those only divisible by 1 and same. using a outer for loop we
check take every number n from x to y
Inner for loop checks each number is prime or not, if prime it prints the n.

8.Python Billing System


Read this Carefully.
Write a Python Program to calculate sale bill for the selling items in a Fruit Shop.
Consider the following dictionary as a item database.
items = {
101:{'item_name':'Apple','Quantity_in_kgs':50,'Price_per_kg':200},

102:{'item_name':'Banana','Quantity_in_kgs':30,'Price_per_kg':80},
103:{'item_name':'Grapes','Quantity_in_kgs':25,'Price_per_kg':300},

104:{'item_name':'Lemon','Quantity_in_kgs':20,'Price_per_kg':70}
}

Initially the transaction dictionary is Null.


trans = {}

Code the following tasks to implement Billing System for a Fruit Shop.

1. Add Fruits to the System


a. Check whether the fruit is exists in database
b. if exists, Get id & Quantity and add the quantity to existing quantity
c. if not exists, Get id, name,quantity & price and add to dictionary

2. Calculate Bill During Sale.


a. Get id & quantity and calculate bill for one or more items
b. Calculate amount for each item
c. Reduce the sold quantity of corresponding item in items database.
d. Add item to transaction as below
trans = {201:{101:[2,400],104:[.5,35]}}
Here in Transaction 201: 2 kg apples for $400 and half kg lemon for
$35 were sold.
e. Display items, quantity, amount and total on each item entry

3. Check Stock
a. Display the items and available quantity
b. Highlight the items which are available less than 5 kgs.

Program or Solution
items = {
101:
{'item_name':'Apple','Quantity_in_kgs':50,'Price_per_kg':200},
102:
{'item_name':'Banana','Quantity_in_kgs':30,'Price_per_kg':80},
103:
{'item_name':'Grapes','Quantity_in_kgs':25,'Price_per_kg':300},
104:
{'item_name':'Lemon','Quantity_in_kgs':20,'Price_per_kg':70}
}

trans = {}
#Stock Printing
def stock_check():
print("Item Name | Available Stock")
for item_id in items:

if items[item_id]['Quantity_in_kgs'] <= 5:

print("----------------------------------------")
print("| ",items[item_id]['item_name'], " | ",items[item_id]
['Quantity_in_kgs']," |")
print("----------------------------------------")
else:
print("| ",items[item_id]['item_name'], " | ",items[item_id]
['Quantity_in_kgs']," |")
#Add New Item to Database
def add_new_item():
item_ids = list(items.keys())
item_id = max(item_ids) + 1
item_name = input("Enter Item Name:")
price = int(input("Enter Price Per Kilo Gram:"))
quantiy = int(input("Enter Quantity"))
item =
{'item_name':item_name,'Quantity_in_kgs':quantiy,'Price_per_kg':price}
items[item_id]= item
print('Item Added')
print('Item id | Item Name | Quantity | Price ')
print(item_id, " | ", item_name, " | ", quantiy, " | ", price)
#Update the Quantity of Existing Item
def update_item(item_id):
quantiy = int(input("Enter Quantity"))
items[item_id]['Quantity_in_kgs'] = items[item_id]['Quantity_in_kgs'] +
quantiy
print('Item Updated')
print('Item id | Item Name | Quantity | Price ')
print(item_id, " | ", items[item_id]['item_name'], " | ", items[item_id]
['Quantity_in_kgs'], " | ", items[item_id]['Price_per_kg'] )
#Stock Entry
def add_item():
item_name = input("Enter the Item Name")
print("item id | item name")
print("-----------------")
for item in items:
if item_name in items[item]['item_name']:
print(item, " | ", items[item]['item_name'])

item_id = int(input("Enter item id (if existing)/Enter 0 (if New)"))


if item_id == 0:
add_new_item()
else:
#Check for Valid Item ID
while not item_id in items:
print("Not Valid Item id")
item_id = int(input("Enter item id:"))
update_item(item_id)
#Billing
def sale(trans_id):
total = 0
transaction_items = {}
while True:
item_id = int(input("Enter item id (0 if no item):"))
if item_id == 0:
break
else:
while not item_id in items:
print("Not Valid Item id")
item_id = int(input("Enter item id:"))
quantity = int(input("Enter Quantity:"))
amount = items[item_id]['Price_per_kg'] * quantity
items[item_id]['Quantity_in_kgs'] = items[item_id]
['Quantity_in_kgs'] - quantity
total += amount
transaction_items[item_id] = [quantity,amount]
print('Item id | Item Name | Quantity | Price | Amount')
for item in transaction_items:
print(item, "| ", items[item]['item_name'], " |
",transaction_items[item][0], " | ", items[item]['Price_per_kg'], " | ",
transaction_items[item][1])
print("---------------------------------------------------")
print("Total:\t\t\t ", total)
trans[trans_id] = transaction_items
#Main Function
while True:
print("Billing System\n Enter Your Choice \n 1. Add Items \n 2. Sales \n
3. Check Stock \n 4. Exit ")
choice = int(input("Your Choice:"))
if choice == 1:
add_item()
elif choice == 2:
trans_ids = list(trans.keys())
if len(trans_ids) == 0:
trans_id = 201
else:
trans_id = max(trans_ids) + 1
sale(trans_id)
elif choice == 3:
stock_check()
elif choice == 4:
break
else:
print("Invalid Choice")

Program Explanation
add_item() method checks whether the item is existing item or new item to the fruit shop.
if item is new then it calls add_new_item() method else it call update_item() method.
sale() method gets detail of each item and fetch price from dictionary to calculate amount.
amount will be added to the total. Sale() method finally decrease the sold quantity in item
dictionary.
stock_check() method prints all items and its available quantity.

You might also like