Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Python Programs-1

Uploaded by

BTCST
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Python Programs-1

Uploaded by

BTCST
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

How to compute the factorial of a number in Python

def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact

def factorial(n):
if n == 1: #base case
return n
else:
return n*factorial(n-1) # recursive case

number = 4
if number < 0:
print("Factorial exists for positive numbers only")
elif number == 0:
print("Factorial of 0 : 1")
else:
print("Factorial of",number,":",factorial(number))

Python Program for Sum the digits of a given number


def getSum(n):

sum = 0
for digit in str(n):
sum += int(digit)
return sum

n = 12345
print(getSum(n))

Python Program to print all Possible Combinations from the three


Digits
def comb(L):

for i in range(3):
for j in range(3):
for k in range(3):

# check if the indexes are not


# same
if (i!=j and j!=k and i!=k):
print(L[i], L[j], L[k])

# Driver Code
comb([1, 2, 3])
Python Program for Efficient program to print all prime factors of a
given number
def primeFactors(n):

# Print the number of two\'s that divide n


while n % 2 == 0:
print 2,
n = n / 2

# n must be odd at this point


# so a skip of 2 ( i = i + 2) can be used
for i in range(3,int(math.sqrt(n))+1,2):

# while i divides n , print i ad divide n


while n % i== 0:
print i,
n = n / i

# Condition if n is a prime
# number greater than 2
if n > 2:
print n
n = 315
primeFactors(n)
Python program to calculate the number of digits and letters in a
string
all_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

# define all letters


all_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z']

# given string
string = "geeks2for3geeks"

# intialized value
total_digits = 0
total_letters = 0

# iterate through all characters


for s in string:

# if character found in all_digits then increment total_digits by one


if s in all_digits:
total_digits += 1

# if character found in all_letters then increment total_letters by one


elif s in all_letters:
total_letters += 1

print("Total letters found :-", total_letters)


print("Total digits found :-", total_digits)

ANOTHER APPROACH:

string = "python1234"

# intialized value
total_digits = 0
total_letters = 0

# iterate through all characters


for s in string:

# if character is digit (return True)


if s.isnumeric():
total_digits += 1

# if character is letter (return False)


else:
total_letters += 1

print("Total letters found :-", total_letters)


print("Total digits found :-", total_digits)

Python program to sort digits of a number in ascending order


def getSortedNumber(n):

# Convert to equivalent string


number = str(n)

# Sort the string


number = ''.join(sorted(number))

# Convert to equivalent integer


number = int(number)

# Return the integer


return number

# Driver Code
n = 193202042

print(getSortedNumber(n))

Input, print and numbers


a = input()
b = input()
s=a+b
print(s)

val = input("Enter your value: ")


print(val)

num = input ("Enter number :")


print(num)
name1 = input("Enter name : ")
print(name1)

How to find the length of a string in Python


counter = 0
for c in "educative": # traverse the string “educative”
counter+=1 #increment the counter
print (counter) # outputs the length (9) of the string “educative”
str = "geeks"
print(len(str))

def findLen(str):
counter = 0
while str[counter:]:
counter += 1
return counter

str = "geeks"
print(findLen(str))

# Program to check if a number is prime or not

num = 29

# To take input from the user


#num = int(input("Enter a number: "))

# define a flag variable


flag = False

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

# Python program to check if the number is an Armstrong number or not

# take input from the user


num = int(input("Enter a number: "))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

# Python program to display all the prime numbers within an interval

lower = 900
upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

# Python program to find H.C.F of two numbers

# define a function
def compute_hcf(x, y):

# choose the smaller number


if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

num1 = 54
num2 = 24

print("The H.C.F. is", compute_hcf(num1, num2))

Occurrence of a Character in
String
count = 0

my_string = "Programiz"
my_char = "r"

for i in my_string:
if i == my_char:
count += 1

print(count)

Python Program to Create a


Countdown Timer
import time

def countdown(time_sec):
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
time_sec -= 1

print("stop")

countdown(5)
Python Program to Check If Two
Strings are Anagram
str1 = "Race"
str2 = "Care"

# convert both the strings into lowercase


str1 = str1.lower()
str2 = str2.lower()

# check if length is same


if(len(str1) == len(str2)):

# sort the strings


sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)

# if sorted char arrays are same


if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")

else:
print(str1 + " and " + str2 + " are not anagram.")

Python Program to Compute the


Power of a Number
base = 3
exponent = 4

result = 1

while exponent != 0:
result *= base
exponent-=1

print("Answer = " + str(result))


Python Program to Reverse a
Number
num = 1234
reversed_num = 0

while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10

print("Reversed Number: " + str(reversed_num))

*
* *
* * *
* * * *
* * * * *

rows = int(input("Enter number of rows: "))

for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")

# Program to count the number of each vowels

# string of vowels
vowels = 'aeiou'

ip_str = 'Hello, have you tried our tutorial section yet?'

# make it suitable for caseless comparisions


ip_str = ip_str.casefold()

# make a dictionary with each vowel a key and value 0


count = {}.fromkeys(vowels,0)

# count the vowels


for char in ip_str:
if char in count:
count[char] += 1

print(count)
# Program to sort alphabetically the words form a string provided by
the user

my_str = "Hello this Is an Example With cased letters"

# To take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = [word.lower() for word in my_str.split()]

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

# Program to check if a string is palindrome or not

my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

# Program to add two matrices using nested loop

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

# Python3 program to find maximum


# in arr[] of size n

# python function to find maximum


# in arr[] of size n
def largest(arr,n):

# Initialize maximum element


max = arr[0]

# Traverse array elements from second


# and compare every element with
# current max
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max

# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr,n)
print ("Largest in given array is",Ans)

# Python 3 code to find sum


# of elements in given array
def _sum(arr):

# initialize a variable
# to store the sum
# while iterating through
# the array later
sum=0

# iterate through the array


# and add each element to the sum variable
# one at a time
for i in arr:
sum = sum + i

return(sum)

# driver function
arr=[]
# input values to list
arr = [12, 3, 4, 15]

# calculating length of array


n = len(arr)

ans = _sum(arr)

# display sum
print ('Sum of the array is ', ans)

# This code is contributed by Himanshu Ranjan

# Function to reverse words of string

def rev_sentence(sentence):

# first split the string into words


words = sentence.split(' ')

# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))

# finally return the joined string


return reverse_sentence

if __name__ == "__main__":
input = 'geeks quiz practice code'
print (rev_sentence(input))

You might also like