Write a Python Program to Print all Pythagorean Triplets in the Range
limit=10
c=0
m=2
while(c<limit):
for n in range(1,m+1):
a=m*m-n*n
b=2*m*n
c=m*m+n*n
if(c>limit):
break
if(a==0 or b==0 or c==0):
break
print(a,b,c)
m=m+1
Write a Python Program to print the Number of Times a Particular Number Occurs in a List
a=[2, 3, 8, 9, 2, 4, 6]
k=0
num=int(input("Enter the number to be counted:"))
for j in a:
if(j==num):
k=k+1
print("Number of times",num,"appears is",k)
Write a Python Program to test and print Collatz Conjecture for a Given Number
def collatz(n):
while n > 1:
print(n, end=' ')
if (n % 2):
# n is odd
n = 3*n + 1
else:
# n is even
n = n//2
print(1, end='')
Write a Python function to Count Set Bits in a Number
def count_set_bits(n):
count = 0
while n:
n &= n - 1
count += 1
return count
Write a Python Program to Generate Gray Codes using Recursion
def get_gray_codes(n):
"""Return n-bit Gray code in a list."""
if n == 0:
return ['']
first_half = get_gray_codes(n - 1)
second_half = first_half.copy()
first_half = ['0' + code for code in first_half]
second_half = ['1' + code for code in reversed(second_half)]
return first_half + second_half
Write a Python Program to Convert Gray Code to Binary
def gray_to_binary(n):
"""Convert Gray codeword to binary and return it."""
n = int(n, 2)
mask = n
while mask != 0:
mask >>= 1
n ^= mask
return bin(n)[2:]
Write a Python Program to Convert Binary to Gray Code
def binary_to_gray(n):
"""Convert Binary to Gray codeword and return it."""
n = int(n, 2)
n ^= (n >> 1)
return bin(n)[2:]