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

python-5

The document contains a collection of Python functions that perform various tasks such as checking for Armstrong numbers, rotating arrays, counting characters in strings, removing duplicates, and more. Each function is accompanied by example usage, demonstrating its functionality. The document serves as a programming reference for common algorithms and operations in Python.

Uploaded by

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

python-5

The document contains a collection of Python functions that perform various tasks such as checking for Armstrong numbers, rotating arrays, counting characters in strings, removing duplicates, and more. Each function is accompanied by example usage, demonstrating its functionality. The document serves as a programming reference for common algorithms and operations in Python.

Uploaded by

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

1.

Armstrong Number

def is_armstrong(n):

num_str = str(n)

num_digits = len(num_str)

total = 0

for digit in num_str:

total += int(digit) ** num_digits

return total == n

# Example usage:

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

if is_armstrong(num):

print(f"{num} is an Armstrong number.")

else:

print(f"{num} is not an Armstrong number.")

2. Array rota on

def le _rotate(arr, k):

k %= len(arr) # Handle cases where k > len(arr)

return arr[k:] + arr[:k]

# Example usage:

arr = [1, 2, 3, 4, 5]

k=2

print(f"Original array: {arr}")

print(f"Le rotated by {k}: {le _rotate(arr, k)}")


3. Count Alphabet

def analyze_string(input_string):

# Remove spaces from the input string

modified_string = input_string.replace(" ", "")

# Calculate the length of the modified string

length_of_string = len(modified_string)

# Create a dic onary to count occurrences of each character

char_count = {}

for char in modified_string:

if char in char_count:

char_count[char] += 1

else:

char_count[char] = 1

# Print the results

print(f"Length of the string (excluding spaces): {length_of_string}")

print("Character occurrences (excluding spaces):")

for char, count in char_count.items():

print(f"'{char}': {count}")

# Example usage:

input_string = input("Enter a string: ")

analyze_string(input_string)

4. DELETE removing second occurrence


def delete_second_occurance(lst):

occurance = { }

i=0

while i < len(lst):

item = lst[i]

if item in occurance:

occurance[item] += 1

else:

occurance[item] = 1

if occurance[item] = 2:

lst.pop(i)

else:

i += 1

return lst

# Example usage:

l = [3, 1, 6, 2, 7, 2, 5, 4, 9, 16, 14, 2]

result = delete_second_occurrence(l)

print("List a er removing second occurrence:", result)

5. Fla en List

def fla en_list(nested_list):

fla ened= [ ]

for item in nested_list:


if isinstance(item, list):

fla ened.extend(fla en_list(item))

else:

fla ened.append(item)

return fla ened

# Example usage:

nested_list = [1, [2, [3, 4], 5], [6, 7], 8]

print(fla en_list(nested_list))

6. Interchange first and Last element in array

def interchange_first_last(arr):

if len(arr) > 1:

arr[0], arr[-1] = arr[-1], arr[0]

return arr

# Example usage:

arr = [1, 2, 3, 4, 5]

print(f"Original array: {arr}")

print(f"Array a er swapping: {interchange_first_last(arr)}")

7. Intersect_without_built_in

def intersec on(list1, list2):

intersect = [ ]

for i in list1:
if item in list2 and item not in intersect:

intersect.append(item)

return intersect

# Example usage:

list1 = [1, 2, 3, 4, 5]

list2 = [3, 4, 5, 6, 7]

print(intersec on(list1, list2))

# Output: [3, 4, 5]

8. Manual Duplicate Removal

def remove_duplicates(lst):

# Create an empty list to store unique elements

unique_list = []

# Iterate through each item in the original list

for item in lst:

# Check if the item is not already in the unique_list

if item not in unique_list:

unique_list.append(item) # Add the item to the unique_list if it's not a duplicate

return unique_list

# Example usage:

l = [3, 1, 6, 2, 7, 5, 4, 9, 16, 14, 2, 6, 7]

unique_list = remove_duplicates(l)

print("List a er removing duplicates:", unique_list)


9. Palindrome

def is_palindrome(string):

# Convert the string to lowercase to make it case-insensi ve

string = string.lower()

# Reverse the string and compare it with the original string

if string == string[::-1]:

return True

else:

return False

# Example usage:

input_string = "Madam"

if is_palindrome(input_string):

print(f'"{input_string}" is a palindrome.')

else:

print(f'"{input_string}" is not a palindrome.')

10. Print '_' Using User input Data

def print_right_angle_triangle():

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

for i in range(1, n + 1):

for j in range(i):

print('* ', end='')

print()
# Example usage:

print_right_angle_triangle()

11. Prin ng Stars '_' in Diamond Shape

def print_diamond(n):

# Top half of the diamond (including the middle row)

for i in range(1, n + 1):

# Print spaces

for j in range(n - i):

print(' ', end='')

# Print stars

for k in range(2 * i - 1):

print('*', end='')

# Move to the next line

print()

# Bo om half of the diamond

for i in range(n - 1, 0, -1):

# Print spaces

for j in range(n - i):

print(' ', end='')

# Print stars

for k in range(2 * i - 1):

print('*', end='')

# Move to the next line

print()
# Get user input

n = int(input("Enter the number of rows for the top half of the diamond: "))

# Call the func on with the user's input

print_diamond(n)

12. Prin ng Stars '_' in Reverse Pyramid Shape

n=5

# Loop for each row

for i in range(n, 0, -1):

# Print spaces for alignment

print(' ' * (n - i), end='')

# Print stars

print('* ' * i)

13. Fibanacci

def fibonacci_recursive(n):

if n <= 1:

return n

return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)

# Example usage:

print([fibonacci_recursive(i) for i in range(10)])


14. dic onary duplicate values append

def group_by_value(dic onary):

result = { }

for key, value in dic onary.items():

if value in result:

result[value].append(key)

else:

result[value] = [key]

return result

# Example

my_dict = {'a': 10, 'b': 20, 'c': 10, 'd': 30, 'e': 20}

print(group_by_value(my_dict))

# Output: {10: ['a', 'c'], 20: ['b', 'e'], 30: ['d']}

15. find all sum of dic onary items

def sum_dict_values(dic onary):

total = 0

for value in dic onary.values():

total += value

return total

# Example

my_dict = {'a': 10, 'b': 20, 'c': 30}

print(sum_dict_values(my_dict)) # Output: 60
16. find largest value in Array

arr = [3, 1, 4, 1, 5, 9, 2]

largest = arr[0]

for num in arr:

if num > largest:

largest = num

print(f"The largest value in the array is: {largest}")

17. fla en_list

def fla en_list(input_list):

flat_list = []

for item in input_list:

if isinstance(item, list):

flat_list.extend(fla en_list(item))

else:

flat_list.append(item)

return flat_list

# Example usage:

input_list = [1, 2, [3, 4, 5, 6], 9, 10, 11, 0, [23, 45, 78], [100, 90]]

fla ened = fla en_list(input_list)

print(fla ened)

18. missing numbers

def find_missing_numbers(lst):
# Find the minimum and maximum values in the list

min_val = min(lst)

max_val = max(lst)

# Create a set of all numbers in the range from min_val to max_val

full_set = set(range(min_val, max_val + 1))

# Create a set from the list

list_set = set(lst)

# Find the missing numbers by subtrac ng list_set from full_set

missing_numbers = full_set - list_set

return sorted(missing_numbers)

# Example usage:

l = [3, 1, 6, 2, 7, 5, 4, 9, 16, 14]

missing_numbers = find_missing_numbers(l)

print("The missing numbers are:", missing_numbers)

19. move_zeros_to_end

def move_zeros_to_end(input_list):

non_zero_list = [] # List to store non-zero elements

zero_count = 0 # Counter for zeros

# Iterate through the input list

for i in input_list:
if i != 0:

non_zero_list.append(i) # Append non-zero elements

else:

zero_count += 1 # Count zeros

# Append the zeros at the end

for j in range(zero_count):

non_zero_list.append(0)

return non_zero_list

# Example usage:

input_list = [0, 5, 9, 0, 20, 12, 0]

reordered_list = move_zeros_to_end(input_list)

print(reordered_list)

20. prime number

def is_prime_basic(n):

if n <= 1:

return False

for i in range(2, n):

if n % i == 0:

return False

return True

# Example usage:

print(is_prime_basic(29)) # True
print(is_prime_basic(30)) # False

21. remove all duplicates in strin

def remove_duplicates(string):

# Step 1: Count occurrences of each character

freq = {}

for char in string:

if char in freq:

freq[char] += 1

else:

freq[char] = 1

# Step 2: Keep only characters that appear once

result = ""

for char in string:

if freq[char] == 1:

result += char

return result

# Example

print(remove_duplicates("programming")) # Output: "progamin"

print(remove_duplicates("hello world")) # Output: "he wrd"

22. reverse words

def reverse_words(sentence):
return ' '.join(sentence.split()[::-1])

# Example

print(reverse_words("Hello World")) # Output: "World Hello"

23. sum of square first n natural numbers

def sum_of_squares_itera ve(n):

total = 0

for i in range(1, n + 1):

total += i**2

return total

# Example usage:

print(sum_of_squares_itera ve(5)) # Output: 55

24. swap two elements

def swap_elements(arr, index1, index2):

arr[index1], arr[index2] = arr[index2], arr[index1]

return arr

# Example usage:

arr = [1, 2, 3, 4, 5]

index1 = 1 # Second element

index2 = 3 # Fourth element

print(f"Original array: {arr}")

print(f"Array a er swapping: {swap_elements(arr, index1, index2)}")


25. words frequency in string

from collec ons import Counter

def word_frequency(string):

words = string.split()

return Counter(words)

# Example

print(word_frequency("hello world hello python world"))

# Output: Counter({'hello': 2, 'world': 2, 'python': 1})

26. word2number

def words_to_number(word):

word = word.lower()

num_dict = {

"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,

"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,

"hundred": 100, "thousand": 1_000, "million": 1_000_000

parts = word.split()

number = 0

temp = 0

for part in parts:

if part in num_dict:
if part == "hundred":

temp *= num_dict[part]

elif part == "thousand" or part == "million":

temp *= num_dict[part]

number += temp

temp = 0

else:

temp += num_dict[part]

return number + temp

input_text = "five hundred million"

output_number = words_to_number(input_text)

# Format the number with commas

forma ed_output = f"{output_number:,}"

print(forma ed_output)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy