0% found this document useful (0 votes)
17 views59 pages

Exchange Values, Factorial

The document covers fundamental algorithms and Python control flow, including value exchange, counting, summation, factorial computation, Fibonacci sequence, and base conversions. It provides algorithms and Python code examples for various operations such as exchanging values of variables, counting digits in a number, calculating factorials, and converting between number bases. Additionally, it explains the Fibonacci sequence and includes methods for generating and reversing it.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views59 pages

Exchange Values, Factorial

The document covers fundamental algorithms and Python control flow, including value exchange, counting, summation, factorial computation, Fibonacci sequence, and base conversions. It provides algorithms and Python code examples for various operations such as exchanging values of variables, counting digits in a number, calculating factorials, and converting between number bases. Additionally, it explains the Fibonacci sequence and includes methods for generating and reversing it.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Unit-3

Contents

Fundamental Algorithms:
Introduction
 Exchange the values
 Counting
 Summation
 Factorial Computation
 Fibonacci Sequence
 Reverse
 Base Conversion
 Character to Number Conversion
Python Control Flow,
Functions :

Conditionals: Boolean values and
operators,
 conditional (if, if- else, if-elif-else)
 Iteration statements (state, while, for
break, ontinue, pass)
What is the Algorithm for
exchanging values of two variables?
 Algorithm:
 Step 1: Start
 Step 2: Read the value of Number1, Number2
 Step 3: Number1= Number1 + Number2
 Step 4: Number2= Number1 - Number2
 Step 5: Number1= Number1 - Number2
 Step 6: PRINT the value of Number1 and Number2
 Step 7: Stop
Q. Write a program for exchanging
values of two variables in python
 Source Code: Without Using
Temporary Variable
x =5
y = 10
 x, y = y, x
 print(“value of x: =", x)
 print(“value of y: =", y)
Output
2. Addition and Subtraction code to exchange the value
of variable

X=10
Y=50
x =x+y
y =x-y
x =x–y
 print("Value of x:", x)
 print("Value of y:", y)
Output
3. Multiplication and Division
code to exchange the value of
variable
X=10
Y=50
x = x * y
y = x / y
x = x / y
 print("Value of x : ", x)
 print("Value of y : ", y)
Output
4.XOR swap the value of
variables
 This algorithm works for integers only.
 X=2
 Y=3
 x = x ^ y # 2 ^3 =1
 y = x ^ y # 2^ 3 = 2
 x=x^y# 3
 print("Value of x : ", x)
 print("Value of y : ", y)
Output
Write an algorithm to exchange of
two numbers using third variable
 Step 1: Start
 Step 2: READ num1, num2
 Step 3: temp = num1
 Step 4: num1 = num2
 Step 5: num2 = temp
 Step 6: PRINT num1, num2
 Step 7: Stop
Write a program to exchange of two
numbers using third variable in
python
X= int(input( “ enter the first no”))
 Y=int(input(“enter the second no”))
 Temp=x
 X=y
 y= temp
 Print(“the value of x:”,x)
 Print(“the value of y:”,y)
Output
Write an algorithm to count the
digits in a given number.
 Step 1: Start
 Step 2: READ number
 Step3: Initialize the count 0
 Step 4: repeat step 5 untill number become 0 other wise goto step 7
 Step 5: divide number with 10
 Step 6: count<-count+1
 Step 7: write count
 Step 8: Stop
Q. write a program to count the
digits in a given number in python
 n=int(input("Enter number:")) #n =12546 five
 count=0
 while(n>0): # 12546>0
 count=count+1 #cont =1 2 3 4 5
 n=n//10 # 12546//10 = 1254//10=125 , 125//10= 12 12/10
1//10 0
 print("The number of digits in the number are:",count)
Output
write a program to count the digits in a given
number in python by using inbuilt function

num= 123456
Print(len(str(num)))
Output
Write a program in python to find
the sum of digits of a number.
1234
 rem = 123%10 # 4
Sum = sum+rem # 0+4= 4
Return= n//10 # 123
1234
Sum()

 products_purchased = [5.40, 2.20, 9.95, 1.50, 1.50, 2.20, 4.65, 3.00,


2.00]

total_price = sum(products_purchased)
 print(total_price)
Using Far loop

 n = input("Enter Number to calculate sum")


 n = int (n)
 sum = 0
 for num in range(0, n+1, 1):
 sum = sum+num
 print("SUM of first ", n, "numbers is: ", sum )
Python program to find the sum of
natural using recursive function
 def recur_sum(n):
 if n <= 1:
 return n
 else:
 return n + recur_sum(n-1)
 # change this value for a different result
 num = 16
 if num < 0:
 print("Enter a positive number")
 else:
 print("The sum is",recur_sum(num))
What is factorial computation?

 In simple words, if you want to find a factorial of an


positive integer, keep multiplying it with all the
positive integers less then that number.
 The final result that you get is the Factorial of that
number.
 So if you want to find the factorial of 7, multiply 7
with all positive integers less than 7.
 Those numbers would be 6,5,4,3,2,1. Multiply all
these numbers by 7 and the final result is the
factorial of 7.
Formula of Factorial

Factorial of a number is
denoted by n!, is the product
of all positive integers less
than or equal to n:
n! = n*(n-1)*(n-2)*…..3*2*1
Example

10 Factorial:-
So what is 10!? Multiply 10
with all the positive integers
which are less than 10.
10!
=10*9*8*7*6*5*4*3*2*1=3628
800
# Python program to find the
factorial of a number provided by
the


user.
num = 7 # To take input from the user #
num = int(input("Enter a number: "))
 factorial = 1 # check if the number is negative, positive or zero
 if num < 0:
 print("Sorry, factorial does not exist for negative numbers")
 elif num == 0:
 print("The factorial of 0 is 1")
 else:
 for i in range(1,num + 1):
 factorial = factorial*i
 print("The factorial of",num,"is",factorial)
Fibonacci sequence

 A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....


The first two terms are 0 and 1.
 All other terms are obtained by adding the preceding two terms. This
means to say the nth term is the sum of (n-1)th and (n-2)th term.
In mathematical terms

 Inmathematical terms, the sequence "Fn" of


the Fibonacci sequence of numbers is
defined by the recurrence relation:
 Fn= Fn_1+ Fn_2
 Where seed values are:
 F0=0 and F1=1
Fibonacci sequence:
Method: 1 - By using a while loop

 We will use a while loop for printing the sequence of the Fibonacci
sequence.
 Step 1: Input the number of values we want to generate the
Fibonacci sequence
 Step 2: Initialize the count = 0, n_1 = 0 and n_2 = 1.
 Step 3: If the n_terms <= 0
 Step 4: print "error" as it is not a valid number for series
 Step 5: if n_terms = 1, it will print n_1 value.
 Step 6: while count < n_terms
 Step 7: print (n_1)
 Step 8: nth = n_1 + n_2
 n_terms = int(input ("How many terms the user wants to print? "))
 # First two terms
 n_1 = 0
 n_2 = 1
 count = 0
 # Now, we will check if the number of terms is valid or not
 if n_terms <= 0:
 print ("Please enter a positive integer, the given number is not valid")
 # if there is only one term, it will return n_1
 elif n_terms == 1:
 print ("The Fibonacci sequence of the numbers up to", n_terms, ": ")
 print(n_1)
 # Then we will generate Fibonacci sequence of number
 else:
 print ("The fibonacci sequence of the numbers is:")
 while count < n_terms:
 print(n_1)
 nth = n_1 + n_2
 # At last, we will update values
 n_1 = n_2
 n_2 = nth
Fibonacci sequence
Method: 1 - By using a Far loop

 n= int(input("enter the number"))


 a=0
 print("Fibonacci sequence:",a)
 b=1
 print("Fibonacci sequence:",b)
 for i in range(0,n+1):
 c=a+b
 a=b
 b=c
 print("Fibonacci sequence:",c)
Reverse
 How to Reverse a String in Python
 txt = ( "Hello World“)[)::-1]
print(txt)

 for i in range(10, 0, -2):


 print(i)
Print reverse order of Fibonacci
sequence:-
 def reverseFibonacci(n):
 a = [0] * n
 # assigning first and second elements
 a[0] = 0
 a[1] = 1
 for i in range(2, n):
 # storing sum in the preceding location
 a[i] = a[i - 2] + a[i - 1]
 for i in range(n - 1, -1 , -1):
 # printing array in reverse order
 print(a[i],end=" ")
 # Driver function
 n=7
 reverseFibonacci(n)
Base Conversion
# Decimal to binary conversion:-
Binary to Decimal Conversion in Python

 We have already seen that the Binary System is a combination


of [0 or 1] with each digit being worth two times more than the
last digit, so let’s see how this information will help us to
convert binary to decimal equivalent.
Consider a Binary Number 01011

Digit 0 1 0 1 1

Weight 2^4=16 2^3=8 2^2=4 2^1=2 2^0=1


 Hence,
 (01011)2 =
(0*2^4)+(1*2^3)+(0*2^2)+(1*2^1)+(1*2^0)
 = 0+8+0+2+1=11
 Binary (base-2) is equivalent to decimal(base-10)
 (01011)2= 11
Base Decimal to Binary

 def decimalToBinary(num):
 if num > 0:
 decimalToBinary(num // 2)
 print(num % 2, end = “ ”)
 number = int(input("Enter the decimal number: "))
 #main()
 function decimalToBinary(number)
Using bin() function to form decimal
to binary
 number = int(input("Enter the decimal number: "))
 print(bin(number))
 Output
 Enter the decimal number: 56
 0b111000
Write a program to print binary to
decimal number?
 # Taking binary input
 binary = input("Enter a binary number:")
 def BinaryToDecimal(binary):
 decimal = 0
 for digit in binary:
 decimal = decimal*2 + int(digit)
 print("The decimal value is:", decimal)
 # Calling the function
 BinaryToDecimal(binary)
Decimal to octa conversion
Decimal to octa conversion

 def dectoOct(decimal):
 if(decimal > 0):
 dectoOct((int)(decimal/8))
 print(decimal%8, end='')

 decimal = int(input("Enter a decimal number: "))


 print("Octal: ", end='' )
 dectoOct(decimal)
Octa to decimal conversion:-
Q . Write a program to perform octa
to decimal
 # Python program to convert octal to decimal

 def OctalDecimal(num): #user-defined function


 decimal = 0
 base = 1 #Initializing base value to 1, i.e 8^0

 while (num):
 # Extracting last digit
 last_digit = num % 10
 num = int(num / 10)

 decimal += last_digit * base


 base = base * 8

 return decimal

 # take inputs
 num = int(input('Enter an octal number: '))

 # calling function and display result


Decimal to hexadecimal
Write a program to convert decimal
to hexadecimal
 conversion_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C', 'D', 'E', 'F']

 decimal = int(input("Enter a number: "))


 hexadecimal = ''

 while(decimal>0):
 remainder = decimal%16
 hexadecimal = conversion_table[remainder]+ hexadecimal
 decimal = decimal//16

 print("Hexadecimal: ",hexadecimal)
Output

Entera number: 67
Hexadecimal: 43
Hexa decimal to decimal conversion
Write a program to convert
hexadecimal to decimal
 # hexadecimal string
 hex = '0F'

 # conversion
 dec = int(hex, 16)

 print('Value in hexadecimal:', hex)


 print('Value in decimal:', dec)
OUTPUT

Value in hexadecimal: 0F
Value in decimal: 15
Python Program to Convert Decimal to
Binary, Octal and Hexadecimal

 dec = 344

 print("The decimal value of", dec, "is:")


 print(bin(dec), "in binary.")
 print(oct(dec), "in octal.")
 print(hex(dec), "in hexadecimal.")
Output

The decimal value of 344 is:


0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.
Ascii value:-
Character to number conversion

text
= "a"
number = ord(text)

print(number)
Output
97
Number to character conversion

 number = 97
 ascii = chr(number)

 print(ascii)
 Output
 a

You might also like