Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions crossopt/assignment1/Q1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
# coding: utf-8
from re import split
from collections import Counter


# return hashable count of elements
def hashCount(container):
return tuple(sorted(Counter(container).items()))


# checks whether strings are anagrams
def isStringAnagram(str1, str2, case_sensitive=False):
if not case_sensitive:
str1 = str1.lower()
str2 = str2.lower()

return Counter(str1) == Counter(str2)


# checks whether sentences are anagrams. Punctuation is ignored
def isSentenceAnagram(str1, str2, case_sensitive=False):
if not case_sensitive:
str1 = str1.lower()
str2 = str2.lower()

# TODO - figure out apostrophes
# get list of words, replace all words with their count, make it hashable
words1 = [hashCount(word) for word in split('\W', str1) if word]
words2 = [hashCount(word) for word in split('\W', str2) if word]
return Counter(words1) == Counter(words2)


if __name__ == "__main__":
str1 = "triangle"
str2 = "Integral"
assert not isStringAnagram(str1, str2, 1)
assert isStringAnagram(str1, str2)

str1 = "посеять: клоповник"
str2 = "полковник опьется"
assert isSentenceAnagram(str1, str2, 1)
assert isSentenceAnagram(str1, str2, 0)
58 changes: 58 additions & 0 deletions crossopt/assignment1/Q2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env python3


class Node(object):
def __init__(self, data):
self.data = data
self.next = None


class LinkedList(object):
def __init__(self):
self.head = None

# adds element to front of list
def insert(self, new_elem):
new_node = Node(new_elem)
new_node.next = self.head
self.head = new_node

def __len__(self):
ans = 0
cnt = self.head
while cnt:
ans += 1
cnt = cnt.next
return ans

def __str__(self):
ans = []
cnt = self.head
while cnt:
ans.append(str(cnt.data))
cnt = cnt.next
return "{" + ", ".join(ans) + "}"

# list[-k] returns kth element from end of list, last element is -1
def __getitem__(self, k):
length = len(self)

if k >= 0:
raise NotImplementedError()
elif k < -length:
raise IndexError()

cnt = self.head
for i in range(length + k):
cnt = cnt.next
return cnt

if __name__ == "__main__":
list = LinkedList()
list.insert(5)
list.insert('dog')
list.insert(set([1, 2, 3]))
print("list is {}".format(list))
for k in range(1, 4):
print("for k = {}, kth from last element is {}"
.format(k, list[-k].data))