Skip to content

Instantly share code, notes, and snippets.

@apalii
Last active September 8, 2023 07:52
Show Gist options
  • Save apalii/2a86f8fb8d4d3e4b0c27 to your computer and use it in GitHub Desktop.
Save apalii/2a86f8fb8d4d3e4b0c27 to your computer and use it in GitHub Desktop.
# _____________________________________________________
def roman_to_arabic(line):
roman_numerals = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
result = 0
prev_value = 0
for i in line[::-1]:
value = roman_numerals[i]
if value < prev_value:
result -= value
else:
result += value
prev_value = value
return result
assert roman_to_arabic("XXII") == 22
# Example usage
mp3_file_path = "path/to/your/mp3_file.mp3"
transcription = transcribe_mp3_to_text(mp3_file_path)
if transcription:
print("Transcription:")
print(transcription)
# Cleanup: Delete the temporary WAV file
wav_file_path = mp3_file_path.replace(".mp3", ".wav")
if os.path.exists(wav_file_path):
os.remove(wav_file_path)
# _____________________________________________________
def convert_string(num):
"""Convert string to integer without int()
"""
negative = num.startswith("-")
if negative:
num = num[1:]
result = 0
for c in num:
if not c.isdigit():
raise ValueError("Wrong format")
result = result * 10 + ord(c) - ord('0')
return result * -1 if negative else result
print(convert_string("-123"))
# _____________________________________________________
"""For each natural number in the interval from M to N, derive all divisors,
except one and a number itself.
"""
def posible_number(num):
res = []
for i in range(2, num):
if num % i == 0:
res.append(i)
return res
def divisors(m, n):
result = {}
m = int(m)
n = int(n)
for i in range(m, n+1):
result[i] = posible_number(i)
return result
# _____________________________________________________
def combination(target):
"""Write a program that finds all combinations of three numbers up to a certain limit,
which add up to a different number
Limit for numbers to be sorted: 5 (from 0 to 5)
Amount sought: 10
"""
result = []
numbers = [0,1,2,3,4,5]
for i in numbers:
for j in numbers:
for k in numbers:
if sum(i) == target:
result.append((i,j,k))
return result
# _____________________________________________________
def flatten_array_recursive(arr):
flattened = []
for item in arr:
if isinstance(item, list):
flattened.extend(flatten_array_recursive(item))
else:
flattened.append(item)
return flattened
result = flatten_array_recursive(nested_array)
print(result) # Вывод: [1, 2, 3, 4, 5, 6, 7]
# _____________________________________________________
def intervals(tolerance, timestamps):
intervals_list = []
start = timestamps[0]
end = timestamps[0]
for i in range(1, len(timestamps)):
if timestamps[i] - end <= tolerance:
end = timestamps[i]
else:
intervals_list.append((start, end))
start = timestamps[i]
end = timestamps[i]
intervals_list.append((start, end))
return intervals_list
tolerance = 5
timestamps = [1, 2, 3, 4, 10, 13, 16, 40, 100, 101, 102]
print(intervals(tolerance, timestamps))
# _____________________________________________________
def find_minimum(input_list):
min_value = input_list[0]
for i in range(1, len(input_list)):
if input_list[i] < min_value:
min_value = input_list[i]
return min_value
print(find_minimum([1,2,3,4,5,-999]))
# _____________________________________________________
def count_words(string):
"""Function to count the frequency of each word in a string"""
words = string.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
# palindrome check
def is_palindrome(string):
# re.sub("\W*|\s*", "", string.lower())
string = filter(lambda x: x.isalpha() or x.isdigit(), string.lower())
return string == string[::-1]
# my
from math import factorial as f
def pascal(p):
result = []
for n in range(p):
result.append([(f(n)/f(n-k)/f(k)) for k in range(0,n+1)])
return result
# Write a reverseWords function that accepts a string a parameter,
# and reverses each word in the string.
# Every space should stay, so you cannot use words from Prelude.
def reverse_words(str):
return ' '.join(s[::-1] for s in str.split(' '))
# -----------------------------------------------
# A simple substitution cipher replaces one character from an alphabet
# with a character from an alternate alphabet, where each character's position
# in an alphabet is mapped to the alternate alphabet for encoding or decoding.
"""
map1 = "abcdefghijklmnopqrstuvwxyz";
map2 = "etaoinshrdlucmfwypvbgkjqxz";
cipher = Cipher(map1, map2);
cipher.encode("abc") # => "eta"
cipher.encode("xyz") # => "qxz"
"""
class Cipher(object):
def __init__(self, map1, map2):
# number: char => nc
self.mapnc1 = dict(enumerate(map1))
self.mapnc2 = dict(enumerate(map2))
# char: number => cn
self.mapcn1 = dict(((y,x) for x,y in enumerate(map1)))
self.mapcn2 = dict(((y,x) for x,y in enumerate(map2)))
def encode(self, string):
code = [self.mapcn1[i] if i in self.mapcn1.keys() else i for i in string]
return "".join(self.mapnc2[i] if isinstance(i, int) else i for i in code)
def decode(self, string):
code = [self.mapcn2[i] if i in self.mapcn1.keys() else i for i in string]
return "".join(self.mapnc1[i] if isinstance(i, int) else i for i in code)
# -----------------------------------------------
class PaginationHelper(object):
# The constructor takes in an array of items and a integer indicating
# how many items fit within a single page
def __init__(self, collection, items_per_page):
self.collection = collection
self.items = len(collection)
self.items_per_page = items_per_page
self.rest = self.items - ( self.items_per_page * ( self.items / self.items_per_page ) )
# returns the number of items within the entire collection
def item_count(self):
return self.items
# returns the number of pages
def page_count(self):
if self.rest > 0:
return (self.items / self.items_per_page) + 1
elif self.rest == 0 and self.items < self.items_per_page:
return 1
return (self.items / self.items_per_page)
# returns the number of items on the current page. page_index is zero based
# this method should return -1 for page_index values that are out of range
def page_item_count(self, page_index):
page_index = page_index + 1
pages = self.page_count()
if page_index == pages:
return self.rest
elif page_index > pages:
return -1
elif page_index < pages:
return self.items_per_page
# determines what page an item is on. Zero based indexes.
# this method should return -1 for item_index values that are out of range
def page_index(self, item_index):
if item_index < 0 or item_index > self.items - 1:
return -1
elif item_index < self.items_per_page:
return 0
return item_index / self.items_per_page
# _____________________________________________________
Position = {'high': 'h','low': 'l'}
class Warrior():
def __init__(self, name):
#each warrior should be created with a name and 100 health points
self.name = name
self.health = 100
#default guard is "", that is unguarded
self.block = ""
def attack(self, enemy, position):
#attacking high deals 10 damage, low 5
#0 damage if the enemy blocks in the same position
damage = 0
if enemy.block != position:
damage += 10 if position == Position['high'] else 5
#and even more damage if the enemy is not blocking at all
print
if enemy.block=="":
damage+=5
enemy.set_health(enemy.health-damage)
def set_health(self, new_health):
#health cannot have negative values
self.health=min(0,new_health)
#if a warrior is set to 0 health he is dead
if self.health==0:
self.deceased=True
self.zombie=False
#he would be a zombie only if he was already dead
if self.deceased:
self.zombie=True
ninja = Warrior('Hanzo Hattori')
samurai = Warrior('Ryōma Sakamoto')
samurai.block = 'l'
ninja.attack(samurai, 'h')
# -----------------------------------------------
'''
test.assert_equals(format_duration(1), "1 second")
test.assert_equals(format_duration(62), "1 minute and 2 seconds")
test.assert_equals(format_duration(120), "2 minutes")
test.assert_equals(format_duration(3600), "1 hour")
test.assert_equals(format_duration(3662), "1 hour, 1 minute and 2 seconds")
'''
from collections import OrderedDict
def format_duration(seconds):
if seconds == 0:
return "now"
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
y, d = divmod(d, 365)
seconds = "{} second{}".format(s, 's' if s != 1 else '')
minutes = "{} minute{}".format(m, 's' if m != 1 else '')
hours = "{} hour{}".format(h, 's' if h != 1 else '')
days = "{} day{}".format(d, 's' if d != 1 else '')
years = "{} year{}".format(y, 's' if y != 1 else '')
strings = OrderedDict(zip(range(1,6), [years, days, hours, minutes, seconds]))
filtered = [strings[i] for i in filter(lambda x: strings[x][0] != "0", strings)]
if len(filtered) == 1:
return filtered[0]
elif len(filtered) == 2:
return "{} and {}".format(*filtered)
elif len(filtered) == 3:
return "{}, {} and {}".format(*filtered)
elif len(filtered) == 4:
return "{}, {}, {} and {}".format(*filtered)
elif len(filtered) == 5:
return "{}, {}, {}, {} and {}".format(*filtered)
# -----------------------------------------------
"""
Description:
Finish the solution so that it takes an input 'n' (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.
Assume: 0 <= n < 1000000000
10 -> "10"
100000 -> "100,000"
35235235 -> "35,235,235"
"""
def group_by_commas(n):
return format(n, ',d')
# -------------------------------------
"""
Write a function called validParentheses that takes a string of parentheses,
and determines if the order of the parentheses is valid. validParentheses should
return true if the string is valid, and false if it's invalid.
Examples:
validParentheses( "()" ) => returns true
validParentheses( ")(()))" ) => returns false
validParentheses( "(" ) => returns false
validParentheses( "(())((()())())" ) => returns true
"""
def valid_parentheses(string):
filtered = filter(lambda x: x in "()", string)
if filtered.startswith(")") or filtered.endswith("(") or \
filtered.count("(") != filtered.count(")"):
return False
else:
while len(filtered) > 1 and filtered != ")(":
filtered = filtered.replace("()", "")
return True if filtered == "" else False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment