RachitD15673 commited on
Commit
5d39a4d
·
1 Parent(s): 9ebc698

Upload very_small_token_data.csv

Browse files
Files changed (1) hide show
  1. very_small_token_data.csv +1217 -0
very_small_token_data.csv ADDED
@@ -0,0 +1,1217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Concept,Prompt,text
2
+ This is a question asked by a user,"The stock span problem is a financial problem where we have a series of n daily
3
+ price quotes for a stock and we need to calculate span of stock's price for all n days.
4
+
5
+ The span Si of the stock's price on a given day i is defined as the maximum
6
+ number of consecutive days just before the given day, for which the price of the stock
7
+ on the current day is less than or equal to its price on the given day.","def calculation_span(price, s):
8
+ n = len(price)
9
+ st = []
10
+ st.append(0)
11
+ s[0] = 1
12
+ for i in range(1, n):
13
+ while len(st) > 0 and price[st[0]] <= price[i]:
14
+ st.pop()
15
+ s[i] = i + 1 if len(st) <= 0 else i - st[0]
16
+ st.append(i)
17
+
18
+
19
+ def print_array(arr, n):
20
+ for i in range(n):
21
+ print(arr[i], end=' ')
22
+
23
+
24
+ price = [10, 4, 5, 90, 120, 80]
25
+ S = [(0) for i in range(len(price) + 1)]
26
+ calculation_span(price, S)
27
+ print_array(S, len(price))"
28
+ This is a question asked by a user,Generate code for middle_element_of_linked_list,"from __future__ import annotations
29
+
30
+
31
+ class Node:
32
+
33
+ def __init__(self, data: int) ->None:
34
+ self.data = data
35
+ self.next = None
36
+
37
+
38
+ class LinkedList:
39
+
40
+ def __init__(self):
41
+ self.head = None
42
+
43
+ def push(self, new_data: int) ->int:
44
+ new_node = Node(new_data)
45
+ new_node.next = self.head
46
+ self.head = new_node
47
+ return self.head.data
48
+
49
+ def middle_element(self) ->(int | None):
50
+ slow_pointer = self.head
51
+ fast_pointer = self.head
52
+ if self.head:
53
+ while fast_pointer and fast_pointer.next:
54
+ fast_pointer = fast_pointer.next.next
55
+ slow_pointer = slow_pointer.next
56
+ return slow_pointer.data
57
+ else:
58
+ print('No element found.')
59
+ return None
60
+
61
+
62
+ if __name__ == '__main__':
63
+ link = LinkedList()
64
+ for _ in range(int(input().strip())):
65
+ data = int(input().strip())
66
+ link.push(data)
67
+ print(link.middle_element())
68
+ "
69
+ This is a question asked by a user,"Task:
70
+ Given a positive int number. Return True if this number is power of 4
71
+ or False otherwise.
72
+
73
+ Implementation notes: Use bit manipulation.
74
+ For example if the number is the power of 2 it's bits representation:
75
+ n = 0..100..00
76
+ n - 1 = 0..011..11
77
+
78
+ n & (n - 1) - no intersections = 0
79
+ If the number is a power of 4 then it should be a power of 2
80
+ and the set bit should be at an odd position.","def power_of_4(number: int) ->bool:
81
+ if not isinstance(number, int):
82
+ raise TypeError('number must be an integer')
83
+ if number <= 0:
84
+ raise ValueError('number must be positive')
85
+ if number & number - 1 == 0:
86
+ c = 0
87
+ while number:
88
+ c += 1
89
+ number >>= 1
90
+ return c % 2 == 1
91
+ else:
92
+ return False
93
+
94
+
95
+ if __name__ == '__main__':
96
+ import doctest
97
+ doctest.testmod()"
98
+ This is a question asked by a user,"Author: Alexander Joslin
99
+ GitHub: github.com/echoaj
100
+
101
+ Explanation: https://medium.com/@haleesammar/implemented-in-js-dijkstras-2-stack-
102
+ algorithm-for-evaluating-mathematical-expressions-fc0837dae1ea
103
+
104
+ We can use Dijkstra's two stack algorithm to solve an equation
105
+ such as: (5 + ((4 * 2) * (2 + 3)))
106
+
107
+ THESE ARE THE ALGORITHM'S RULES:
108
+ RULE 1: Scan the expression from left to right. When an operand is encountered,
109
+ push it onto the operand stack.
110
+
111
+ RULE 2: When an operator is encountered in the expression,
112
+ push it onto the operator stack.
113
+
114
+ RULE 3: When a left parenthesis is encountered in the expression, ignore it.
115
+
116
+ RULE 4: When a right parenthesis is encountered in the expression,
117
+ pop an operator off the operator stack. The two operands it must
118
+ operate on must be the last two operands pushed onto the operand stack.
119
+ We therefore pop the operand stack twice, perform the operation,
120
+ and push the result back onto the operand stack so it will be available
121
+ for use as an operand of the next operator popped off the operator stack.
122
+
123
+ RULE 5: When the entire infix expression has been scanned, the value left on
124
+ the operand stack represents the value of the expression.
125
+
126
+ NOTE: It only works with whole numbers.","__author__ = 'Alexander Joslin'
127
+ import operator as op
128
+ from .stack import Stack
129
+
130
+
131
+ def dijkstras_two_stack_algorithm(equation: str) ->int:
132
+ operators = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub}
133
+ operand_stack: Stack[int] = Stack()
134
+ operator_stack: Stack[str] = Stack()
135
+ for i in equation:
136
+ if i.isdigit():
137
+ operand_stack.push(int(i))
138
+ elif i in operators:
139
+ operator_stack.push(i)
140
+ elif i == ')':
141
+ opr = operator_stack.peek()
142
+ operator_stack.pop()
143
+ num1 = operand_stack.peek()
144
+ operand_stack.pop()
145
+ num2 = operand_stack.peek()
146
+ operand_stack.pop()
147
+ total = operators[opr](num2, num1)
148
+ operand_stack.push(total)
149
+ return operand_stack.peek()
150
+
151
+
152
+ if __name__ == '__main__':
153
+ equation = '(5 + ((4 * 2) * (2 + 3)))'
154
+ print(f'{equation} = {dijkstras_two_stack_algorithm(equation)}')"
155
+ This is a question asked by a user,Generate code for base16,"def base16_encode(data: bytes) ->str:
156
+ return ''.join([hex(byte)[2:].zfill(2).upper() for byte in list(data)])
157
+
158
+
159
+ def base16_decode(data: str) ->bytes:
160
+ if len(data) % 2 != 0:
161
+ raise ValueError(
162
+ """"""Base16 encoded data is invalid:
163
+ Data does not have an even number of hex digits.""""""
164
+ )
165
+ if not set(data) <= set('0123456789ABCDEF'):
166
+ raise ValueError(
167
+ """"""Base16 encoded data is invalid:
168
+ Data is not uppercase hex or it contains invalid characters.""""""
169
+ )
170
+ return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2)
171
+ )
172
+
173
+
174
+ if __name__ == '__main__':
175
+ import doctest
176
+ doctest.testmod()"
177
+ This is a question asked by a user,Python3 program to evaluate a prefix expression.,"calc = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y:
178
+ x * y, '/': lambda x, y: x / y}
179
+
180
+
181
+ def is_operand(c):
182
+ return c.isdigit()
183
+
184
+
185
+ def evaluate(expression):
186
+ stack = []
187
+ for c in expression.split()[::-1]:
188
+ if is_operand(c):
189
+ stack.append(int(c))
190
+ else:
191
+ o1 = stack.pop()
192
+ o2 = stack.pop()
193
+ stack.append(calc[c](o1, o2))
194
+ return stack.pop()
195
+
196
+
197
+ if __name__ == '__main__':
198
+ test_expression = '+ 9 * 2 6'
199
+ print(evaluate(test_expression))
200
+ test_expression = '/ * 10 2 + 4 1 '
201
+ print(evaluate(test_expression))"
202
+ This is a question asked by a user,"A XOR Gate is a logic gate in boolean algebra which results to 1 (True) if only one of
203
+ the two inputs is 1, and 0 (False) if an even number of inputs are 1.
204
+ Following is the truth table of a XOR Gate:
205
+ ------------------------------
206
+ | Input 1 | Input 2 | Output |
207
+ ------------------------------
208
+ | 0 | 0 | 0 |
209
+ | 0 | 1 | 1 |
210
+ | 1 | 0 | 1 |
211
+ | 1 | 1 | 0 |
212
+ ------------------------------
213
+
214
+ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/","def xor_gate(input_1: int, input_2: int) ->int:
215
+ return (input_1, input_2).count(0) % 2
216
+
217
+
218
+ if __name__ == '__main__':
219
+ import doctest
220
+ doctest.testmod()"
221
+ This is a question asked by a user,"Author : Alexander Pantyukhin
222
+ Date : November 30, 2022
223
+
224
+ Task:
225
+ Given two int numbers. Return True these numbers have opposite signs
226
+ or False otherwise.
227
+
228
+ Implementation notes: Use bit manipulation.
229
+ Use XOR for two numbers.","def different_signs(num1: int, num2: int) ->bool:
230
+ return num1 ^ num2 < 0
231
+
232
+
233
+ if __name__ == '__main__':
234
+ import doctest
235
+ doctest.testmod()"
236
+ This is a question asked by a user,"A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the
237
+ inputs are different, and 1 (True), if the inputs are same.
238
+ It's similar to adding a NOT gate to an XOR gate
239
+
240
+ Following is the truth table of a XNOR Gate:
241
+ ------------------------------
242
+ | Input 1 | Input 2 | Output |
243
+ ------------------------------
244
+ | 0 | 0 | 1 |
245
+ | 0 | 1 | 0 |
246
+ | 1 | 0 | 0 |
247
+ | 1 | 1 | 1 |
248
+ ------------------------------
249
+ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/","def xnor_gate(input_1: int, input_2: int) ->int:
250
+ return 1 if input_1 == input_2 else 0
251
+
252
+
253
+ if __name__ == '__main__':
254
+ import doctest
255
+ doctest.testmod()"
256
+ This is a question asked by a user,Generate code for find_triplets_with_0_sum,"from itertools import combinations
257
+
258
+
259
+ def find_triplets_with_0_sum(nums: list[int]) ->list[list[int]]:
260
+ return [list(x) for x in sorted({abc for abc in combinations(sorted(
261
+ nums), 3) if not sum(abc)})]"
262
+ This is a question asked by a user,Generate code for reverse_bits,"def get_reverse_bit_string(number: int) ->str:
263
+ if not isinstance(number, int):
264
+ msg = (
265
+ f'operation can not be conducted on a object of type {type(number).__name__}'
266
+ )
267
+ raise TypeError(msg)
268
+ bit_string = ''
269
+ for _ in range(32):
270
+ bit_string += str(number % 2)
271
+ number = number >> 1
272
+ return bit_string
273
+
274
+
275
+ def reverse_bit(number: int) ->str:
276
+ if number < 0:
277
+ raise ValueError('the value of input must be positive')
278
+ elif isinstance(number, float):
279
+ raise TypeError(""Input value must be a 'int' type"")
280
+ elif isinstance(number, str):
281
+ raise TypeError(
282
+ ""'<' not supported between instances of 'str' and 'int'"")
283
+ result = 0
284
+ for _ in range(1, 33):
285
+ result = result << 1
286
+ end_bit = number % 2
287
+ number = number >> 1
288
+ result = result | end_bit
289
+ return get_reverse_bit_string(result)
290
+
291
+
292
+ if __name__ == '__main__':
293
+ import doctest
294
+ doctest.testmod()"
295
+ This is a question asked by a user,Generate code for brute_force_caesar_cipher,"import string
296
+
297
+
298
+ def decrypt(message: str) ->None:
299
+ for key in range(len(string.ascii_uppercase)):
300
+ translated = ''
301
+ for symbol in message:
302
+ if symbol in string.ascii_uppercase:
303
+ num = string.ascii_uppercase.find(symbol)
304
+ num = num - key
305
+ if num < 0:
306
+ num = num + len(string.ascii_uppercase)
307
+ translated = translated + string.ascii_uppercase[num]
308
+ else:
309
+ translated = translated + symbol
310
+ print(f'Decryption using Key #{key}: {translated}')
311
+
312
+
313
+ def main() ->None:
314
+ message = input('Encrypted message: ')
315
+ message = message.upper()
316
+ decrypt(message)
317
+
318
+
319
+ if __name__ == '__main__':
320
+ import doctest
321
+ doctest.testmod()
322
+ main()"
323
+ This is a question asked by a user,"A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle
324
+ through a graph that visits each node exactly once.
325
+ Determining whether such paths and cycles exist in graphs
326
+ is the 'Hamiltonian path problem', which is NP-complete.
327
+
328
+ Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path","def valid_connection(graph: list[list[int]], next_ver: int, curr_ind: int,
329
+ path: list[int]) ->bool:
330
+ if graph[path[curr_ind - 1]][next_ver] == 0:
331
+ return False
332
+ return not any(vertex == next_ver for vertex in path)
333
+
334
+
335
+ def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int
336
+ ) ->bool:
337
+ if curr_ind == len(graph):
338
+ return graph[path[curr_ind - 1]][path[0]] == 1
339
+ for next_ver in range(len(graph)):
340
+ if valid_connection(graph, next_ver, curr_ind, path):
341
+ path[curr_ind] = next_ver
342
+ if util_hamilton_cycle(graph, path, curr_ind + 1):
343
+ return True
344
+ path[curr_ind] = -1
345
+ return False
346
+
347
+
348
+ def hamilton_cycle(graph: list[list[int]], start_index: int=0) ->list[int]:
349
+ path = [-1] * (len(graph) + 1)
350
+ path[0] = path[-1] = start_index
351
+ return path if util_hamilton_cycle(graph, path, 1) else []"
352
+ This is a question asked by a user,Generate code for binary_count_trailing_zeros,"from math import log2
353
+
354
+
355
+ def binary_count_trailing_zeros(a: int) ->int:
356
+ if a < 0:
357
+ raise ValueError('Input value must be a positive integer')
358
+ elif isinstance(a, float):
359
+ raise TypeError(""Input value must be a 'int' type"")
360
+ return 0 if a == 0 else int(log2(a & -a))
361
+
362
+
363
+ if __name__ == '__main__':
364
+ import doctest
365
+ doctest.testmod()"
366
+ This is a question asked by a user,Generate code for gray_code_sequence,"def gray_code(bit_count: int) ->list:
367
+ if bit_count < 0:
368
+ raise ValueError('The given input must be positive')
369
+ sequence = gray_code_sequence_string(bit_count)
370
+ for i in range(len(sequence)):
371
+ sequence[i] = int(sequence[i], 2)
372
+ return sequence
373
+
374
+
375
+ def gray_code_sequence_string(bit_count: int) ->list:
376
+ if bit_count == 0:
377
+ return ['0']
378
+ if bit_count == 1:
379
+ return ['0', '1']
380
+ seq_len = 1 << bit_count
381
+ smaller_sequence = gray_code_sequence_string(bit_count - 1)
382
+ sequence = []
383
+ for i in range(seq_len // 2):
384
+ generated_no = '0' + smaller_sequence[i]
385
+ sequence.append(generated_no)
386
+ for i in reversed(range(seq_len // 2)):
387
+ generated_no = '1' + smaller_sequence[i]
388
+ sequence.append(generated_no)
389
+ return sequence
390
+
391
+
392
+ if __name__ == '__main__':
393
+ import doctest
394
+ doctest.testmod()"
395
+ This is a question asked by a user,"An AND Gate is a logic gate in boolean algebra which results to 1 (True) if both the
396
+ inputs are 1, and 0 (False) otherwise.
397
+
398
+ Following is the truth table of an AND Gate:
399
+ ------------------------------
400
+ | Input 1 | Input 2 | Output |
401
+ ------------------------------
402
+ | 0 | 0 | 0 |
403
+ | 0 | 1 | 0 |
404
+ | 1 | 0 | 0 |
405
+ | 1 | 1 | 1 |
406
+ ------------------------------
407
+
408
+ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/","def and_gate(input_1: int, input_2: int) ->int:
409
+ return int(input_1 and input_2)
410
+
411
+
412
+ if __name__ == '__main__':
413
+ import doctest
414
+ doctest.testmod()"
415
+ This is a question asked by a user,Generate code for index_of_rightmost_set_bit,"def get_index_of_rightmost_set_bit(number: int) ->int:
416
+ if not isinstance(number, int) or number < 0:
417
+ raise ValueError('Input must be a non-negative integer')
418
+ intermediate = number & ~(number - 1)
419
+ index = 0
420
+ while intermediate:
421
+ intermediate >>= 1
422
+ index += 1
423
+ return index - 1
424
+
425
+
426
+ if __name__ == '__main__':
427
+ """"""
428
+ Finding the index of rightmost set bit has some very peculiar use-cases,
429
+ especially in finding missing or/and repeating numbers in a list of
430
+ positive integers.
431
+ """"""
432
+ import doctest
433
+ doctest.testmod(verbose=True)"
434
+ This is a question asked by a user,Generate code for binary_count_setbits,"def binary_count_setbits(a: int) ->int:
435
+ if a < 0:
436
+ raise ValueError('Input value must be a positive integer')
437
+ elif isinstance(a, float):
438
+ raise TypeError(""Input value must be a 'int' type"")
439
+ return bin(a).count('1')
440
+
441
+
442
+ if __name__ == '__main__':
443
+ import doctest
444
+ doctest.testmod()"
445
+ This is a question asked by a user,"In this problem, we want to determine all possible subsequences
446
+ of the given sequence. We use backtracking to solve this problem.
447
+
448
+ Time complexity: O(2^n),
449
+ where n denotes the length of the given sequence.","from __future__ import annotations
450
+ from typing import Any
451
+
452
+
453
+ def generate_all_subsequences(sequence: list[Any]) ->None:
454
+ create_state_space_tree(sequence, [], 0)
455
+
456
+
457
+ def create_state_space_tree(sequence: list[Any], current_subsequence: list[
458
+ Any], index: int) ->None:
459
+ if index == len(sequence):
460
+ print(current_subsequence)
461
+ return
462
+ create_state_space_tree(sequence, current_subsequence, index + 1)
463
+ current_subsequence.append(sequence[index])
464
+ create_state_space_tree(sequence, current_subsequence, index + 1)
465
+ current_subsequence.pop()
466
+
467
+
468
+ if __name__ == '__main__':
469
+ seq: list[Any] = [3, 1, 2, 4]
470
+ generate_all_subsequences(seq)
471
+ seq.clear()
472
+ seq.extend(['A', 'B', 'C'])
473
+ generate_all_subsequences(seq)"
474
+ This is a question asked by a user,"Calculates the sum of two non-negative integers using bitwise operators
475
+ Wikipedia explanation: https://en.wikipedia.org/wiki/Binary_number","def bitwise_addition_recursive(number: int, other_number: int) ->int:
476
+ if not isinstance(number, int) or not isinstance(other_number, int):
477
+ raise TypeError('Both arguments MUST be integers!')
478
+ if number < 0 or other_number < 0:
479
+ raise ValueError('Both arguments MUST be non-negative!')
480
+ bitwise_sum = number ^ other_number
481
+ carry = number & other_number
482
+ if carry == 0:
483
+ return bitwise_sum
484
+ return bitwise_addition_recursive(bitwise_sum, carry << 1)
485
+
486
+
487
+ if __name__ == '__main__':
488
+ import doctest
489
+ doctest.testmod()"
490
+ This is a question asked by a user,"Calculate the Product Sum from a Special Array.
491
+ reference: https://dev.to/sfrasica/algorithms-product-sum-from-an-array-dc6
492
+
493
+ Python doctests can be run with the following command:
494
+ python -m doctest -v product_sum.py
495
+
496
+ Calculate the product sum of a ""special"" array which can contain integers or nested
497
+ arrays. The product sum is obtained by adding all elements and multiplying by their
498
+ respective depths.
499
+
500
+ For example, in the array [x, y], the product sum is (x + y). In the array [x, [y, z]],
501
+ the product sum is x + 2 * (y + z). In the array [x, [y, [z]]],
502
+ the product sum is x + 2 * (y + 3z).
503
+
504
+ Example Input:
505
+ [5, 2, [-7, 1], 3, [6, [-13, 8], 4]]
506
+ Output: 12","def product_sum(arr: list[int | list], depth: int) ->int:
507
+ total_sum = 0
508
+ for ele in arr:
509
+ total_sum += product_sum(ele, depth + 1) if isinstance(ele, list
510
+ ) else ele
511
+ return total_sum * depth
512
+
513
+
514
+ def product_sum_array(array: list[int | list]) ->int:
515
+ return product_sum(array, 1)
516
+
517
+
518
+ if __name__ == '__main__':
519
+ import doctest
520
+ doctest.testmod()"
521
+ This is a question asked by a user,Generate code for intersection,"import math
522
+ from collections.abc import Callable
523
+
524
+
525
+ def intersection(function: Callable[[float], float], x0: float, x1: float
526
+ ) ->float:
527
+ x_n: float = x0
528
+ x_n1: float = x1
529
+ while True:
530
+ if x_n == x_n1 or function(x_n1) == function(x_n):
531
+ raise ZeroDivisionError(
532
+ 'float division by zero, could not find root')
533
+ x_n2: float = x_n1 - function(x_n1) / ((function(x_n1) - function(
534
+ x_n)) / (x_n1 - x_n))
535
+ if abs(x_n2 - x_n1) < 10 ** -5:
536
+ return x_n2
537
+ x_n = x_n1
538
+ x_n1 = x_n2
539
+
540
+
541
+ def f(x: float) ->float:
542
+ return math.pow(x, 3) - 2 * x - 5
543
+
544
+
545
+ if __name__ == '__main__':
546
+ print(intersection(f, 3, 3.5))"
547
+ This is a question asked by a user,Convert a Decimal Number to an Octal Number.,"import math
548
+
549
+
550
+ def decimal_to_octal(num: int) ->str:
551
+ octal = 0
552
+ counter = 0
553
+ while num > 0:
554
+ remainder = num % 8
555
+ octal = octal + remainder * math.floor(math.pow(10, counter))
556
+ counter += 1
557
+ num = math.floor(num / 8)
558
+ return f'0o{int(octal)}'
559
+
560
+
561
+ def main() ->None:
562
+ print('\n2 in octal is:')
563
+ print(decimal_to_octal(2))
564
+ print('\n8 in octal is:')
565
+ print(decimal_to_octal(8))
566
+ print('\n65 in octal is:')
567
+ print(decimal_to_octal(65))
568
+ print('\n216 in octal is:')
569
+ print(decimal_to_octal(216))
570
+ print('\n512 in octal is:')
571
+ print(decimal_to_octal(512))
572
+ print('\n')
573
+
574
+
575
+ if __name__ == '__main__':
576
+ main()"
577
+ This is a question asked by a user,"Convert a string of characters to a sequence of numbers
578
+ corresponding to the character's position in the alphabet.
579
+
580
+ https://www.dcode.fr/letter-number-cipher
581
+ http://bestcodes.weebly.com/a1z26.html","from __future__ import annotations
582
+
583
+
584
+ def encode(plain: str) ->list[int]:
585
+ return [(ord(elem) - 96) for elem in plain]
586
+
587
+
588
+ def decode(encoded: list[int]) ->str:
589
+ return ''.join(chr(elem + 96) for elem in encoded)
590
+
591
+
592
+ def main() ->None:
593
+ encoded = encode(input('-> ').strip().lower())
594
+ print('Encoded: ', encoded)
595
+ print('Decoded:', decode(encoded))
596
+
597
+
598
+ if __name__ == '__main__':
599
+ main()"
600
+ This is a question asked by a user,Generate code for onepad_cipher,"import random
601
+
602
+
603
+ class Onepad:
604
+
605
+ @staticmethod
606
+ def encrypt(text: str) ->tuple[list[int], list[int]]:
607
+ plain = [ord(i) for i in text]
608
+ key = []
609
+ cipher = []
610
+ for i in plain:
611
+ k = random.randint(1, 300)
612
+ c = (i + k) * k
613
+ cipher.append(c)
614
+ key.append(k)
615
+ return cipher, key
616
+
617
+ @staticmethod
618
+ def decrypt(cipher: list[int], key: list[int]) ->str:
619
+ plain = []
620
+ for i in range(len(key)):
621
+ p = int((cipher[i] - key[i] ** 2) / key[i])
622
+ plain.append(chr(p))
623
+ return ''.join(plain)
624
+
625
+
626
+ if __name__ == '__main__':
627
+ c, k = Onepad().encrypt('Hello')
628
+ print(c, k)
629
+ print(Onepad().decrypt(c, k))"
630
+ This is a question asked by a user,Generate code for binary_and_operator,"def binary_and(a: int, b: int) ->str:
631
+ if a < 0 or b < 0:
632
+ raise ValueError('the value of both inputs must be positive')
633
+ a_binary = str(bin(a))[2:]
634
+ b_binary = str(bin(b))[2:]
635
+ max_len = max(len(a_binary), len(b_binary))
636
+ return '0b' + ''.join(str(int(char_a == '1' and char_b == '1')) for
637
+ char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))
638
+ )
639
+
640
+
641
+ if __name__ == '__main__':
642
+ import doctest
643
+ doctest.testmod()"
644
+ This is a question asked by a user,"Author : Naman Sharma
645
+ Date : October 2, 2023
646
+
647
+ Task:
648
+ To Find the largest power of 2 less than or equal to a given number.
649
+
650
+ Implementation notes: Use bit manipulation.
651
+ We start from 1 & left shift the set bit to check if (res<<1)<=number.
652
+ Each left bit shift represents a pow of 2.
653
+
654
+ For example:
655
+ number: 15
656
+ res: 1 0b1
657
+ 2 0b10
658
+ 4 0b100
659
+ 8 0b1000
660
+ 16 0b10000 (Exit)","def largest_pow_of_two_le_num(number: int) ->int:
661
+ if isinstance(number, float):
662
+ raise TypeError(""Input value must be a 'int' type"")
663
+ if number <= 0:
664
+ return 0
665
+ res = 1
666
+ while res << 1 <= number:
667
+ res <<= 1
668
+ return res
669
+
670
+
671
+ if __name__ == '__main__':
672
+ import doctest
673
+ doctest.testmod()"
674
+ This is a question asked by a user,Generate code for hash_table_with_linked_list,"from collections import deque
675
+ from .hash_table import HashTable
676
+
677
+
678
+ class HashTableWithLinkedList(HashTable):
679
+
680
+ def __init__(self, *args, **kwargs):
681
+ super().__init__(*args, **kwargs)
682
+
683
+ def _set_value(self, key, data):
684
+ self.values[key] = deque([]) if self.values[key
685
+ ] is None else self.values[key]
686
+ self.values[key].appendleft(data)
687
+ self._keys[key] = self.values[key]
688
+
689
+ def balanced_factor(self):
690
+ return sum(self.charge_factor - len(slot) for slot in self.values
691
+ ) / self.size_table * self.charge_factor
692
+
693
+ def _collision_resolution(self, key, data=None):
694
+ if not (len(self.values[key]) == self.charge_factor and self.values
695
+ .count(None) == 0):
696
+ return key
697
+ return super()._collision_resolution(key, data)"
698
+ This is a question asked by a user,"A NOT Gate is a logic gate in boolean algebra which results to 0 (False) if the
699
+ input is high, and 1 (True) if the input is low.
700
+ Following is the truth table of a XOR Gate:
701
+ ------------------------------
702
+ | Input | Output |
703
+ ------------------------------
704
+ | 0 | 1 |
705
+ | 1 | 0 |
706
+ ------------------------------
707
+ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/","def not_gate(input_1: int) ->int:
708
+ return 1 if input_1 == 0 else 0
709
+
710
+
711
+ if __name__ == '__main__':
712
+ import doctest
713
+ doctest.testmod()"
714
+ This is a question asked by a user,Generate code for missing_number,"def find_missing_number(nums: list[int]) ->int:
715
+ low = min(nums)
716
+ high = max(nums)
717
+ missing_number = high
718
+ for i in range(low, high):
719
+ missing_number ^= i ^ nums[i - low]
720
+ return missing_number
721
+ "
722
+ This is a question asked by a user,"Lower–upper (LU) decomposition factors a matrix as a product of a lower
723
+ triangular matrix and an upper triangular matrix. A square matrix has an LU
724
+ decomposition under the following conditions:
725
+ - If the matrix is invertible, then it has an LU decomposition if and only
726
+ if all of its leading principal minors are non-zero (see
727
+ https://en.wikipedia.org/wiki/Minor_(linear_algebra) for an explanation of
728
+ leading principal minors of a matrix).
729
+ - If the matrix is singular (i.e., not invertible) and it has a rank of k
730
+ (i.e., it has k linearly independent columns), then it has an LU
731
+ decomposition if its first k leading principal minors are non-zero.
732
+
733
+ This algorithm will simply attempt to perform LU decomposition on any square
734
+ matrix and raise an error if no such decomposition exists.
735
+
736
+ Reference: https://en.wikipedia.org/wiki/LU_decomposition","from __future__ import annotations
737
+ import numpy as np
738
+
739
+
740
+ def lower_upper_decomposition(table: np.ndarray) ->tuple[np.ndarray, np.ndarray
741
+ ]:
742
+ rows, columns = np.shape(table)
743
+ if rows != columns:
744
+ msg = (
745
+ f""'table' has to be of square shaped array but got a {rows}x{columns} array:\n{table}""
746
+ )
747
+ raise ValueError(msg)
748
+ lower = np.zeros((rows, columns))
749
+ upper = np.zeros((rows, columns))
750
+ for i in range(columns):
751
+ for j in range(i):
752
+ total = np.sum(lower[i, :i] * upper[:i, j])
753
+ if upper[j][j] == 0:
754
+ raise ArithmeticError('No LU decomposition exists')
755
+ lower[i][j] = (table[i][j] - total) / upper[j][j]
756
+ lower[i][i] = 1
757
+ for j in range(i, columns):
758
+ total = np.sum(lower[i, :i] * upper[:i, j])
759
+ upper[i][j] = table[i][j] - total
760
+ return lower, upper
761
+
762
+
763
+ if __name__ == '__main__':
764
+ import doctest
765
+ doctest.testmod()"
766
+ This is a question asked by a user,Provide the functionality to manipulate a single bit.,"def set_bit(number: int, position: int) ->int:
767
+ return number | 1 << position
768
+
769
+
770
+ def clear_bit(number: int, position: int) ->int:
771
+ return number & ~(1 << position)
772
+
773
+
774
+ def flip_bit(number: int, position: int) ->int:
775
+ return number ^ 1 << position
776
+
777
+
778
+ def is_bit_set(number: int, position: int) ->bool:
779
+ return number >> position & 1 == 1
780
+
781
+
782
+ def get_bit(number: int, position: int) ->int:
783
+ return int(number & 1 << position != 0)
784
+
785
+
786
+ if __name__ == '__main__':
787
+ import doctest
788
+ doctest.testmod()"
789
+ This is a question asked by a user,Generate code for count_1s_brian_kernighan_method,"def get_1s_count(number: int) ->int:
790
+ if not isinstance(number, int) or number < 0:
791
+ raise ValueError('Input must be a non-negative integer')
792
+ count = 0
793
+ while number:
794
+ number &= number - 1
795
+ count += 1
796
+ return count
797
+
798
+
799
+ if __name__ == '__main__':
800
+ import doctest
801
+ doctest.testmod()"
802
+ This is a question asked by a user,Generate code for is_even,"def is_even(number: int) ->bool:
803
+ return number & 1 == 0
804
+
805
+
806
+ if __name__ == '__main__':
807
+ import doctest
808
+ doctest.testmod()"
809
+ This is a question asked by a user,Generate code for mean_threshold,"from PIL import Image
810
+ """"""
811
+ Mean thresholding algorithm for image processing
812
+ https://en.wikipedia.org/wiki/Thresholding_(image_processing)
813
+ """"""
814
+
815
+
816
+ def mean_threshold(image: Image) ->Image:
817
+ height, width = image.size
818
+ mean = 0
819
+ pixels = image.load()
820
+ for i in range(width):
821
+ for j in range(height):
822
+ pixel = pixels[j, i]
823
+ mean += pixel
824
+ mean //= width * height
825
+ for j in range(width):
826
+ for i in range(height):
827
+ pixels[i, j] = 255 if pixels[i, j] > mean else 0
828
+ return image
829
+
830
+
831
+ if __name__ == '__main__':
832
+ image = mean_threshold(Image.open('path_to_image').convert('L'))
833
+ image.save('output_image_path')"
834
+ This is a question asked by a user,"An NIMPLY Gate is a logic gate in boolean algebra which results to 0 if
835
+ either input 1 is 0, or if input 1 is 1, then it is 0 only if input 2 is 1.
836
+ It is false if input 1 implies input 2. It is the negated form of imply
837
+
838
+ Following is the truth table of an NIMPLY Gate:
839
+ ------------------------------
840
+ | Input 1 | Input 2 | Output |
841
+ ------------------------------
842
+ | 0 | 0 | 0 |
843
+ | 0 | 1 | 0 |
844
+ | 1 | 0 | 1 |
845
+ | 1 | 1 | 0 |
846
+ ------------------------------
847
+
848
+ Refer - https://en.wikipedia.org/wiki/NIMPLY_gate","def nimply_gate(input_1: int, input_2: int) ->int:
849
+ return int(input_1 == 1 and input_2 == 0)
850
+
851
+
852
+ if __name__ == '__main__':
853
+ import doctest
854
+ doctest.testmod()"
855
+ This is a question asked by a user,Newton's Method.,"from collections.abc import Callable
856
+ RealFunc = Callable[[float], float]
857
+
858
+
859
+ def newton(function: RealFunc, derivative: RealFunc, starting_int: int
860
+ ) ->float:
861
+ prev_guess = float(starting_int)
862
+ while True:
863
+ try:
864
+ next_guess = prev_guess - function(prev_guess) / derivative(
865
+ prev_guess)
866
+ except ZeroDivisionError:
867
+ raise ZeroDivisionError('Could not find root') from None
868
+ if abs(prev_guess - next_guess) < 10 ** -5:
869
+ return next_guess
870
+ prev_guess = next_guess
871
+
872
+
873
+ def f(x: float) ->float:
874
+ return x ** 3 - 2 * x - 5
875
+
876
+
877
+ def f1(x: float) ->float:
878
+ return 3 * x ** 2 - 2
879
+
880
+
881
+ if __name__ == '__main__':
882
+ print(newton(f, f1, 3))"
883
+ This is a question asked by a user,Queue implementation using two stacks,"from collections.abc import Iterable
884
+ from typing import Generic, TypeVar
885
+ _T = TypeVar('_T')
886
+
887
+
888
+ class QueueByTwoStacks(Generic[_T]):
889
+
890
+ def __init__(self, iterable: (Iterable[_T] | None)=None) ->None:
891
+ self._stack1: list[_T] = list(iterable or [])
892
+ self._stack2: list[_T] = []
893
+
894
+ def __len__(self) ->int:
895
+ return len(self._stack1) + len(self._stack2)
896
+
897
+ def __repr__(self) ->str:
898
+ return f'Queue({tuple(self._stack2[::-1] + self._stack1)})'
899
+
900
+ def put(self, item: _T) ->None:
901
+ self._stack1.append(item)
902
+
903
+ def get(self) ->_T:
904
+ stack1_pop = self._stack1.pop
905
+ stack2_append = self._stack2.append
906
+ if not self._stack2:
907
+ while self._stack1:
908
+ stack2_append(stack1_pop())
909
+ if not self._stack2:
910
+ raise IndexError('Queue is empty')
911
+ return self._stack2.pop()
912
+
913
+
914
+ if __name__ == '__main__':
915
+ from doctest import testmod
916
+ testmod()"
917
+ This is a question asked by a user,Generate code for quadratic_probing,"from .hash_table import HashTable
918
+
919
+
920
+ class QuadraticProbing(HashTable):
921
+
922
+ def __init__(self, *args, **kwargs):
923
+ super().__init__(*args, **kwargs)
924
+
925
+ def _collision_resolution(self, key, data=None):
926
+ i = 1
927
+ new_key = self.hash_function(key + i * i)
928
+ while self.values[new_key] is not None and self.values[new_key] != key:
929
+ i += 1
930
+ new_key = self.hash_function(key + i * i
931
+ ) if not self.balanced_factor() >= self.lim_charge else None
932
+ if new_key is None:
933
+ break
934
+ return new_key"
935
+ This is a question asked by a user,https://www.enjoyalgorithms.com/blog/median-of-two-sorted-arrays,"def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) ->float:
936
+ if not nums1 and not nums2:
937
+ raise ValueError('Both input arrays are empty.')
938
+ merged = sorted(nums1 + nums2)
939
+ total = len(merged)
940
+ if total % 2 == 1:
941
+ return float(merged[total // 2])
942
+ middle1 = merged[total // 2 - 1]
943
+ middle2 = merged[total // 2]
944
+ return (float(middle1) + float(middle2)) / 2.0
945
+
946
+
947
+ if __name__ == '__main__':
948
+ import doctest
949
+ doctest.testmod()"
950
+ This is a question asked by a user,"Given an array of integers and an integer req_sum, find the number of pairs of array
951
+ elements whose sum is equal to req_sum.
952
+
953
+ https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0","from itertools import combinations
954
+
955
+
956
+ def pairs_with_sum(arr: list, req_sum: int) ->int:
957
+ return len([(1) for a, b in combinations(arr, 2) if a + b == req_sum])
958
+
959
+
960
+ if __name__ == '__main__':
961
+ from doctest import testmod
962
+ testmod()"
963
+ This is a question asked by a user,"Minimax helps to achieve maximum score in a game by checking all possible moves
964
+ depth is current depth in game tree.
965
+
966
+ nodeIndex is index of current node in scores[].
967
+ if move is of maximizer return true else false
968
+ leaves of game tree is stored in scores[]
969
+ height is maximum height of Game tree","from __future__ import annotations
970
+ import math
971
+
972
+
973
+ def minimax(depth: int, node_index: int, is_max: bool, scores: list[int],
974
+ height: float) ->int:
975
+ if depth < 0:
976
+ raise ValueError('Depth cannot be less than 0')
977
+ if len(scores) == 0:
978
+ raise ValueError('Scores cannot be empty')
979
+ if depth == height:
980
+ return scores[node_index]
981
+ if is_max:
982
+ return max(minimax(depth + 1, node_index * 2, False, scores, height
983
+ ), minimax(depth + 1, node_index * 2 + 1, False, scores, height))
984
+ return min(minimax(depth + 1, node_index * 2, True, scores, height),
985
+ minimax(depth + 1, node_index * 2 + 1, True, scores, height))
986
+
987
+
988
+ def main() ->None:
989
+ scores = [90, 23, 6, 33, 21, 65, 123, 34423]
990
+ height = math.log(len(scores), 2)
991
+ print('Optimal value : ', end='')
992
+ print(minimax(0, 0, True, scores, height))
993
+
994
+
995
+ if __name__ == '__main__':
996
+ import doctest
997
+ doctest.testmod()
998
+ main()"
999
+ This is a question asked by a user,"Author : Alexander Pantyukhin
1000
+ Date : November 3, 2022
1001
+
1002
+ Implement the class of prefix sum with useful functions based on it.","class PrefixSum:
1003
+
1004
+ def __init__(self, array: list[int]) ->None:
1005
+ len_array = len(array)
1006
+ self.prefix_sum = [0] * len_array
1007
+ if len_array > 0:
1008
+ self.prefix_sum[0] = array[0]
1009
+ for i in range(1, len_array):
1010
+ self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i]
1011
+
1012
+ def get_sum(self, start: int, end: int) ->int:
1013
+ if start == 0:
1014
+ return self.prefix_sum[end]
1015
+ return self.prefix_sum[end] - self.prefix_sum[start - 1]
1016
+
1017
+ def contains_sum(self, target_sum: int) ->bool:
1018
+ sums = {0}
1019
+ for sum_item in self.prefix_sum:
1020
+ if sum_item - target_sum in sums:
1021
+ return True
1022
+ sums.add(sum_item)
1023
+ return False
1024
+
1025
+
1026
+ if __name__ == '__main__':
1027
+ import doctest
1028
+ doctest.testmod()"
1029
+ This is a question asked by a user,Generate code for highest_set_bit,"def get_highest_set_bit_position(number: int) ->int:
1030
+ if not isinstance(number, int):
1031
+ raise TypeError(""Input value must be an 'int' type"")
1032
+ position = 0
1033
+ while number:
1034
+ position += 1
1035
+ number >>= 1
1036
+ return position
1037
+
1038
+
1039
+ if __name__ == '__main__':
1040
+ import doctest
1041
+ doctest.testmod()"
1042
+ This is a question asked by a user,"A NOR Gate is a logic gate in boolean algebra which results to false(0)
1043
+ if any of the input is 1, and True(1) if both the inputs are 0.
1044
+ Following is the truth table of a NOR Gate:
1045
+ | Input 1 | Input 2 | Output |
1046
+ | 0 | 0 | 1 |
1047
+ | 0 | 1 | 0 |
1048
+ | 1 | 0 | 0 |
1049
+ | 1 | 1 | 0 |
1050
+
1051
+ Following is the code implementation of the NOR Gate","def nor_gate(input_1: int, input_2: int) ->int:
1052
+ return int(input_1 == input_2 == 0)
1053
+
1054
+
1055
+ def main() ->None:
1056
+ print('Truth Table of NOR Gate:')
1057
+ print('| Input 1 | Input 2 | Output |')
1058
+ print(f'| 0 | 0 | {nor_gate(0, 0)} |')
1059
+ print(f'| 0 | 1 | {nor_gate(0, 1)} |')
1060
+ print(f'| 1 | 0 | {nor_gate(1, 0)} |')
1061
+ print(f'| 1 | 1 | {nor_gate(1, 1)} |')
1062
+
1063
+
1064
+ if __name__ == '__main__':
1065
+ import doctest
1066
+ doctest.testmod()
1067
+ main()
1068
+ """"""Code provided by Akshaj Vishwanathan""""""
1069
+ """"""Reference: https://www.geeksforgeeks.org/logic-gates-in-python/"""""""
1070
+ This is a question asked by a user,Generate code for cryptomath_module,"from maths.greatest_common_divisor import gcd_by_iterative
1071
+
1072
+
1073
+ def find_mod_inverse(a: int, m: int) ->int:
1074
+ if gcd_by_iterative(a, m) != 1:
1075
+ msg = f'mod inverse of {a!r} and {m!r} does not exist'
1076
+ raise ValueError(msg)
1077
+ u1, u2, u3 = 1, 0, a
1078
+ v1, v2, v3 = 0, 1, m
1079
+ while v3 != 0:
1080
+ q = u3 // v3
1081
+ v1, v2, v3, u1, u2, u3 = (u1 - q * v1, u2 - q * v2, u3 - q * v3, v1,
1082
+ v2, v3)
1083
+ return u1 % m"
1084
+ This is a question asked by a user,"Graph Coloring also called ""m coloring problem""
1085
+ consists of coloring a given graph with at most m colors
1086
+ such that no adjacent vertices are assigned the same color
1087
+
1088
+ Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring","def valid_coloring(neighbours: list[int], colored_vertices: list[int],
1089
+ color: int) ->bool:
1090
+ return not any(neighbour == 1 and colored_vertices[i] == color for i,
1091
+ neighbour in enumerate(neighbours))
1092
+
1093
+
1094
+ def util_color(graph: list[list[int]], max_colors: int, colored_vertices:
1095
+ list[int], index: int) ->bool:
1096
+ if index == len(graph):
1097
+ return True
1098
+ for i in range(max_colors):
1099
+ if valid_coloring(graph[index], colored_vertices, i):
1100
+ colored_vertices[index] = i
1101
+ if util_color(graph, max_colors, colored_vertices, index + 1):
1102
+ return True
1103
+ colored_vertices[index] = -1
1104
+ return False
1105
+
1106
+
1107
+ def color(graph: list[list[int]], max_colors: int) ->list[int]:
1108
+ colored_vertices = [-1] * len(graph)
1109
+ if util_color(graph, max_colors, colored_vertices, 0):
1110
+ return colored_vertices
1111
+ return []"
1112
+ This is a question asked by a user,Generate code for circular_queue,"class CircularQueue:
1113
+
1114
+ def __init__(self, n: int):
1115
+ self.n = n
1116
+ self.array = [None] * self.n
1117
+ self.front = 0
1118
+ self.rear = 0
1119
+ self.size = 0
1120
+
1121
+ def __len__(self) ->int:
1122
+ return self.size
1123
+
1124
+ def is_empty(self) ->bool:
1125
+ return self.size == 0
1126
+
1127
+ def first(self):
1128
+ return False if self.is_empty() else self.array[self.front]
1129
+
1130
+ def enqueue(self, data):
1131
+ if self.size >= self.n:
1132
+ raise Exception('QUEUE IS FULL')
1133
+ self.array[self.rear] = data
1134
+ self.rear = (self.rear + 1) % self.n
1135
+ self.size += 1
1136
+ return self
1137
+
1138
+ def dequeue(self):
1139
+ if self.size == 0:
1140
+ raise Exception('UNDERFLOW')
1141
+ temp = self.array[self.front]
1142
+ self.array[self.front] = None
1143
+ self.front = (self.front + 1) % self.n
1144
+ self.size -= 1
1145
+ return temp"
1146
+ This is a question asked by a user,Generate code for permutations,"def permute_recursive(nums: list[int]) ->list[list[int]]:
1147
+ result: list[list[int]] = []
1148
+ if len(nums) == 0:
1149
+ return [[]]
1150
+ for _ in range(len(nums)):
1151
+ n = nums.pop(0)
1152
+ permutations = permute_recursive(nums.copy())
1153
+ for perm in permutations:
1154
+ perm.append(n)
1155
+ result.extend(permutations)
1156
+ nums.append(n)
1157
+ return result
1158
+
1159
+
1160
+ def permute_backtrack(nums: list[int]) ->list[list[int]]:
1161
+
1162
+ def backtrack(start: int) ->None:
1163
+ if start == len(nums) - 1:
1164
+ output.append(nums[:])
1165
+ else:
1166
+ for i in range(start, len(nums)):
1167
+ nums[start], nums[i] = nums[i], nums[start]
1168
+ backtrack(start + 1)
1169
+ nums[start], nums[i] = nums[i], nums[start]
1170
+ output: list[list[int]] = []
1171
+ backtrack(0)
1172
+ return output
1173
+
1174
+
1175
+ if __name__ == '__main__':
1176
+ import doctest
1177
+ result = permute_backtrack([1, 2, 3])
1178
+ print(result)
1179
+ doctest.testmod()"
1180
+ This is a question asked by a user,Generate code for newton_forward_interpolation,"from __future__ import annotations
1181
+ import math
1182
+
1183
+
1184
+ def ucal(u: float, p: int) ->float:
1185
+ temp = u
1186
+ for i in range(1, p):
1187
+ temp = temp * (u - i)
1188
+ return temp
1189
+
1190
+
1191
+ def main() ->None:
1192
+ n = int(input('enter the numbers of values: '))
1193
+ y: list[list[float]] = []
1194
+ for _ in range(n):
1195
+ y.append([])
1196
+ for i in range(n):
1197
+ for j in range(n):
1198
+ y[i].append(j)
1199
+ y[i][j] = 0
1200
+ print('enter the values of parameters in a list: ')
1201
+ x = list(map(int, input().split()))
1202
+ print('enter the values of corresponding parameters: ')
1203
+ for i in range(n):
1204
+ y[i][0] = float(input())
1205
+ value = int(input('enter the value to interpolate: '))
1206
+ u = (value - x[0]) / (x[1] - x[0])
1207
+ for i in range(1, n):
1208
+ for j in range(n - i):
1209
+ y[j][i] = y[j + 1][i - 1] - y[j][i - 1]
1210
+ summ = y[0][0]
1211
+ for i in range(1, n):
1212
+ summ += ucal(u, i) * y[0][i] / math.factorial(i)
1213
+ print(f'the value at {value} is {summ}')
1214
+
1215
+
1216
+ if __name__ == '__main__':
1217
+ main()"