content
stringlengths 7
1.05M
|
---|
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
paths = [[1] * n for _ in range(m)]
for row in range(1, m):
for col in range(1, n):
paths[row][col] = paths[row-1][col] + paths[row][col-1]
return paths[m-1][n-1] |
# The search the 2D array for the target element where array is sorted from
# left to right and top to bottom
def search_2D_array(arr,x):
row = 0
col = len(arr[0]) - 1
while row < len(arr) and col >= 0:
if arr[col][row] == x:
return True
elif arr[row][col] < x:
row += 1
else:
col -= 1
return False
if __name__ == "__main__":
arr = [[10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]
]
if search_2D_array(arr,37):
print("Present in array")
else:
print("Not present.")
|
n, k = map(int, input().split())
a = list(map(int, input().split()))
fre = [0] * (10 ** 5 + 5)
unique = 0
j = 0
for i in range(n):
if fre[a[i]] == 0:
unique += 1
fre[a[i]] += 1
while unique == k:
fre[a[j]] -= 1
if fre[a[j]] == 0:
print(j + 1, i + 1)
exit()
j += 1
print('-1 -1')
|
"""The pyang library for parsing, validating, and converting YANG modules"""
__version__ = '2.5.3'
__date__ = '2022-03-30'
|
def fat_total(receita_estados: dict):
return sum(receita_estados.values())
def repr_percentual(receita_estados: dict):
receita_total = fat_total(receita_estados)
for estado, faturamento in receita_estados.items():
repr_percentual = (faturamento/receita_total)*100
print(
f"{estado} teve uma representação percentual de aproximadamente {repr_percentual:.2f}% "
f"em relação ao faturamento total"
)
def main():
faturamento_estados = {'SP': 67836.43, 'RJ': 36678.66, 'MG': 29229.88, 'ES': 27165.48, 'Outros': 19849.53}
repr_percentual(faturamento_estados)
if __name__ == '__main__':
main() |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of the `swift_import` rule."""
load(":api.bzl", "swift_common")
load(":attrs.bzl", "SWIFT_COMMON_RULE_ATTRS")
load(":providers.bzl", "SwiftClangModuleInfo", "merge_swift_clang_module_infos")
load("@bazel_skylib//lib:dicts.bzl", "dicts")
def _swift_import_impl(ctx):
archives = ctx.files.archives
deps = ctx.attr.deps
swiftdocs = ctx.files.swiftdocs
swiftmodules = ctx.files.swiftmodules
providers = [
DefaultInfo(
files = depset(direct = archives + swiftdocs + swiftmodules),
runfiles = ctx.runfiles(
collect_data = True,
collect_default = True,
files = ctx.files.data,
),
),
swift_common.build_swift_info(
deps = deps,
direct_libraries = archives,
direct_swiftdocs = swiftdocs,
direct_swiftmodules = swiftmodules,
),
]
# Only propagate `SwiftClangModuleInfo` if any of our deps does.
if any([SwiftClangModuleInfo in dep for dep in deps]):
clang_module = merge_swift_clang_module_infos(deps)
providers.append(clang_module)
return providers
swift_import = rule(
attrs = dicts.add(
SWIFT_COMMON_RULE_ATTRS,
{
"archives": attr.label_list(
allow_empty = False,
allow_files = ["a"],
doc = """
The list of `.a` files provided to Swift targets that depend on this target.
""",
mandatory = True,
),
"swiftdocs": attr.label_list(
allow_empty = True,
allow_files = ["swiftdoc"],
doc = """
The list of `.swiftdoc` files provided to Swift targets that depend on this target.
""",
default = [],
mandatory = False,
),
"swiftmodules": attr.label_list(
allow_empty = False,
allow_files = ["swiftmodule"],
doc = """
The list of `.swiftmodule` files provided to Swift targets that depend on this target.
""",
mandatory = True,
),
},
),
doc = """
Allows for the use of precompiled Swift modules as dependencies in other `swift_library` and
`swift_binary` targets.
""",
implementation = _swift_import_impl,
)
|
n = int(input())
spaces = 2*(n-1)
for i in range(1, n+1):
print(" "*spaces, end="")
if i == 1:
print("1")
else:
for j in range(i, 2*i):
print(str(j) + " ", end="")
for j in range(2*i-2, i-1, -1 ):
print(str(j) + " ", end="")
print()
spaces -= 2 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-12-22 10:42:23
# @Author : Jan Yang
# @Software : Sublime Text
class Email:
def __init__(self):
pass
|
# Perulangan pada string
print('=====Perulangan Pada String=====')
teks = 'helloworld'
print('teks =',teks)
hitung = 0
for i in range(len(teks)):
if 'l' == teks[i]:
hitung = hitung + 1
print('jumlah l pada teks',teks,'adalah',hitung) |
"""
APCS 106/10
Logic Operator
20220127
by Kevin Hsu
"""
iTmp = input("input three number:\n").split()
x = int(iTmp[0])
y = int(iTmp[1])
z = int(iTmp[2])
answer = [0] * 3
if x > 0:
x = 1
if y > 0:
y = 1
if ((x & y) == z):
answer[0] = 1
else:
answer[0] = 0
if ((x | y) == z):
answer[1] = 1
else:
answer[1] = 0
if ((x ^ y) == z):
answer[2] = 1
else:
answer[2] = 0
if answer[0] == 1:
print("AND")
if answer[1] == 1:
print("OR")
if answer[2] == 1:
print("XOR")
if answer[0] == 0 and answer[1] == 0 and answer[2] == 0:
print("IMPOSSIBLE") |
h, m = 100, 200
h_deg, m_deg = h//2, m//3
# In Python3, // rounds down to the nearest whole number
angle = abs(h_deg - m_deg)
if angle > 180:
angle = 360 - angle
print(int(angle))
|
# Gregary C. Zweigle
# 2020
MAX_PIANO_NOTE = 88
# TODO - Should this move elsewhere?
class FileName:
def __init__(self):
self.note_number = 0
self.file_name_l = 'EMPTY_L'
self.file_name_r = 'EMPTY_R'
def initialize_file_name(self, record_start_note):
self.note_number = int(float(record_start_note))
self.file_name_l = 'noteL' + str(self.note_number) + '.dat'
self.file_name_r = 'noteR' + str(self.note_number) + '.dat'
def advance_file_name(self):
self.note_number = self.note_number + 1
self.file_name_l = 'noteL' + str(self.note_number) + '.dat'
self.file_name_r = 'noteR' + str(self.note_number) + '.dat'
def get_file_name(self):
return (self.file_name_l, self.file_name_r)
def check_if_finished_all_notes(self):
if self.note_number > MAX_PIANO_NOTE:
return True
else:
return False
# TODO - Originally it seemed like a good idea to track
# notes in this class, but its too unrelated, need to move out.
def get_note_number(self):
return self.note_number |
n = int(input())
s = list(map(int, input().split()))
c = [0] * 10010
res, count = 0, 0
for i in s:
c[i] += 1
if c[i] > count:
res = i
count = c[i]
elif c[i] == count:
res = min(res, i)
print(res)
|
INPUT= """2
0
0
-2
0
1
-2
-1
-6
2
-1
2
0
2
-13
0
-2
-15
-15
-3
-10
-11
1
-5
-20
-21
-14
-21
-4
-9
-29
2
-10
-5
-33
-33
-9
0
2
-24
0
-26
-24
-38
-28
-42
-14
-42
2
-2
-48
-48
-17
-19
-26
-39
0
-15
-42
-3
-19
-19
-7
-1
-11
-5
-17
-46
-15
-43
-22
-31
-60
-59
-71
-58
-39
-66
-74
-11
-18
-68
1
-70
-79
-18
-56
-17
0
-52
-79
-86
-90
-74
-89
-20
-30
-65
-2
-47
-42
-33
-35
-61
-4
-101
-38
-8
-26
-37
-56
-30
-36
-55
-87
-85
-58
-22
-9
-81
-119
-94
-81
-83
-24
-105
-21
-69
-11
-7
-114
-60
-74
-19
-126
-66
-106
-5
-112
0
-58
-18
-122
-50
-72
-83
-15
-93
-60
-17
-37
-55
-119
-118
-12
-101
-65
-35
-122
-149
-97
-140
-62
-101
-85
-23
-43
-141
-158
-37
-103
-142
1
-112
-55
-139
-90
-5
-75
-73
-171
-4
-39
-4
-135
-126
-40
-74
-161
-125
-174
-90
-129
-126
-166
-106
-16
-51
-54
-135
-37
-21
-103
-73
-64
-59
-88
-153
-196
-123
-98
-36
-193
-164
-111
-81
-49
-87
-91
-191
-219
-103
-217
-107
-87
-82
-23
-157
-56
-20
-149
-133
-53
-37
-199
-85
-133
-12
-228
-15
-217
-106
-52
-179
-118
-54
-70
-99
-160
-24
-71
-55
-7
-105
-174
-187
-226
-210
-55
-130
-137
-255
-259
-117
-10
-162
-61
-19
-54
-225
-23
-84
-183
-262
-44
-215
-268
-201
-89
-3
-241
-277
-8
-177
-31
-269
-35
-132
-175
-253
-85
-286
-265
-292
-196
-132
-212
-131
-117
-196
-245
-294
-32
-20
-184
-246
-171
-64
-220
-3
-179
-186
-51
-276
-203
-191
-205
-141
-304
-186
-273
-299
-17
-46
-254
-126
-268
-163
-69
-326
-192
-279
-293
-220
-20
-137
-330
-8
-53
-49
2
-149
-181
-298
-297
-66
-136
-166
-146
-28
-146
-226
-270
-349
-216
-348
-184
-298
-348
-323
-244
-207
-22
-172
-359
-188
-1
-278
-76
-216
-343
-29
-37
-257
-357
-226
-19
-246
-76
-105
-312
-219
-268
0
-230
-379
-357
-69
-1
-30
-321
-212
-262
-297
-86
-102
-390
-384
-98
-294
-359
-326
-58
-296
-104
-309
-244
-308
-116
-148
-134
-307
-307
-207
-391
-312
-209
-334
-225
-193
-345
-224
-299
-110
-414
-252
-302
-142
-239
-376
-54
-227
-126
-154
-263
-18
-387
-214
-129
-163
-151
-325
-401
-382
-329
-288
-283
-376
-211
-221
-448
-292
-187
-76
-84
-342
-162
-251
-110
-66
-349
-435
-380
-82
-281
-29
-61
-402
-287
-118
-428
-429
-403
-324
-391
-203
-374
-397
-352
-462
-440
-89
-209
-133
-436
-187
-142
-299
-402
-210
-217
-50
-456
-177
-335
-204
-338
-146
-82
-379
-332
-148
-370
-188
-42
-351
-219
-89
-129
-388
-42
-338
-169
-104
-508
-43
-432
-99
-484
2
-461
-469
-151
-279
-309
-121
-306
-210
-302
-100
-415
-307
2
-111
-432
-457
-299
-95
-327
-508
-327
-211
-319
-83
-340
-474
-160
-494
-351
-177
-514
-198
-177
-45
-364
-232
-432
-137
-467
-11
-253
-237
-367
-42
-442
-14
-323
-489
-466
-389
-362
-195
-110
-170
-394
-234
-296
-296
-469
-275
-2
-413
-149
-477
-543
-435
-255
-259
-152
-73
-47
-72
-252
-499
-305
-169
-406
-280
-287
-43
-20
-242
-271
-336
-500
-341
-354
-559
-364
-126
-173
-444
-555
-532
-532
-369
-468
-315
-469
-506
-151
-202
-459
-139
-434
-383
-353
-13
-272
-517
-629
-573
-502
-337
-454
-376
-288
-430
-503
-482
-327
-418
-623
-576
-412
-416
-457
-84
-251
-466
-520
-262
-642
-329
-308
-145
-391
-189
-226
-48
-167
-626
-325
-288
-432
-615
-149
-414
-387
-622
-260
-200
-483
-531
-22
-82
-308
-593
-271
-134
-431
-190
-460
-434
-558
-166
-136
-404
-10
-225
-397
-375
-371
-654
-374
-137
-659
-413
-117
-602
-585
-601
-451
-171
-296
-437
-505
-675
-153
-286
-28
-515
-221
-124
-662
-516
-119
-390
-78
-372
-490
-403
-341
-623
-264
-672
-94
-238
-250
-382
-526
-360
-170
-109
-228
-226
-70
-519
-481
-174
-471
-9
-497
-488
-337
-729
-72
-489
-717
-426
-159
-436
-600
-84
-1
-742
-258
-346
-205
-427
-479
-243
-358
-90
-482
-471
-234
-131
-108
-670
-740
-748
-427
-563
-691
-354
-427
-755
-708
-389
-741
-125
-723
-274
-464
-223
-497
-182
-167
-83
-387
-464
-195
-131
-161
-213
-671
-491
-66
-138
-121
-498
-408
-429
-643
-803
-118
-561
-217
-282
-400
-396
-434
-501
-134
-409
-162
-696
-14
-269
-663
-531
-620
-208
-71
-511
-421
-371
-797
-454
-273
-167
-261
-618
-769
-738
-71
-239
-117
-204
-149
-820
-222
-337
-383
-181
-433
-765
-367
-286
-152
-59
-673
-333
-238
-121
-16
-614
-630
-196
-306
-703
-363
-296
-366
-515
-673
-90
-421
-474
-794
-522
-842
-185
-732
-642
-830
-19
-735
-153
-814
-654
-550
-175
-626
-148
-661
-876
-601
-822
-692
-784
-761
-738
-144
-672
-16
-572
-484
-851
-849
-41
-59
-700
-586
-323
-504
-156
-755
-408
-10
-228
-116
-174
-860
-837
-796
-392
-380
-403
-886
-360
-200
-38
-544
-448
-281
-218
-132
-571
-650
-666
-332
-130
-618
-306
-272
-95
-110
-804
-25
-61
-114
-369
-675
-58
-341
-543
-477
-936
-617
-684
-803
-40
-285
-919
-72
-685
-318
-107
-210
-926
-600
-130
-707
-355
-221
-951
-687
-599
-745
-889
-10
-188
-687
-191
-789
-44
-774
-53
-738
-889
-332
-575
-838
-975
-224
-720
-910
-478
-35
-740
-549
-911
-624
-596
-865
-485
-476
-348
-664
-674
-597
-839
-698
-746
-527
-95
-623
-662
-795
-287
-969
-21
-730
-191
-866"""
jump_list = [int(x) for x in INPUT.split("\n")]
current_index = 0
steps_taken = 0
while 0 <= current_index < len(jump_list):
current_jump = jump_list[current_index]
jump_list[current_index] += 1
current_index += current_jump
steps_taken += 1
print("V1 Final index: %d, steps taken: %d" % (current_index, steps_taken))
jump_list = [int(x) for x in INPUT.split("\n")]
current_index = 0
steps_taken = 0
while 0 <= current_index < len(jump_list):
current_jump = jump_list[current_index]
if current_jump >= 3:
jump_list[current_index] -= 1
else:
jump_list[current_index] += 1
current_index += current_jump
steps_taken += 1
print("V2 Final index: %d, steps taken: %d" % (current_index, steps_taken))
|
class ApiError(Exception):
pass
class AuthorizationFailed(Exception):
pass
|
s = 'one two one two one'
print(s.replace('one', 'two').replace('two', 'one'))
# one one one one one
print(s.replace('one', 'X').replace('two', 'one').replace('X', 'two'))
# two one two one two
def swap_str(s_org, s1, s2, temp='*q@w-e~r^'):
return s_org.replace(s1, temp).replace(s2, s1).replace(temp, s2)
print(swap_str(s, 'one', 'two'))
# two one two one two
print(s.replace('o', 't').replace('t', 'o'))
# one owo one owo one
print(s.translate(str.maketrans({'o': 't', 't': 'o'})))
# tne owt tne owt tne
print(s.translate(str.maketrans('ot', 'to')))
# tne owt tne owt tne
|
# TODO: create functions for data sending
async def send_data(event, buttons):
pass
|
n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
c = input().split()
if c[0] == "update":
s.update(set(map(int, input().split())))
elif c[0] == "intersection_update":
s.intersection_update(set(map(int, input().split())))
elif c[0] == "difference_update":
s.difference_update(set(map(int, input().split())))
else:
s.symmetric_difference_update(set(map(int, input().split())))
print(sum(s)) |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def right_view_util(root, max_level, level):
if not root:
return
if max_level[0] < level:
print(root.val)
max_level[0] = level
right_view_util(root.right, max_level, level+1)
right_view_util(root.left, max_level, level+1)
def right_view(root):
max_level = [0]
right_view_util(root, max_level, 1)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
right_view(root)
|
"""Tabuada de um inteiro"""
# Uso dos operadores aritméticos
num = int(input('Digite um número: '))
inicio = 'Resultado'
fim = 'Fim'
print()
print('{:=^25}'.format(inicio))
print()
print(f'{num} x 0 = {num*0}\n'
f'{num} x 1 = {num*1}\n'
f'{num} x 2 = {num*2}\n'
f'{num} x 3 = {num*3}\n'
f'{num} x 4 = {num*4}\n'
f'{num} x 5 = {num*5}\n'
f'{num} x 6 = {num*6}\n'
f'{num} x 7 = {num*7}\n'
f'{num} x 8 = {num*8}\n'
f'{num} x 9 = {num*9}\n'
f'{num} x 10 = {num*10}')
print()
print('{:=^25}'.format(fim))
|
def removeDuplicates(nums):
"""
:type nums: List[int] - sorted
:rtype: List[int]
"""
i = 0
for j in range(len(nums)):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
return nums[0: i + 1]
print(removeDuplicates([1, 1, 2, 3, 3, 3, 5]))
print(removeDuplicates([])) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# # https://oj.leetcode.com/problems/symmetric-tree
# Given a binary tree, check whether it is a mirror of itself
# (ie, symmetric around its center).
# For example, this binary tree is symmetric:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
#
# But the following is not:
# 1
# / \
# 2 2
# \ \
# 3 3
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
def isSym(L, R):
if not L and not R:
return True
if L and R and L.val == R.val:
return isSym(L.left, R.right) and isSym(L.right, R.left)
return False
return isSym(root, root)
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
tree = \
TreeNode(1,
TreeNode(2,
TreeNode(3),
TreeNode(4) \
),
TreeNode(2,
TreeNode(4),
TreeNode(3)
)
)
s = Solution()
r = s.isSymmetric(tree)
print(r)
|
'''
Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão:
1 - binário
2 - octal
3 - hexadecimal
'''
'''
n = int(input('Número inteiro: '))
escolha = (int(input('Conversor:\n'
'1 - Binário\n'
'2 - Octal\n'
'3 - Hexadecimal\n'
'Escolha: ')))
if escolha == 1:
list.count(n)
for x in range (len(n)):
n1 = n / 2
if n1 % 2 == 0:
n2 = 0
elif n % 2 != 0:
n2 = 1
print('{}'.format(n2))
if escolha == 2:
n1 = n // 64
n2 = n - n1 * 64
n3 = n2 // 8
n4 = n2 - n3 * 8
print('Hexadecimal de {} = {}{}{}'.format(n, n1, n3, n4))
if escolha == 3:
n1 = n // 16
n2 = n - n1 * 16
if n1 == 10:
n1 = 'A'
elif n1 == 11:
n1 = 'B'
elif n1 == 12:
n1 = 'C'
elif n1 == 13:
n1 = 'D'
elif n1 == 14:
n1 = 'E'
elif n1 == 15:
n1 = 'F'
print('{}{}'.format(n1, n2))'''
a = int(input('N: '))
print('Octal: {}\n'
'Binary: {}\n'
'Hexadecimal: {}'.format(oct(a), bin(a), hex(a)))
|
# These regexes must not include line anchors ('^', '$'). Those will be added by the
# ValidateRegex library function and anybody else who needs them.
NAME_VALIDATION = r"(?P<name>[@\-\w\.]+)"
# This regex needs to exactly match the above, EXCEPT that the name should be "name2". So if the
# above regex changes, change this one. This is kind of gross. :\
NAME2_VALIDATION = r"(?P<name2>[@\-\w\.]+)"
# Regexes for validating permission/argument names
PERMISSION_VALIDATION = r"(?P<name>(?:[a-z0-9]+[_\-\.])*[a-z0-9]+)"
PERMISSION_WILDCARD_VALIDATION = r"(?P<name>(?:[a-z0-9]+[_\-\.])*[a-z0-9]+(?:\.\*)?)"
ARGUMENT_VALIDATION = r"(?P<argument>|\*|[\w=+/.:-]+\*?)"
# Global permission names to prevent stringly typed things
PERMISSION_GRANT = "grouper.permission.grant"
PERMISSION_CREATE = "grouper.permission.create"
PERMISSION_AUDITOR = "grouper.permission.auditor"
AUDIT_MANAGER = "grouper.audit.manage"
AUDIT_VIEWER = "grouper.audit.view"
# Permissions that are always created and are reserved.
SYSTEM_PERMISSIONS = [
(PERMISSION_CREATE, "Ability to create permissions within Grouper."),
(PERMISSION_GRANT, "Ability to grant a permission to a group."),
(PERMISSION_AUDITOR, "Ability to own or manage groups with audited permissions."),
(AUDIT_MANAGER, "Ability to start global audits and view audit status."),
(AUDIT_VIEWER, "Ability to view audit results and status."),
]
# Used to construct name tuples in notification engine.
ILLEGAL_NAME_CHARACTER = '|'
# A list of regular expressions that are reserved anywhere names are created. I.e., if a regex
# in this list is matched, a permission cannot be created in the UI. Same with group names.
# These are case insensitive.
RESERVED_NAMES = [
r"^grouper",
r"^admin",
r"^test",
r"^[^.]*$",
r"^[0-9]+$", # Reserved in order to select user or group by id.
r".*\|.*",
]
# Maximum length a name can be. This applies to user names and permission arguments.
MAX_NAME_LENGTH = 128
|
def check(n):
sqlist = str(n**2)# list(map(int,str(n**2)))
l = len(sqlist)
if l%2 == 0: #if even
rsq = int(sqlist[l//2:])
lsq = int(sqlist[:l//2])
else:
rsq = int(sqlist[(l-1)//2:])
if l!= 1:
lsq = int(sqlist[:(l-1)//2])
else:
lsq = 0 #only lsq can have an empty list
if rsq + lsq == n:
return True
p = int(input())
q = int(input())
ans = []
for i in range(p, q+1):
if check(i) == True:
ans.append(i)
if len(ans)!= 0:
for i in ans:
print(i, end =' ')
else:
print('INVALID RANGE')
#for i in [1,9,45,55,99]:
#print(check(i))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Ben Poile'
SITENAME = 'blog'
SITEURL = 'https://poiley.github.io'
# GITHUB_URL = 'https://github.com/poiley/poiley.github.io'
PATH = 'content'
OUTPUT_PATH = 'output'
STATIC_PATHS = ['articles', 'downloads']
ARTICLE_PATHS = ['articles',]
ARTICLE_URL = 'articles/{date:%Y}/{date:%m}/{slug}.html'
ARTICLE_SAVE_AS = 'articles/{date:%Y}/{date:%m}/{slug}.html'
TIMEZONE = 'America/Los_Angeles'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blog Roll
LINKS = (('Home', 'https://poile.dev/'),
('All Posts', 'https://www.python.org/'),
('Resume', 'https://docs.google.com/document/d/1T2MaWT8CHgR9t5hDoQqLDpXZYJ5eKKwgfJBa2nVceo0/edit?usp=sharing'))
# Social widget
SOCIAL = (('Github', 'https://github.com/poiley'),
('Spotify', 'https://open.spotify.com/user/qqxne71rxqru593o2cg1y8avg?si=fb593f2b738f4402'),
('Twitter', 'https://twitter.com/_poile_'))
DEFAULT_PAGINATION = 3
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
THEME = 'theme'
#DIRECT_TEMPLATES = (('index', 'blog', 'tags', 'categories', 'archives'))
#PAGINATED_DIRECT_TEMPLATES = (('blog', ))
#TEMPLATE_PAGES = {'home.html': 'index.html',}
|
class SomethingAbstract:
property_a: str
property_b: str
property_c: Optional[str]
property_d: Optional[str]
def __init__(
self,
property_a: str,
property_b: str,
property_c: Optional[str] = None,
property_d: Optional[str] = None,
) -> None:
self.property_a = property_a
self.property_b = property_b
self.property_c = property_c
self.property_d = property_d
class Something(SomethingAbstract):
property_e: str
property_f: str
property_g: Optional[str]
property_h: Optional[str]
# NOTE (mristin, 2022-03-25):
# The order of the inherited and defined properties do not match the order of
# the constructor arguments.
def __init__(
self,
property_e: str,
property_f: str,
property_a: str,
property_b: str,
property_g: Optional[str] = None,
property_h: Optional[str] = None,
property_c: Optional[str] = None,
property_d: Optional[str] = None,
) -> None:
SomethingAbstract.__init__(
self,
property_a=property_a,
property_b=property_b,
property_c=property_c,
property_d=property_d,
)
self.property_e = property_e
self.property_f = property_f
self.property_g = property_g
self.property_h = property_h
__book_url__ = "dummy"
__book_version__ = "dummy"
|
# Modifique o programa para trabalhar com duas filas
# Para facilitar seu trabalho, considere o comando A para atendimento da fila 1; e B, para atendimento da fila 2
# O mesmo para a chegada de clientes: F para fila 1; e G, para fila 2
def line(size):
print('-' * size)
last = 10
queue1 = list(range(1, last + 1))
queue2 = list(range(1, last + 1))
while True:
print()
line(70)
print(f'Existem {len(queue1)} clientes na FILA 1')
print(f'Fila atual: {queue1}')
line(70)
print(f'Existem {len(queue2)} clientes na FILA 2')
print(f'Fila atual: {queue2}')
line(70)
print('\nAdicionar cliente na fila:')
print(' - Digite F para adicionar na fila 1, e G para adicionar na fila 2')
print('Atendimento:')
print(' - Digite A para atender da fila 1, e B para atender da fila 2')
print('Sair do programa:')
print(' - Digite S')
operation = str(input('\nOperação (F, G, A, B ou S): ')).strip().upper()
counter = 0
leave = False
while counter < len(operation):
if operation[counter] == 'A':
if len(queue1) > 0:
attended = queue1.pop(0)
print(f'\nCliente {attended} da FILA 1 atendido')
else:
print(f'Fila 1 vazia! Ninguém para atender.')
elif operation[counter] == 'B':
if len(queue2) > 0:
attended = queue2.pop(0)
print(f'\nCliente {attended} da FILA 2 atendido.')
else:
print(f'Fila 2 vazia! Ninguém para atender.')
elif operation[counter] == 'F':
last = len(queue1) + 1
queue1.append(last)
print('\nChegou um cliente ao final da fila 1.')
print(f'Existem {len(queue1)} clientes na fila 1.')
print(f'Fila atual: {queue1}')
elif operation[counter] == 'G':
last = len(queue2) + 1
queue2.append(last)
print('\nChegou um cliente ao final da fila 2.')
print(f'Existem {len(queue2)} clientes na fila 2.')
print(f'Fila atual: {queue2}')
elif operation[counter] == 'S':
leave = True
break
else:
print('\nOperação inválida! Digite apenas F, A ou S!')
counter += 1
if leave:
break
print('\nFim da execução!')
|
#soma=0
#for c in range(3,501,6):
# soma=soma+c
#print(soma)
#ou
soma = 0
cont = 0
for c in range(1,501,2):
if c % 3 == 0:
soma += c # soma = soma+ c
cont += 1 # cont = cont + 1
print('a soma de todos os {} valores é {}'.format(cont,soma))
|
nomeCompleto = input('Digite seu nome completo: ').strip().split()
print('O seu primeiro nome é: {}'.format(nomeCompleto[0]))
#forma 1
print('O seu último nome é: {}'.format(nomeCompleto[-1]))
#forma 2
#print('O seu último nome é: {}'.format((nomeCompleto[len(nomeCompleto)-1])))
|
text = open("subInfo.txt").read()
def findCount(sub):
count = 0
terms = open(sub).readlines()
terms = [t.strip().lower() for t in terms]
for t in terms:
if t in text:
count += 1
return count
subArr = []
subArr.append((findCount("biology_terms.txt"), "biology_terms.txt"))
subArr.append((findCount("chemistry_terms.txt"), "chemistry_terms.txt"))
subArr.append((findCount("History_terms.txt"), "History_terms.txt"))
subArr.append((findCount("physics_terms.txt"), "physics_terms.txt"))
subArr.append((findCount("math_terms.txt"), "math_terms.txt"))
subArr = sorted(subArr)[::-1]
print(subArr)
print(subArr[0][1])
|
dia=input ('Dia =')
mês=input ('mês =')
ano=input ('ano =')
print ('Você nasceu no dia',dia,'de',mês,'de',ano,'.''Correto?')
|
class eAxes:
xAxis, yAxis, zAxis = range(3)
class eTurn:
learner, simulator = range(2)
class eEPA:
evaluation, potency, activity = range(3)
evaluationSelf, potencySelf, activitySelf,\
evaluationAction, potencyAction, activityAction,\
evaluationOther, potencyOther, activityOther = range(9)
fundamental, tau = range(2)
class eIdentityParse:
identity, maleEvaluation, malePotency, maleActivity,\
femaleEvaluation, femalePotency, femaleActivity, institution = range(8)
class eAgentListBoxParam:
identity, maleSentiment, femaleSentiment, institution = range(4)
class eInstitutions:
gender, institution, undefined = range(3)
class eInteractants:
agent, client = range(2)
class eGender:
male, female = range(2)
class eGenderKey:
anyGender, male, female = range(3)
class eGui:
simulator, interactive = range(2)
class eRect:
fromLeft, fromBottom, fractionOfX, fractionOfY = range(4) |
"""
MyMCAdmin system
"""
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: Alan
@time: 2021/05/18
"""
|
cars=["Maruthi","Honda","TataIndica"]
x = cars[0]
print("x=\n",x)
cars[0]="Ford"
print("cars=\n",cars)
L = len(cars)
print("Length of cars=",L)
#Print each item in the car array
for y in cars:
print(y)
cars.append("BMW")
print("cars=\n",cars)
#Delete the second element of the cars array
cars.pop(1)
print("cars=\n",cars)
#Delete the element that has the value "Honda"
cars.remove('TataIndica')
print("cars=\n",cars)
#Result
##x= Maruthi
##cars= ['Ford', 'Honda', 'TataIndica']
##Length of cars= 3
##Ford
##Honda
##TataIndica
##cars= ['Ford', 'Honda', 'TataIndica', 'BMW']
##cars= ['Ford', 'TataIndica', 'BMW']
##cars= ['Ford', 'BMW']
|
guests = ["Mark", "Kevin", "Mellisa"]
msg = "I'd like to invite you to have a dinner with us on 5/18. Thanks, Andrew"
print(f"Hi {guests[0]}, {msg}")
print(f"Hi {guests[1]}, {msg}")
print(f"Hi {guests[2]}, {msg}")
print(f"\nSorry, {guests[1]} can't make it.\n")
guests[1] = "Ace"
print(f"Hi {guests[0]}, {msg}")
print(f"Hi {guests[1]}, {msg}")
print(f"Hi {guests[2]}, {msg}")
|
# Problem Set 1a
# Name: Eloi Gil
# Time Spent: 1
#
balance = float(input('balance: '))
annualInterestRate = float(input('annual interest rate: '))
minMonthlyPaymentRate = float(input('minimum monthly payment rate: '))
month = 0.0
while month < 12.0:
month += 1.0
print('Month ' + str(month))
minMonthlyPayment = round(balance * minMonthlyPaymentRate, 2)
print('minimum monthly payment: ' + str(minMonthlyPayment))
interestPaid = round(annualInterestRate / 12.0 * balance, 2)
principlePaid = round(minMonthlyPayment - interestPaid, 2)
print('principle paid: ' + str(principlePaid))
balance -= round(principlePaid, 2)
print('remaining balance: ' + str(round(balance, 2)))
|
s=0
for c in range(0,4):
n= int(input('Digite um valor: '))
s += n
print('Somatorio deu: {}' .format(s)) |
'''
__init__ :Python的初始化方法
'''
class Enemy:
def __init__(self):
print("this is init ")
enemy1=Enemy()
print("---------")
'''
带参的构造方法
'''
class Enemy2:
def __init__(self,x):
self.energy=x
def get_energy(self):
print(self.energy)
jsaon=Enemy2(2)
sandy=Enemy2(18)
jsaon.get_energy()
sandy.get_energy()
|
__title__ = 'DRF Exception Handler'
__version__ = '1.0.1'
__author__ = 'Thomas'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 Thomas'
# Version synonym
VERSION = __version__
|
{
"targets": [
{
"target_name": "boost-property_tree",
"type": "none",
"include_dirs": [
"1.57.0/property_tree-boost-1.57.0/include"
],
"all_dependent_settings": {
"include_dirs": [
"1.57.0/property_tree-boost-1.57.0/include"
]
},
"dependencies": [
"../boost-config/boost-config.gyp:*",
"../boost-serialization/boost-serialization.gyp:*",
"../boost-assert/boost-assert.gyp:*",
"../boost-optional/boost-optional.gyp:*",
"../boost-throw_exception/boost-throw_exception.gyp:*",
"../boost-core/boost-core.gyp:*",
"../boost-spirit/boost-spirit.gyp:*",
"../boost-static_assert/boost-static_assert.gyp:*",
"../boost-multi_index/boost-multi_index.gyp:*",
"../boost-mpl/boost-mpl.gyp:*",
"../boost-any/boost-any.gyp:*",
"../boost-iterator/boost-iterator.gyp:*"
]
} ,
# note the json parser is the only part of boost-property_tree
# using boost-spirit
{
"target_name": "boost-property_tree_test_json_parser",
"type": "executable",
"test": {},
"sources": [ "1.57.0/property_tree-boost-1.57.0/test/test_json_parser.cpp" ],
"dependencies": [ "boost-property_tree"],
# this disables building the example on iOS
"conditions": [
["OS=='iOS'",
{
"type": "none"
}
],
["OS=='mac'",
{
"type": "none"
}
]
]
}
]
}
|
def movewhile():
"""Kara geht solange einen Schritt wie kein Baum vor ihr ist"""
# Wenn vor Kara kein Baum ist geht sie einen Schritt
# und ruft danach solange sich selbst auf, wie vor
# ihr kein Baum ist.
if not kara.treeFront():
kara.move()
movewhile()
else:
pass
def main():
"""Main-Funktion (Führt Programm aus)"""
# "Geradeaus gehen"
movewhile()
kara.turnLeft()
# "Nach oben gehen"
movewhile()
# Von Aufgabe definierte Endposition einnehmen
kara.turnRight()
kara.turnRight()
# Bringe mia de Stein innett Rolle...
main() |
"""
hello_world.py
Simple Hello World program.
ECE196 Face Recognition Project
Author: Will Chen
1. Write a Write a program that prints "Hello World!" and uses the main function convention.
"""
# TODO: Write a program that prints "Hello World!" and uses a main function.
def main():
print("Hello World!")
if(__name__ == '__main__'):
main()
|
def between_markers(text,mark1,mark2):
'''
You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions.
This is a simplified version of the Between Markers mission.
The initial and final markers are always different.
The initial and final markers are always 1 char size.
The initial and final markers always exist in a string and go one after another.
Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers.
Output: A string.
Precondition: There can't be more than one final and one initial markers.
'''
if mark1 and mark2 in text:
i1 = text.index(mark1)
i2 = text.index(mark2)
if i1<i2:
return text[text.index(mark1)+1:text.index(mark2)]
if __name__ == '__main__':
print('Example:')
print(between_markers('What is >apple<', '>', '<'))
print(between_markers('What is [apple]', '[', ']'))
print(between_markers('What is ><', '>', '<'))
print(between_markers('>apple<', '>', '<'))
print(between_markers('an -apologize> to read', '-', '>'))
|
# Copyright (C) 2017 Tiancheng Zhao, Carnegie Mellon University
class KgCVAEConfig(object):
description= None
use_hcf = True # use dialog act in training (if turn off kgCVAE -> CVAE)
update_limit = 3000 # the number of mini-batch before evaluating the model
# how to encode utterance.
# bow: add word embedding together
# rnn: RNN utterance encoder
# bi_rnn: bi_directional RNN utterance encoder
sent_type = "bi_rnn"
# latent variable (gaussian variable)
latent_size = 200 # the dimension of latent variable
full_kl_step = 10000 # how many batch before KL cost weight reaches 1.0
dec_keep_prob = 1.0 # do we use word drop decoder [Bowman el al 2015]
# Network general
cell_type = "gru" # gru or lstm
embed_size = 200 # word embedding size
topic_embed_size = 30 # topic embedding size
da_embed_size = 30 # dialog act embedding size
cxt_cell_size = 600 # context encoder hidden size
sent_cell_size = 300 # utterance encoder hidden size
dec_cell_size = 400 # response decoder hidden size
backward_size = 10 # how many utterance kept in the context window
step_size = 1 # internal usage
max_utt_len = 40 # max number of words in an utterance
num_layer = 1 # number of context RNN layers
# Optimization parameters
op = "adam"
grad_clip = 5.0 # gradient abs max cut
init_w = 0.08 # uniform random from [-init_w, init_w]
batch_size = 30 # mini-batch size
init_lr = 0.001 # initial learning rate
lr_hold = 1 # only used by SGD
lr_decay = 0.6 # only used by SGD
keep_prob = 1.0 # drop out rate
improve_threshold = 0.996 # for early stopping
patient_increase = 2.0 # for early stopping
early_stop = True
max_epoch = 60 # max number of epoch of training
grad_noise = 0.0 # inject gradient noise?
|
# Cast to int
x = int(100) # x will be 100
y = int(5.75) # y will be 5
z = int("32") # z will be 32
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
# cast to float
a = float(100) # x will be 100.0
b = float(5.75) # y will be 5.75
c = float("32") # z will be 32.0
d = float("32.5") # z will be 32.5
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
# cast to str
s1 = str("s1") # will be "s1"
s2 = str(100) # will be "100"
s3 = str(5.75) # will be "5.75"
print(s1)
print(s2)
print(s3)
print(type(s1))
print(type(s2))
print(type(s3))
# concatenate number (int/float) with str, bust be explicit casting
result = "The result is: " + str(b)
print(result)
|
class MetadataHolder():
def set_metadata(self, key, value):
self.client.api.call_function('set_metadata', {
'entity_type': self._data['type'],
'entity_id': self.id,
'key': key,
'value': value
})
def set_metadata_dict(self, metadata_dict):
self.client.api.call_function('set_metadata_dict', {
'entity_type': self._data['type'],
'entity_id': self.id,
'metadata': metadata_dict,
})
def get_metadata(self):
return self.client.api.call_function('get_metadata', {
'entity_type': self._data['type'],
'entity_id': self.id,
})
|
"""VIMS generic errors."""
class VIMSError(Exception):
"""Generic VIMS error."""
class VIMSCameraError(VIMSError):
"""Generic VIMS Camera error."""
|
'''
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
Example 1:
Input: preorder = [5,2,1,3,6]
Output: true
Example 2:
Input: preorder = [5,2,6,1,3]
Output: false
'''
# Convert to Inorder and check if sorted or not
# TC O(N) and Space O(N)
class Solution(object):
def to_inorder(self, preorder):
# O(N) TC and O(N) Space
stack = deque()
inorder = []
for pre in preorder:
while stack and pre > stack[-1]:
inorder.append(stack.pop())
stack.append(pre)
while stack:
inorder.append(stack.pop())
return inorder
def verifyPreorder(self, preorder):
inorder = self.to_inorder(preorder)
for elem in range(1, len(inorder)):
if inorder[elem - 1] > inorder[elem]:
return False
return True
|
# -*-coding:utf-8-*-
"""
진법 변환 recursive 알고리즘
2 <= n <= 16까지 가능
"""
def convert(n,t):
T = "0123456789ABCDEF"
q,r = divmod(n, t)
if q ==0:
return T[r]
else:
return convert(q, t) + T[r]
"""
def test(n,t):
answer = ''
while t//n >= 1:
re = t%n
t = t//n
answer = str(re) + answer
print(answer)
if t < n:
answer = str(t) + answer
return int(answer)
"""
"""
# 진법 변환 함수 재도전
def convert_2(t, n):
s = 'ABCDEF'
a = ''
while t:
if t%n > 9:
a = s[t%n -10] + a
else:
a = str(t%n) + a
t = t//n
return a
""" |
'''
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
'''
# Since every node can only have one parent,
# in case we're inside a cycle the last node we visit
# will have 2 parents
# In the case we have an edge going in both directions
# we can just check if the number of parents of the current node and their
# childs is just equal to one
# In the case when we have 2 or more connected components, when we see
# A node that has no parent and it's different from 0 then we have found
# a connected component
def find_root(n, lC, rC): # The root can be any of the n nodes
aux_arr = [0]*n # See test case 36
# So first we have to find it
# We are just looking the node that No
# of parents == 0
for i in range(n):
l, r = lC[i], rC[i]
if l != -1:
aux_arr[l] += 1
if r != -1:
aux_arr[r] += 1
root = -1
for i in range(n):
if aux_arr[i] == 0:
root = i
break
return root
def validateBinaryTreeNodes(n, leftChild, rightChild):
root = find_root(n, leftChild, rightChild)
if root == -1:
return False
visited = [0]*n
queue = [root]
visited[root] = 1
while queue:
curr = queue.pop(0)
l, r = leftChild[curr], rightChild[curr]
if l != -1:
if visited[l] == 1:
return False
visited[l] = 1
queue.append(l)
if r != -1:
if visited[r] == 1:
return False
visited[r] = 1
queue.append(r)
for node in visited:
if node == 0:
return False
return True
|
# Nesse exemplo retorna uma lista ordenada
lista = [1,5,3,2,7,50,9]
def bubbleSort(list):
for i in range(len(list)):
for j in range(0, len(list) - 1 - i):
if (list[j] > list[j+1]):
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
return list
if __name__ == "__main__":
bubbleSort(lista) |
# General settings
HOST = "irc.twitch.tv"
PORT = 6667
COOLDOWN = 10 #Global cooldown for commands (in seconds)
# Bot account settings
PASS = "oauth:abcabcabcabcabcabcacb1231231231"
IDENT = "bot_username"
# Channel owner settings
CHANNEL = "channel_owner_username" #The username of your Twitch account (lowercase)
CHANNELPASS = "oauth:abcabcbaacbacbabcbac123456789" #The oauth token for the channel owner's Twitch account (the whole thing, including "oauth:")
GAMES = [['Sample Game', 'sg', 'Sample Platform', 'sp64'], ['Sample Game 2', 'sg2', 'Sample Platform', 'sp64']]
CATEGORIES = [['Sample Category 1', 'sample_1'], ['Sample Category 2', 'sample_2']]
SRC_USERNAME = CHANNEL
|
## Exercício 14 do livro Python 3 - Conceitos e Aplicações - Uma Abordagem Didática
""" Uso de condições simples: considerando os valores fornecidos, avalie cada condição e informe se o resultado é
falso (false) ou verdadeiro (true).
Para A = 0 e B = -3 -> condição = A > B
Para X = 3.7 -> condição X <= 10.0
Para A = 9 e B = 16 -> condição = A - B >= 0
Para A = 2, B = 4 e N = 10 -> condição = A * B < N
Para A = 3, B = 9 e C = 5 -> condição = 10 * A >= B * C
Para A = 3, B = 6 e C = 5 -> condição = 10 * A >= B * C
Para N = 7 -> Condição = N % 2 == 0
Para N = 8 -> Condição = N % 2 == 0
Para T = 'Morango' -> Condição T == 'Banana'
Para T = 'Morango' -> Condição T > 'Banana'"""
a = 0
b = -3
r = a > b
print("Para A = 0 e B = -3, a condição A > B retorna: {}".format(r))
print("")
x = 3.7
r = x <= 10.0
print("Para X = 3.7, a condição X <= 10.0 retorna: {}".format(r))
print("")
a = 9
b = 16
r = a - b >= 0
print("Para A = 9 e B = 16, a condição A - B >= 0 retorna {}".format(r))
print("")
a = 2
b = 4
n = 10
r = a * b < n
print("Para A = 2, B = 4 e N = 10, a condição A * B < N retorna {}".format(r))
print("")
a = 3
b = 9
c = 5
r = 10 * a >= b * c
print("Para A = 3, B = 9 e C = 5, a condição 10 * A >= B * C retorna {}".format(r))
print("")
a = 3
b = 6
c = 5
r = 10 * a >= b * c
print("Para A = 3, B = 6 e C = 5, a condição 10 * A >= B * C retorna {}".format(r))
print("")
n = 7
r = n % 2 == 0
print("Para N = 7, a condição N % 2 == 0 retorna {}".format(r))
print("")
n = 8
r = n % 2 == 0
print("Para N = 8, a condição N % 2 == 0 retorna {}".format(r))
print("")
t = 'morango'
r = t == 'banana'
print("Para T = Morango, a condição T == Banana retorna {}".format(r))
print("")
t = 'morango'
r = t > 'banana'
print("Para T = Morango, a condição T > Banana retorna {}".format(r))
|
class Health(object):
"""
Represents a Health object used by the HealthDetails resource.
"""
def __init__(self, status, environment, application, timestamp):
self.status = status
self.environment = environment
self.application = application
self.timestamp = timestamp
|
def generate_data_replace_string():
'''
为了将日期字符串 /2/5 转换成 0205这样,
构建一个map,key为原始字符串,value为目标字符串
:return:
date_replace_str_map
'''
ori_str_list = []
new_str_list = []
for idx in range(1,9):
str_num = '/'+str(idx);
new_str_num = '0'+str(idx);
ori_str_list.append(str_num);
new_str_list.append(new_str_num);
ori_str_map = {k:v+1 for v,k in enumerate(ori_str_list)}
date_replace_str_map= {k:new_str_list[idx] for idx,k in enumerate(ori_str_map.keys())}
ori_str_list = []
new_str_list = []
for idx in range(10,32):
str_num = '/' + str(idx);
new_str_num = str(idx)
ori_str_list.append(str_num)
new_str_list.append(new_str_num)
ori_str_map = {k:v+1 for v,k in enumerate(ori_str_list)}
replace_str_map_part2= {k:new_str_list[idx] for idx,k in enumerate(ori_str_map.keys())}
for key in replace_str_map_part2.keys():
date_replace_str_map[key] = replace_str_map_part2.get(key)
#print(replace_str_map)
return date_replace_str_map
def generate_time_replace_string():
'''
为了将日期字符串 ' 0:05' 转换成 '0005' 这样,
构建一个map,key为原始字符串,value为目标字符串
:return:
time_replace_str_map
'''
ori_str_list = []
new_str_list = []
for idx in range(9):
str_num = ' '+str(idx) + ':';
new_str_num = '0'+str(idx);
ori_str_list.append(str_num);
new_str_list.append(new_str_num);
ori_str_map = {k:v+1 for v,k in enumerate(ori_str_list)}
time_replace_str_map= {k:new_str_list[idx] for idx,k in enumerate(ori_str_map.keys())}
ori_str_list = []
new_str_list = []
for idx in range(10,24):
str_num = ' ' + str(idx) + ':';
new_str_num = str(idx)
ori_str_list.append(str_num)
new_str_list.append(new_str_num)
ori_str_map = {k:v+1 for v,k in enumerate(ori_str_list)}
replace_str_map_part2= {k:new_str_list[idx] for idx,k in enumerate(ori_str_map.keys())}
for key in replace_str_map_part2.keys():
time_replace_str_map[key] = replace_str_map_part2.get(key)
#print(replace_str_map)
return time_replace_str_map |
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/1399/A
A. Remove Smallest
Couldn't Solve it myself, answer borrowed.
'''
for _ in range(int(input())):
n = int(input())
a = set(map(int, input().split()))
print('YES' if max(a)-min(a) < len(a) else 'NO')
|
N, *a = map(int, open(0).read().split())
i, j = 0, 0
c = 0
result = 0
while j < N:
if c <= N:
c += a[j]
j += 1
else:
c -= a[i]
i += 1
if c == N:
result += 1
while i < N:
c -= a[i]
i += 1
if c == N:
result += 1
print(result)
|
# test using cpu only
cpu = False
# type of network to be trained, can be bnn, full-bnn, qnn, full-qnn, tnn, full-tnn
network_type = 'full-qnn'
# bits can be None, 2, 4, 8 , whatever
bits=None
wbits = 4
abits = 4
# finetune an be false or true
finetune = False
architecture = 'RESNET'
# architecture = 'VGG'
dataset='CIFAR-10'
# dataset='MNIST'
if dataset == 'CIFAR-10':
dim=32
channels=3
else:
dim=28
channels=1
classes=10
data_augmentation=True
#regularization
kernel_regularizer=0.
kernel_initializer='glorot_uniform'
activity_regularizer=0.
# width and depth
nla=1
nfa=64
nlb=1
nfb=128
nlc=1
nfc=256
nres=3
pfilt=1
cuda="0"
#learning rate decay, factor => LR *= factor
decay_at_epoch = [0, 8, 12 ]
factor_at_epoch = [1, .1, .1]
kernel_lr_multiplier = 10
# debug and logging
progress_logging = 2 # can be 0 = no std logging, 1 = progress bar logging, 2 = one log line per epoch
epochs = 200
batch_size = 128
lr = 0.1
decay = 0.000025
date="00/00/0000"
# important paths
out_wght_path = './weights/{}_{}_{}b_{}b_{}_{}_{}_{}_{}_{}.hdf5'.format(dataset,network_type,abits,wbits,nla,nfa,nlb,nfb,nlc,nfc)
tensorboard_name = '{}_{}_{}b_{}b_{}_{}_{}_{}_{}_{}.hdf5'.format(dataset,network_type,abits,wbits,nla,nfa,nlb,nfb,nlc,nfc)
|
# JIG code from Stand-up Maths video "Why don't Jigsaw Puzzles have the correct number of pieces?"
def low_factors(n):
# all the factors which are the lower half of each factor pair
lf = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
lf.append(i)
return lf
def jig(w,h,n,b=0):
# percentage we'll check in either direction
threshold = 0.1
# the extra badness per piece
penalty = 1.005
ratio = max(w,h)/min(w,h) # switched to be greater than 1
print("")
print(f"{w} by {h} is picture ratio {round(ratio,4)}")
print("")
max_cap = int((1+threshold)*n)
min_cap = int((1-threshold)*n)
up_range = [i for i in range(n,max_cap+1)]
down_range = [i for i in range(min_cap,n)] # do not want n included again
down_range.reverse()
# start at 100 which is silly high and then move down.
up_best = 100
up_best_deets = []
down_best = 100
down_best_deets = []
# I am using the run marker so I know if looking above or below n
run = 0
for dis_range in [up_range,down_range]:
best_n = 0
best_n_ratio = 0
best_n_sides = []
if run == 0:
print(f"Looking for >= {n} solutions:")
print("")
else:
print("")
print("Just out of interest, here are smaller options:")
print("")
for i in dis_range:
this_best = 0
for j in low_factors(i):
j2 = int(i/j) # must be a whole number anyway
this_ratio = j2/j
if this_best == 0:
this_best = this_ratio
best_sides = [j,j2]
else:
if abs(this_ratio/ratio - 1) < abs(this_best/ratio - 1):
this_best = this_ratio
best_sides = [j,j2]
yes = 0
if best_n == 0:
yes = 1
else:
if abs(this_best/ratio - 1) < abs(best_n_ratio/ratio - 1):
yes = 1
if yes == 1:
best_n = i
best_n_ratio = this_best
best_n_sides = best_sides
piece_ratio = max(ratio,this_best)/min(ratio,this_best)
badness_score = (penalty**(abs(i-n)))*piece_ratio
if run == 0:
if badness_score < up_best:
up_best = badness_score
up_best_deets = [best_n,best_n_sides,best_n_ratio]
else:
if badness_score < down_best:
down_best = badness_score
down_best_deets = [best_n,best_n_sides,best_n_ratio]
print(f"{best_n} pieces in {best_n_sides} (grid ratio {round(best_n_ratio,4)}) needs piece ratio {round(piece_ratio,4)}")
if b==1:
print(f"[badness = {round(badness_score,5)}]")
print(f"for {n} the best is {best_n} pieces with size {best_n_sides}")
run += 1
print("")
print(f"If I had to guess: I think it's {up_best_deets[0]} pieces.")
if down_best < up_best:
print("")
print(f"BUT, fun fact, {down_best_deets[0]} would be even better.")
print("")
return 'DONE'
# I duplicated jig_v0 to make is easier to show in the video
def jig_v0(w,h,n,b=0):
# percentage we'll check in either direction
threshold = 0.1
penalty = 1.005
ratio = max(w,h)/min(w,h) # switched to be greater than 1
print("")
print(f"{w} by {h} is picture ratio {round(ratio,4)}")
print("")
max_cap = int((1+threshold)*n)
min_cap = int((1-threshold)*n)
up_range = [i for i in range(n,max_cap+1)]
down_range = [i for i in range(min_cap,n)] # do not want n included again
down_range.reverse()
# start at 100 which is silly high and then move down.
up_best = 100
up_best_deets = []
down_best = 100
down_best_deets = []
run = 0
for dis_range in [up_range,down_range]:
best_n = 0
best_n_ratio = 0
best_n_sides = []
if run == 0:
print(f"Looking for >= {n} solutions:")
print("")
else:
print("")
print("Just out of interest, here are smaller options:")
print("")
for i in dis_range:
this_best = 0
for j in low_factors(i):
j2 = int(i/j) # must be a whole number anyway
this_ratio = j2/j
if this_best == 0:
this_best = this_ratio
best_sides = [j,j2]
else:
if abs(this_ratio/ratio - 1) < abs(this_best/ratio - 1):
this_best = this_ratio
best_sides = [j,j2]
yes = 0
if best_n == 0:
yes = 1
else:
if abs(this_best/ratio - 1) < abs(best_n_ratio/ratio - 1):
yes = 1
if yes == 1:
best_n = i
best_n_ratio = this_best
best_n_sides = best_sides
piece_ratio = max(ratio,this_best)/min(ratio,this_best)
badness_score = (penalty**(abs(i-n)))*piece_ratio
if run == 0:
if badness_score < up_best:
up_best = badness_score
up_best_deets = [best_n,best_n_sides,best_n_ratio]
else:
if badness_score < down_best:
down_best = badness_score
down_best_deets = [best_n,best_n_sides,best_n_ratio]
print(f"{best_n} pieces in {best_n_sides} (grid ratio {round(best_n_ratio,4)}) needs piece ratio {round(piece_ratio,4)}")
if b==1:
print(f"[badness = {round(badness_score,5)}]")
run += 1
print("")
return 'DONE'
|
class Grandpa:
basketball = 1
class Dad(Grandpa):
dance = 1
def d(this):
return f"Yes I Dance {this.dance} no of times"
class Grandson(Dad):
dance = 6
def d(this):
return f"Yes I Dance AWESOMELY {this.dance} no of times"
jo = Grandpa()
bo = Dad()
po = Grandson()
# Everything DAD[OR GANDPA] HAS GOES TO SON TOO --
print(po.basketball)
print(po.d()) |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Coupon_validity, obj[4]: Gender, obj[5]: Age, obj[6]: Children, obj[7]: Education, obj[8]: Occupation, obj[9]: Income, obj[10]: Bar, obj[11]: Coffeehouse, obj[12]: Restaurant20to50, obj[13]: Direction_same, obj[14]: Distance
# {"feature": "Direction_same", "instances": 34, "metric_value": 0.9774, "depth": 1}
if obj[13]<=0:
# {"feature": "Passanger", "instances": 28, "metric_value": 1.0, "depth": 2}
if obj[0]<=2:
# {"feature": "Coupon", "instances": 18, "metric_value": 0.8524, "depth": 3}
if obj[2]<=3:
# {"feature": "Bar", "instances": 11, "metric_value": 0.994, "depth": 4}
if obj[10]<=1.0:
# {"feature": "Education", "instances": 7, "metric_value": 0.8631, "depth": 5}
if obj[7]<=1:
return 'True'
elif obj[7]>1:
# {"feature": "Gender", "instances": 3, "metric_value": 0.9183, "depth": 6}
if obj[4]<=0:
return 'False'
elif obj[4]>0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[10]>1.0:
return 'False'
else: return 'False'
elif obj[2]>3:
return 'False'
else: return 'False'
elif obj[0]>2:
# {"feature": "Occupation", "instances": 10, "metric_value": 0.469, "depth": 3}
if obj[8]<=9:
return 'True'
elif obj[8]>9:
# {"feature": "Time", "instances": 2, "metric_value": 1.0, "depth": 4}
if obj[1]<=0:
return 'True'
elif obj[1]>0:
return 'False'
else: return 'False'
else: return 'True'
else: return 'True'
elif obj[13]>0:
return 'True'
else: return 'True'
|
DOMAIN = "meross"
CONF_KEY = "key"
CONF_VALIDATE = "validate"
CONF_UUID = "uuid"
DEVICE_OFF = 0
DEVICE_ON = 1
LISTEN_TOPIC = '/appliance/{}/publish'
PUBLISH_TOPIC = '/appliance/{}/subscribe'
APP_METHOD_PUSH = "PUSH"
APP_METHOD_GET = "GET"
APP_METHOD_SET = "SET"
APP_SYS_CLOCK = "Appliance.System.Clock"
APP_SYS_ALL = "Appliance.System.All"
APP_CONTROL_TOGGLE = "Appliance.Control.Toggle"
APP_CONTROL_ELEC = "Appliance.Control.Electricity"
ATTR_VERSION = "version"
ATTR_MAC = "mac_addr"
ATTR_IP = "ip_addr"
ATTR_CURRENT_A = "current_a" |
#!/usr/bin/env python3
def main():
print( getProd2() )
print( getProd3() )
def getProd2():
with open( "expenses.txt" ) as f:
expenses = [ int( i.rstrip("\n") ) for i in f.readlines() ]
n = len( expenses )
for i in range( n ):
for j in range( i + 1, n ):
if expenses[ i ] + expenses[ j ] == 2020:
return( expenses[ i ] * expenses[ j ] )
def getProd3():
with open( "expenses.txt" ) as f:
expenses = [ int( i.rstrip("\n") ) for i in f.readlines() ]
n = len( expenses )
for i in range( n ):
for j in range( i + 1, n ):
for k in range( j + 1, n ):
if expenses[ i ] + expenses[ j ] + expenses[ k ] == 2020:
return( expenses[ i ] * expenses[ j ] * expenses[ k ] )
if __name__ == "__main__":
main()
|
class LinkedListIterator:
def __init__(self, beginning):
self._current_cell = beginning
self._first = True
def __iter__(self):
return self
def __next__(self):
try:
getattr(self._current_cell, "value")
except AttributeError:
raise StopIteration()
else:
if self._first:
self._first = False
return self._current_cell
self._current_cell = self._current_cell.next
if self._current_cell is None:
raise StopIteration()
else:
return self._current_cell.value
|
class groupcount(object):
"""Accept a (possibly infinite) iterable and yield a succession
of sub-iterators from it, each of which will yield N values.
>>> gc = groupcount('abcdefghij', 3)
>>> for subgroup in gc:
... for item in subgroup:
... print item,
... print
...
a b c
d e f
g h i
j
"""
def __init__(self, iterable, n=10):
self.it = iter(iterable)
self.n = n
def __iter__(self):
return self
def next(self):
return self._group(self.it.next())
def _group(self, ondeck):
yield ondeck
for i in xrange(1, self.n):
yield self.it.next()
|
'''https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1
Subarray with 0 sum
Easy Accuracy: 49.91% Submissions: 74975 Points: 2
Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanation:
2, -3, 1 is the subarray
with sum 0.
Example 2:
Input:
5
4 2 0 1 6
Output:
Yes
Explanation:
0 is one of the element
in the array so there exist a
subarray with sum 0.
Your Task:
You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n <= 104
-105 <= a[i] <= 105'''
# User function Template for python3
class Solution:
# Function to check whether there is a subarray present with 0-sum or not.
def subArrayExists(self, arr, n):
# Your code here
# Return true or false
s = set()
sum = 0
for i in range(n):
sum += arr[i]
if sum == 0 or sum in s:
return True
s.add(sum)
return False
# {
# Driver Code Starts
# Initial Template for Python 3
def main():
T = int(input())
while(T > 0):
n = int(input())
arr = [int(x) for x in input().strip().split()]
if(Solution().subArrayExists(arr, n)):
print("Yes")
else:
print("No")
T -= 1
if __name__ == "__main__":
main()
# } Driver Code Ends
|
all__ = ['jazPush', 'jazRvalue', 'jazLvalue', 'jazPop', 'jazAssign', 'jazCopy']
class jazPush:
def __init__(self):
self.command = "push"
def call(self, interpreter, arg):
interpreter.GetScope().stack.append(int(arg))
return None
class jazRvalue:
def __init__(self):
self.command = "rvalue"
def call(self, interpreter, arg):
value = interpreter.GetScope().GetVar(arg)
interpreter.GetScope().stack.append(value)
return None
class jazLvalue:
def __init__(self):
self.command = "lvalue"
def call(self, interpreter, arg):
address = interpreter.GetScope().GetAddress(arg)
interpreter.GetScope().stack.append(address)
return None
class jazPop:
def __init__(self):
self.command = "pop"
def call(self, interpreter, arg):
interpreter.GetScope().stack.pop()
return None
class jazAssign:
def __init__(self):
self.command = ":="
def call(self, interpreter, arg):
value = interpreter.GetScope().stack.pop()
addr = interpreter.GetScope().stack.pop()
interpreter.GetScope().SetVar(addr, value)
return None
class jazCopy:
def __init__(self):
self.command = "copy"
def call(self, interpreter, arg):
topStack = interpreter.GetScope().stack[-1]
interpreter.GetScope().stack.append(topStack)
return None
# A dictionary of the classes in this file
# used to autoload the functions
Functions = {'jazPush': jazPush, 'jazRvalue': jazRvalue, 'jazLvalue': jazRvalue, 'jazPop':jazPop, 'jazAssign':jazAssign, 'jazCopy':jazCopy}
|
l1 = int ( input (" primeiro lado ? " ))
l2 = int ( input (" Segundo lado ? " ))
l3= int ( input (" Terceiro lado ? " ))
if (l1 + l2) < l3 or (l2 + l3) < l1 or (l1 +l3) <l2:
print ('Não pode formar triângulo ')
elif (l1 + l2) > l3 or (l2 + l3) > l1 or (l1 +l3) > l2:
print ('Pode formar triângulo')
if (l1 == l2 ) and ( l2 == l3 ):
print ('Triângulo Isósceles ')
elif (l1 != l2 ) and ( l2 != l3):
print ('Triângulo Escaleno')
elif ( l1 == l2 ) or (l1 == l3) or ( l3 == l2):
print ('Triângulo Isósceles ') |
a = int(input())
length = 0
sum_of_sequence = 0
while a != 0:
sum_of_sequence += a
length += 1
a = int(input())
print(sum_of_sequence / length) |
lista = []
cont = 0
while True:
num = int(input('Digite um número: '))
cont += 1
lista.append(num)
resp = ' '
while resp not in 'SN':
resp = str(input('Deseja continuar? [S/N]: ')).upper().strip()[0]
if resp == 'N':
break
print('-=-' * 20)
print(f'Foram digitados {cont} números!!')
print(f'A lista ficou : {sorted(lista, reverse=True)}')
if 5 in lista:
print('O valor 5 ESTÁ na Lista!')
else:
print('O valor 5 NÃO esta na lista!')
|
def swap(i):
i = i.swapcase()
return i
if __name__ == "__main__":
s = input()
res = swap(s)
print(res)
|
"""
one area in which recursion shines is where we need to act on a problem
that has an arbitrary number of levels of depth.
A second area in which recursion shines is where
it is able to make a calculation based on a subproblem of the problem at hand.
steps to solving a recursive problem with sub-problems
1. Imagine the function you’re writing has already been implemented by
someone else.
2. Identify the subproblem of the problem.
3. See what happens when you call the function on the subproblem and go
from there.
""" |
class Cell(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
if (self.x < other.x):
return True
elif (self.x > other.x):
return False
elif (self.x == other.x):
return (self.y < other.y)
|
#
# CAMP
#
# Copyright (C) 2017 -- 2019 SINTEF Digital
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
class About:
PROGRAM = "CAMP"
VERSION = "0.7.0"
COMMIT_HASH = None
LICENSE = "MIT"
COPYRIGHT = "Copyright (C) 2017 -- 2019 SINTEF Digital"
DESCRIPTION = "Amplify your configuration tests!"
@staticmethod
def full_version():
if About.COMMIT_HASH:
return "%s-git.%s" % (About.VERSION, About.COMMIT_HASH[:7])
return About.VERSION
|
# Marcelo Campos de Medeiros
# ADS UNIFIP 2020.1
# Patos-PB 03/04/2020
'''
Dois carros (X e Y) partem em uma mesma direção. O carro X sai com velocidade constante de 60 Km/h e
o carro Y sai com velocidade constante de 90 Km/h.
Em uma hora (60 minutos) o carro Y consegue se distanciar 30 quilômetros do carro X, ou seja,
consegue se afastar um quilômetro a cada 2 minutos.
Leia a distância (em Km) e calcule quanto tempo leva (em minutos) para o carro Y tomar essa distância do outro carro.
Entrada
O arquivo de entrada contém um número inteiro.
Saída
Imprima o tempo necessário seguido da mensagem "minutos".
'''
x = 60
y = 90
d = int(input('d= '))
t = int((d / (y - x)) * 60)
print("{} minutos".format(t))
|
# SIMPLE FORMULA
# __________________________________________________________________________________________
# VARIABLE
# - Localize language: ID
textOpen=(
'Solve it! #1',
'Diketahui W=((X+YxZ)/(XxY))^Z'
)
textInX='Nilai X:'
textInY='Nilai Y:'
textInZ='Nilai Z:'
textOut='Nilai W adalah'
# __________________________________________________________________________________________
# PROGRAM
print(f'\n{textOpen[0]}\n\n{textOpen[1]}\n')
x=int(input(f'{textInX} '))
y=int(input(f'{textInY} '))
z=int(input(f'{textInZ} '))
w=((x+y*z)/(x*y))**z
print(f'{textOut} {w}') |
# I have used sieve of erato algorithm to solve this problem
def seive(Max):
primes = []
isprime = [False] * (Max)
maxN = Max
if maxN < 2:
return 0
if maxN >= 2:
isprime[0] = isprime[1] = True
for i in range(2, maxN):
if (isprime[i] is False):
for j in range(i * i, maxN, i):
isprime[j] = True
for i in range(Max):
if isprime[i] is False:
primes.append(i)
return len(primes)
class Solution:
def countPrimes(self, n: int) -> int:
return seive(n)
|
class FilterError(RuntimeError):
"""
This error is raised when a filter can never match on a given model class
"""
pass
class MultipleResultsError(RuntimeError):
"""
This filter is raised when multiple results are returned while a single
one was expected
"""
|
class Solution():
def isUnique(self, string: str):
'''Checks whether a given string has unique characters only
Inputs
------
string: str
string to be checked for unique chars
Assumptions
------------
Whitespace ' ' is a character
String is in ASCII-128
Returns
-------
bool
whether string has unique chars only
'''
if len(string) > 128:
return False
seen_chars = set()
for char in string:
if char in seen_chars:
return False
seen_chars.add(char)
return True
print(Solution().isUnique('the quick brown'))
# False
print(Solution().isUnique('the quickbrown'))
# True
|
class Page():
def __init__(self, parent, render):
self.__parent = parent
self.__render = render
def render(self):
return self.__render(self)
def parent(self):
return self.__parent
|
"""
* Assignment: File Write CSV
* Required: yes
* Complexity: medium
* Lines of code: 6 lines
* Time: 5 min
English:
1. Separate header from data
2. Write data to file `FILE`:
a. First line in file must be a header (first line of `DATA`)
b. For each row, convert it's values to `str`
c. Use coma (`,`) as a value separator
d. Add line terminator (`\n`) to each row
e. Save row values to file
8. Run doctests - all must succeed
Polish:
1. Odseparuj nagłówek od danych
2. Zapisz dane do pliku `FILE`:
a. Pierwsza linia w pliku musi być nagłówkiem (pierwsza linia `DATA`)
b. Dla każdego wiersza przekonwertuj jego wartości do `str`
c. Użyj przecinka (`,`) jako separatora wartości
d. Użyj `\n` jako koniec linii w każdym wierszu
e. Zapisz do pliku wartości z wiersza
8. Uruchom doctesty - wszystkie muszą się powieść
Hints:
* `','.join(...)`
* `[str(x) for x in ...]`
* Add newline `\n` at the end of line and file
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> from os import remove
>>> result = open(FILE).read()
>>> remove(FILE)
>>> print(result)
Sepal length,Sepal width,Petal length,Petal width,Species
5.8,2.7,5.1,1.9,virginica
5.1,3.5,1.4,0.2,setosa
5.7,2.8,4.1,1.3,versicolor
6.3,2.9,5.6,1.8,virginica
6.4,3.2,4.5,1.5,versicolor
4.7,3.2,1.3,0.2,setosa
<BLANKLINE>
"""
FILE = '_temporary.csv'
DATA = [
('Sepal length', 'Sepal width', 'Petal length', 'Petal width', 'Species'),
(5.8, 2.7, 5.1, 1.9, 'virginica'),
(5.1, 3.5, 1.4, 0.2, 'setosa'),
(5.7, 2.8, 4.1, 1.3, 'versicolor'),
(6.3, 2.9, 5.6, 1.8, 'virginica'),
(6.4, 3.2, 4.5, 1.5, 'versicolor'),
(4.7, 3.2, 1.3, 0.2, 'setosa'),
]
data = [[str(x) for x in y] for y in DATA]
data = [','.join(x) for x in data]
with open(FILE, mode='w') as file:
file.writelines('\n'.join(data) + '\n')
|
class Multiplication:
def __init__(self,matrix1,matrix2):
self.matrix1 = matrix1
self.matrix2 = matrix2
self.result = []
def ismultiplyable(self):
"""
INPUT: No Input
OUTPUT: ismultiplyable : bool
DESC: Can matrices be multiplied?
"""
if len(self.matrix1) == 0 or len(self.matrix2) == 0:
return False
else:
return True
def fill_result(self,col,row):
"""
INPUT: col: int
row: int
OUTPUT: No Output
DESC: Creates a col x row dimensional zero matrix.
"""
self.result=[[0 for i in range(col)] for j in range(row)]
def display_result(self):
"""
DESC: Display result matrix
"""
for r in self.result:
print(r)
|
# from astra import models
#
# class UserObject(models.Model):
# def
#
#
#
class MetaDemo(type):
pass
class Demo(metaclass=MetaDemo):
pass
d = Demo()
print(d.__class__.__metaclass__)
|
#!/usr/bin/env prey
async def main():
count = int(await x("ls -1 | wc -l"))
print(f"Files count: {count}")
|
g = int(input())
if g%2 == 0:
print("no. even")
else:
print("no. is odd")
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 20 12:25:06 2019
@author: abhij
"""
def circle_intersection(f1 = 0, f2 = 0, o1 = 0, o2 = 0, l1 = 0, l2 = 0):
R = (f1**2 + f2**2)**(0.5)
x_cor = f1 - o1
y_cor = f2 - o2
rot1 = (l1**2 - l2**2 + R**2)/(2*R)
print("\n l is", rot1)
rot2 = (l1**2 - rot1**2)**0.5
print("\n h is", rot2)
x = ((rot1/R) * (x_cor)) + ((rot2/R) * (y_cor)) + o1
y = ((rot1/R) * (y_cor)) - ((rot2/R) * (x_cor)) + o2
print("the x coordinate is:", x, "\n")
print("the y coordinate is:", y, "\n")
circle_intersection(2,3,0,0,4,5) |
def soma_elementos(lista):
soma = 0
for i in lista:
soma = soma + i
return soma
lista = [1,2,3,4,5,6]
print(soma_elementos(lista))
|
class str(object):
def __new__(self, *args):
if ___delta("num=", args.__len__(), 0):
return ""
else:
first_arg = ___delta("tuple-getitem", args, 0)
return first_arg.__str__()
def __init__(self, *args):
pass
def __len__(self):
int = ___id("%int")
return ___delta("strlen", self, int)
def __str__(self):
return self
def __add__(self, other):
str = ___id("%str")
return ___delta("str+", self, other, str)
def __mult__(self, other):
str = ___id("%str")
return ___delta("str*", self, other, str)
def __iter__(self):
SeqIter = ___id("%SeqIter")
return SeqIter(self)
def __eq__(self, other):
type = ___id("%type")
str = ___id("%str")
if not (type(other) is str):
return False
return ___delta("str=", self, other)
def __hash__(self):
int = ___id("%int")
return ___delta("str-hash", self, int)
def __cmp__(self, other):
int = ___id("%int")
return ___delta("strcmp", self, other, int)
def __in__(self, test):
return ___delta("strin", self, test)
def __min__(self):
str = ___id("%str")
return ___delta("strmin", self, str)
def __max__(self):
str = ___id("%str")
return ___delta("strmax", self, str)
def __list__(self):
int = ___id("%int")
range = ___id("%range")
l = ___delta("strlen", self, int)
return [self[i] for i in range(0, l)]
def __tuple__(self):
tuple = ___id("%tuple")
return tuple(self.__list__())
def __int__(self):
int = ___id("%int")
return ___delta("strint", self, int)
def __bool__(self):
return self.__len__() != 0
def __getitem__(self, idx):
str = ___id("%str")
return ___delta("str-getitem", self, idx, str)
def __slice__(self, lower, upper, step):
str = ___id("%str")
return ___delta("strslice", self, lower, upper, step, str)
___assign("%str", str)
|
# 9.2.2 Implementation with an Unsorted List
class PriorityQueueBase:
"""Abstract base class for a priority queue."""
class _Item:
"""Lightweight composite to store priority queue items."""
__slots__ = '_key','_value'
def __init__(self,k,v):
self._key = k
self._value = v
def __It__(self,other):
return self._key < other._key # compare items vased on their keys
def is_empty(self):
"""Return True if the priority queue is empty."""
return len(self) == 0
class UnsortedPriorityQueue(PriorityQueueBase):
"""A min-oriented priority queue implemented with an unsorted list."""
def _find_min(self): # nonpublic utility
"""Return Position of item with minimun key."""
if self.is_empty(): # is_empty inherited from base class
raise Empty('Priority queue is empty')
small = self._data.first()
walk = self._data.after(small)
while walk is not None:
if walk.element() < small.element():
small = walk
walk = self._data.after(walk)
return small
def __init__(self):
"""Create a new empty Priority Queue."""
self._data = PositionalList()
def __len__(self):
"""Return the number of the items in the priority queue."""
return len(self.data)
def add(self,key,value):
"""Add a key-value pair."""
self._data.add_last(self._Item(key,value))
def min(self):
"""Return but do not remove(k,v) tuple with minimum key."""
p = self._find_min()
item = p.element()
return (item._key,item._value)
def remove_min(self):
"""Remove and return (k,v) tuple with minimum key."""
p = self._find_min()
item = self._data.delete(p)
return (item._key,item._value)
#----------------------------- my main function ----------------------------- |
#!/usr/bin/python35
fp = open('hello.txt')
print('fp.tell = %s' % (fp.tell()))
fp.seek(10, SEEK_SET)
print('fp.seek(10), fp.tell() = %s' % (fp.tell()))
# only do zero cur-relative seeks
fp.seek(0, SEEK_CUR)
print('fp.seek(0, 1), fp.tell() = %s' % (fp.tell()))
fp.seek(0, SEEK_END)
print('fp.seek(0, 2), fp.tell() = %s' % (fp.tell()))
|
'''
Created on 02-06-2011
@author: Piotr
'''
class GeneratorInterval(object):
'''
Describes the interval in for generating the image.
@attention: DTO
'''
def __init__(self, start, stop, step=0):
'''
Constructor.
@param start: starting point of the interval
@param stop: stopping point of the interval
@param step: step used in this interval.
If step is 0 then only one element should be generate equal to start
'''
self.start = start
self.stop = stop
self.step = step
def __str__(self):
string = "Start: " + str(self.start) + '\n'
string += "Stop: " + str(self.stop) + '\n'
string += "Step: " + str(self.step) + '\n'
return string
def __eq__(self, o):
if isinstance(o, GeneratorInterval):
return o.start == self.start and o.stop == self.stop and o.step == self.step
return False
def __ne__(self, o):
return not self == o
|
with open('8.input') as inputFile:
data = [b.split(' ') for b in [a.rstrip('\n').split(' | ')[1] for a in inputFile.readlines()]]
result = 0
for d in data:
for e in d:
if len(e) in [2,3,4,7]:
result += 1
print(result)
|
def main():
message = input("Introducir Mensaje: ")
key = int(input("Key [1-26]: "))
mode = input("Cifrar o Descifrar [c/d]: ")
if mode.lower().startswith('c'):
mode = "cifrar"
elif mode.lower().startswith('d'):
mode = "descifrar"
translated = encdec(message, key, mode)
if mode == "cifrar":
print(("Mensaje Cifrado:", translated))
elif mode == "descifrar":
print(("Mensaje Descifrado:", translated))
def encdec(message, key, mode):
translated = ""
letters_my = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
letters_mn = "abcdefghijklmnopqrstuvwxyz"
for symbol in message:
if symbol in letters_my:
num = letters_my.find(symbol)
if mode == "cifrar":
num = num + key
elif mode == "descifrar":
num = num - key
if num >= len(letters_my):
num -= len(letters_my)
elif num < 0:
num += len(letters_my)
translated += letters_my[num]
elif symbol in letters_mn:
num = letters_mn.find(symbol)
if mode == "cifrar":
num = num + key
elif mode == "descifrar":
num = num - key
if num >= len(letters_mn):
num -= len(letters_mn)
elif num < 0:
num += len(letters_mn)
translated += letters_mn[num]
else:
translated += symbol
return translated
main()
|
# Problem statement
# write a program to swap two numbers without using third variable
x = input()
y = input()
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
x, y = y, x
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
# sample input
# 10
# 20
# sample output
# Before swapping:
# Value of x : 10 and y : 20
# After swapping:
# Value of x : 20 and y : 10
# Time complexity : O(1)
# space complexity : O(1) |
#!/bin/zsh
'''
Table Printer
Write a function named printTable()
that takes a list of lists of strings and displays it in a well-organized table
with each column right-justified.
Assume that all the inner lists will contain the same number of strings.
For example, the value could look like this:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
Your printTable()
function would print the following:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
Hint: Your code will first have to find the longest string in each of the inner lists
so that the whole column can be wide enough to fit all the strings.
You can store the maximum width of each column as a list of integers.
The printTable()
function can begin with colWidths = [0] * len(tableData)
, which will create a list containing the same number of 0
values as the number of inner lists in tableData
. That way, colWidths[0]
can store the width of the longest string in tableData[0]
, colWidths[1]
can store the width of the longest string in tableData[1]
, and so on. You can then find the largest value in the colWidths
list to find out what integer width to pass to the rjust()
string method.
'''
tabledata = [
['aaples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']
]
def printtable():
pass
# TODO: Complete Algorithm.
|
"""
String Formatting
"""
# Create a variable that contains the first 4 lines of lyrics from your favorite song. Add a comment that includes the song title and artist **each on their own line**! Now print out this variable.
"""
Dancing in the Moonlight
King Harvest
"""
fave_song = '''
We get it almost every night
When that moon is big and bright
It's a supernatural delight
Everybody's dancin' in the moonlight
'''
print(fave_song)
'''
We get it almost every night
When that moon is big and bright
It's a supernatural delight
Everybody's dancin' in the moonlight
''' |
def stable_match(a_pref: dict, b_pref: dict) -> set:
a_list = list(a_pref.keys())
match_dict = {}
while len(match_dict) != len(a_pref):
print(a_list)
for ai in a_list:
if ai in match_dict.values():
continue
print(f"{ai}")
# obtengo mejor candidato
bi = a_pref[ai].pop(0)
# obtengo contrincante
aj = match_dict.get(bi)
# se crea pareja si no existe
if not aj:
print(f"new match {ai}-{bi}")
match_dict[bi] = ai
continue
bi_pref = b_pref[bi]
if bi_pref.index(aj) > bi_pref.index(ai):
print(f"update match {ai}-{bi}")
match_dict[bi] = ai
a_list.append(aj)
continue
return {(ai, bi) for ai, bi in match_dict.items()}
|
#!/usr/bin/env python3
#errors.py
class ParserTongueError(Exception):
pass
########################
### Tokenizer Errors ###
########################
class TokenizerError(ParserTongueError):
pass
class TokenInstantiationTypeError(TokenizerError):
def __init__(self, message):
self.message = message
class UnknownTokenTypeError(TokenizerError):
def __init__(self, message):
self.message = message
class TokenizerNoMatchError(TokenizerError):
def __init__(self, message):
self.message = message
class TokenizerCreationError(TokenizerError):
def __init__(self, message):
self.message = message
######################
### Grammar Errors ###
######################
class GrammarError(ParserTongueError):
pass
class GrammarParsingError(GrammarError):
def __init__(self, message):
self.message = message
class RuleParsingError(GrammarError):
def __init__(self, message):
self.message = message
class RuleLinkageError(GrammarError):
def __init__(self, message):
self.message = message
class RuleTreeError(GrammarError):
def __init__(self, message):
self.message = message
class GrammarLinkError(GrammarError):
def __init__(self, message):
self.message = message
class GrammarDependencyError(GrammarError):
def __init__(self, message):
self.message = message
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.