Skip to main content

read file contents into a list

0 likes • Jun 1, 2023 • 0 views
Python
Loading...

More Python Posts

Python Fibonacci

CHS
0 likes • Sep 6, 2020 • 0 views
Python
def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==1:
return 0
# Second Fibonacci number is 1
elif n==2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
# Driver Program
print(Fibonacci(9))

Check Armstrong Number

0 likes • May 31, 2023 • 0 views
Python
# Function to check Armstrong number
def is_armstrong_number(number):
# Convert number to string to iterate over its digits
num_str = str(number)
# Calculate the sum of the cubes of each digit
digit_sum = sum(int(digit) ** len(num_str) for digit in num_str)
# Compare the sum with the original number
if digit_sum == number:
return True
else:
return False
# Prompt user for a number
number = int(input("Enter a number: "))
# Check if the number is an Armstrong number
if is_armstrong_number(number):
print(number, "is an Armstrong number.")
else:
print(number, "is not an Armstrong number.")

clamp number

0 likes • Nov 19, 2022 • 0 views
Python
def clamp_number(num, a, b):
return max(min(num, max(a, b)), min(a, b))
clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1

combine values

0 likes • Nov 19, 2022 • 0 views
Python
from collections import defaultdict
def combine_values(*dicts):
res = defaultdict(list)
for d in dicts:
for key in d:
res[key].append(d[key])
return dict(res)
d1 = {'a': 1, 'b': 'foo', 'c': 400}
d2 = {'a': 3, 'b': 200, 'd': 400}
combine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]}

return byte size

0 likes • Nov 19, 2022 • 1 view
Python
def byte_size(s):
return len(s.encode('utf-8'))
byte_size('😀') # 4
byte_size('Hello World') # 11

radians to degrees

0 likes • Nov 19, 2022 • 0 views
Python
from math import pi
def rads_to_degrees(rad):
return (rad * 180.0) / pi
rads_to_degrees(pi / 2) # 90.0