hw 1 and 2

This commit is contained in:
Isaac Shoebottom 2024-01-15 18:39:16 -04:00
parent 1fe00454fa
commit 91d8538cc9
3 changed files with 140 additions and 0 deletions

69
2024-1-12.py Normal file
View File

@ -0,0 +1,69 @@
from util import *
def p1():
# Language rule 1, n is less than or equal to 2
n = 2
# Language rule 2, m is less than or equal to n
m = n
strings = []
# Language rule 3, n and m are both non-negative integers
for i in range(0, n + 1):
for j in range(0, m + 1):
if j > i:
continue
strings.append('0' * j + '1' * i)
return strings
def p2():
possible_n = [2, 3, 4, 5, 6]
strings = []
for i in possible_n:
integer_divisors = []
for j in range(1, i + 1):
if i % j == 0:
integer_divisors.append(j)
for j in integer_divisors:
strings.append('a' * j + 'b' * i)
return strings
def p3():
possible_n = [1, 2, 3]
strings = []
for i in possible_n:
an = i
bn = 2 * i - 1
cn = 3 * i - 2
strings.append('a' * an + 'b' * bn + 'c' * cn)
return strings
def p4():
alphabet = ['a', 'b']
# include empty string
strings = get_all_strings_with_a_given_alphabet_and_length(alphabet, 3)
def is_palindrome(s):
return s == s[::-1]
strings = list(filter(is_palindrome, strings))
return strings
def main():
print_strings(p1())
print_strings(p2())
print_strings(p3())
print_strings(p4())
if __name__ == '__main__':
main()

58
2024-1-15.py Normal file
View File

@ -0,0 +1,58 @@
from util import *
def p1():
alphabet = ['a', 'b']
strings = get_all_strings_with_a_given_alphabet_and_length(alphabet, 3)
def number_of_a_is_even(s):
return s.count('a') % 2 == 0
strings = list(filter(number_of_a_is_even, strings))
return strings
def p2():
possible_m = [0, 1, 2, 3, 4]
possible_n = [0, 1, 2, 3, 4]
possible_p = [0, 1, 2, 3, 4]
strings = []
for m in possible_m:
for n in possible_n:
for p in possible_p:
# First rule
if m + n + p <= 4:
# Second rule
if m > n:
# Third rule
if n == p:
strings.append('a' * m + 'b' * n + 'c' * p)
return strings
def p3():
alphabet = ['a', 'b', 'c']
strings = get_all_strings_with_a_given_alphabet_and_length(alphabet, 4)
def number_of_a_is_greater_than_number_of_b(s):
return s.count('a') > s.count('b')
def number_of_b_is_equal_to_number_of_c(s):
return s.count('b') == s.count('c')
strings = list(filter(number_of_a_is_greater_than_number_of_b, strings))
strings = list(filter(number_of_b_is_equal_to_number_of_c, strings))
return strings
def main():
print_strings(p1())
print_strings(p2())
print_strings(p3())
if __name__ == '__main__':
main()

13
util.py Normal file
View File

@ -0,0 +1,13 @@
def get_all_strings_with_a_given_alphabet_and_length(alphabet, length):
strings = ['']
for i in range(length):
s = [s + c for s in strings for c in alphabet]
strings += s
# Remove duplicates (set() isn't as nice as it doesn't preserve order, at least for verification purposes)
strings = list(dict.fromkeys(strings))
return strings
def print_strings(strings):
print(strings, len(strings))