basic code
- Get link
- X
- Other Apps
# factorial of given number
def
factorial(n):
# single line to find factorial
return
1
if
(n
=
=
1
or
n
=
=
0
)
else
n
*
factorial(n
-
1
)
# Driver Code
num
=
5
print
(
"Factorial of"
,num,
"is"
,factorial(num))
----------------------
Find Largest Element in list
In this program, we have an array called array with some elements. We use the max function to find the largest element in the array. The key parameter is set to a lambda function lambda x: x, which simply returns the element itself. This lambda function is used to determine the comparison key for the max function.
Python3
array
=
[
10
,
5
,
20
,
8
,
15
]
largest_element
=
max
(array, key
=
lambda
x: x)
print
(
"Largest element in the array:"
, largest_element)
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 "
, Ans)
----------------
# function which return reverse of a string
def
isPalindrome(s):
return
s
=
=
s[::
-
1
]
# Driver code
s
=
"malayalam"
ans
=
isPalindrome(s)
if
ans:
print
(
"Yes"
)
else
:
print
(
"No"
)
-------------------
# Python3 program to swap first
# and last element of a list
# Swap function
def
swapList(newList):
size
=
len
(newList)
# Swapping
temp
=
newList[
0
]
newList[
0
]
=
newList[size
-
1
]
newList[size
-
1
]
=
temp
return
newList
# Driver code
newList
=
[
12
,
35
,
9
,
56
,
24
]
print
(swapList(newList))
----------------
Python Program to Check Armstrong Number
Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Example:
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
def
is_armstrong_number(number):
return
sum
(
int
(digit)
*
*
len
(
str
(number))
for
digit
in
str
(number))
=
=
number
# Example usage:
num
=
153
if
is_armstrong_number(num):
print
(f
"{num} is an Armstrong number"
)
else
:
print
(f
"{num} is not an Armstrong number"
)
- Get link
- X
- Other Apps
Comments
Post a Comment