- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRemoveNthNodeFromEnd.py
More file actions
Latest commit
108 lines (88 loc) · 2.64 KB
/
Copy pathRemoveNthNodeFromEnd.py
File metadata and controls
108 lines (88 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
importunittest
classNode(object):
def__init__(self,data=None,next=None):
self.data=data
self.next=next
deflistToString(head):
s=''
p=head
whilep:
s+=str(p.data) +'->'
p=p.next
s+='NULL'
returns
deflistLength(head):
i=0
p=head
whilep:
p=p.next
i=i+1
returni
'''
remove the nth node from end of the list
1->2->3->4, n=2, return 1->2->4
'''
defRemoveNthNodeFromEnd(head,n):
'''
Args: head node of the linked list,
the nth node from the end of the list
Return: the head of the linked list
'''
p=head
q=head
ifn<=0orn>listLength(head):
raiseException("Invalid n")
elifn==listLength(head):
head=p.next
else:
whilen>=0:
q=q.next
n=n-1
whileq:
p=p.next
q=q.next
p.next=p.next.next
returnhead
defassertEquals(a, b):
ifa!=b:
raiseException("Values not equal: %s vs. %s"% (a, b))
defassertRaises(f, *args, **kwargs):
raised=False
try:
f(*args, **kwargs)
except:
raised=True
ifnotraised:
raiseException("Exception was not raised")
# printList(RemoveNthNodeFromEnd(head,4))
defGetTestList():
returnNode(1,Node(2,Node(3,Node(4))))
assertEquals("1->2->3->4->NULL", listToString(GetTestList()))
# assertEquals("1->2->3->4->NULL", listToString(RemoveNthNodeFromEnd(head, 0)))
# assertRaises(RemoveNthNodeFromEnd(head, 0))
assertRaises(RemoveNthNodeFromEnd, GetTestList(), 0)
assertEquals("1->2->3->NULL", listToString(RemoveNthNodeFromEnd(GetTestList(), 1)))
assertEquals("1->2->4->NULL", listToString(RemoveNthNodeFromEnd(GetTestList(), 2)))
assertEquals("1->3->4->NULL", listToString(RemoveNthNodeFromEnd(GetTestList(), 3)))
assertEquals("2->3->4->NULL", listToString(RemoveNthNodeFromEnd(GetTestList(), 4)))
assertRaises(RemoveNthNodeFromEnd, GetTestList(), 5)
classTestSequenceFunctions(unittest.TestCase):
defsetUp(self):
self.seq=range(10)
deftest_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
deftest_choice(self):
element=random.choice(self.seq)
self.assertTrue(elementinself.seq)
deftest_sample(self):
withself.assertRaises(ValueError):
random.sample(self.seq, 20)
forelementinrandom.sample(self.seq, 5):
self.assertTrue(elementinself.seq)
if__name__=='__main__':
unittest.main()