sfx2000
Part of the Furniture
Fun Stuff... leet code exercises perhaps...
Here's another...
Here's an easy one...
A bit more interesting...
Code:
# Problem - take a two digit integer and return the sum of the two digits
# For example int == 29, so we extract the two digits and sum them up as
# there are better ways to do this, either thru iteration or recursion, but
# let's keep the scope narrow to the problem at hand
def sum_digits():
num = int(input("Enter a two-digit integer: "));
digit1 = num // 10 # Extract the first digit
digit2 = num % 10 # Extract the second digit
sum = digit1 + digit2; # Calculate the sum
print("The sum of the digits is:", sum)
sum_digits()
Here's another...
Code:
# Problem - determine if parens are balanced using a boolean function
# Example - ()()(())
# Return true or false
def balance_func():
def are_brackets_balanced(str):
count = 0
for char in str:
if char == '(':
count += 1
elif char == ')':
count -= 1
if count < 0:
return False
return count == 0
str = "((()))"
if are_brackets_balanced(str):
print("Brackets are balanced")
else:
print("Brackets are not balanced")
balance_func()
Here's an easy one...
Code:
# Write a function to count the number of set bits (1s) in an integer.
def count_set_bits(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
A bit more interesting...
Code:
# Given a sorted array, create a new array containing squares of
# all the numbers of the input array in the sorted order.
def square_sorted_array(arr):
n = len(arr)
result = [0] * n
left = 0
right = n - 1
index = n - 1
while left <= right:
if abs(arr[left]) > abs(arr[right]):
result[index] = arr[left] * arr[left]
left += 1
else:
result[index] = arr[right] * arr[right]
right -= 1
index -= 1
return result
Last edited: