content
stringlengths 7
1.05M
|
|---|
# -*- coding: utf-8 -*-
def print_logo():
"""
___ __ __ _ __
/ _ \___ ___/ / / / (_)__ / /_
/ , _/ -_) _ / / /__/ (_-</ __/
/_/|_|\__/\_,_/ /____/_/___/\__/
by Team Avengers
MIT LICENSE
"""
print(" ___ __ __ _ __ \n / _ \___ ___/ / / / (_)__ / /_\n / , _/ -_) _ / / /__/ (_-</ __/\n/_/|_|\__/\_,_/ /____/_/___/\__/ \n")
print("by Team Avengers\nMIT LICENSE\n\n")
|
class FizzBuzz(object):
def say(self, number):
if number % 3 == 0 and number % 5 == 0:
return 'FizzBuzz'
elif number % 3 == 0:
return 'Fizz'
elif number % 5 == 0:
return 'Buzz'
else:
return number
|
# -*- coding: utf-8 -*-
__title__ = 'amicleaner'
__version__ = '0.2.0'
__short_version__ = '.'.join(__version__.split('.')[:2])
__author__ = 'Guy Rodrigue Koffi'
__author_email__ = 'koffirodrigue@gmail.com'
__license__ = 'MIT'
|
#-*- coding: utf-8 -*-
spam = 65 # an integer declaration.
print(spam)
print(type(spam)) # this is a function call
eggs = 2
print(eggs)
print(type(eggs))
# Let's see the numeric operations
print(spam + eggs) # sum
print(spam - eggs) # difference
print(spam * eggs) # product
print(spam / eggs) # quotient
print(spam % eggs) # remainder or module
print(spam ** eggs) # power
fooo = -2 # negative value
print(fooo)
print(type(fooo))
print(-fooo) # negated
print(abs(fooo)) # absolute value
print(int(fooo)) # convert to integer
print(float(fooo)) # convert to float
fooo += 1 # auto incremental
print(fooo)
# More on the quotient
print(spam / eggs) # quotient
print(spam / float(eggs)) # quotient
# More on the operations result type
print(type(spam + eggs))
print(type(float(spam) + eggs))
#===============================================================================
# - Python automatically infers the type of the result depending on operands type
#===============================================================================
# Let's try again the power
print(eggs ** spam)
print(type(eggs ** spam))
#===============================================================================
# - Use parentheses to alter operations order
#===============================================================================
#===============================================================================
# Python numeric types:
# - int:
# - Traditional integer
# - Implemented using long in C, at least 32 bits precision
# - Its values are [-sys.maxint - 1, sys.maxint]
# - long:
# - Long integer with unlimited precision
# - Created automatically or when an L suffix is provided
# - float:
# - Floating point number
# - Specified with a dot . as decimals separator
# - Implemented using double in C
# - Check sys.float_info for its internal representation
#
#===============================================================================
#===============================================================================
# SOURCES:
# - http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex
#===============================================================================
|
#!/usr/bin/env python
# created by Bruce Yuan on 17-11-27
class ConstError(Exception):
def __init__(self, message):
self._message = str(message)
def __str__(self):
return self._message
__repr__ = __str__
|
banyakPerulangan = 10
i = 0
while (i < banyakPerulangan):
print('Hello World')
i += 1
|
class Solution:
def sortSentence(self, s: str) -> str:
s=s.split()
s.sort(key = lambda x: x[-1])
sent=""
for i in s:
sent += (i[:-1]+" ")
s=sent.strip()
return s
|
a=10
b=20
print(b-a)
print("SUBTRACTED b-a")
|
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'camera',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'change_picture',
'dependencies': [
'<(DEPTH)/third_party/polymer/v1_0/components-chromium/iron-selector/compiled_resources2.gyp:iron-selector-extracted',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'../compiled_resources2.gyp:route',
'camera',
'change_picture_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'change_picture_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'easy_unlock_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'easy_unlock_turn_off_dialog',
'dependencies': [
'<(DEPTH)/ui/webui/resources/cr_elements/cr_dialog/compiled_resources2.gyp:cr_dialog',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'easy_unlock_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'import_data_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'manage_profile',
'dependencies': [
'../compiled_resources2.gyp:route',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'manage_profile_browser_proxy',
'sync_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'manage_profile_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'password_prompt_dialog',
'dependencies': [
'../compiled_resources2.gyp:route',
'<(EXTERNS_GYP):quick_unlock_private',
'lock_screen_constants',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'people_page',
'dependencies': [
'../compiled_resources2.gyp:route',
'../settings_page/compiled_resources2.gyp:settings_animated_pages',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:icon',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'easy_unlock_browser_proxy',
'easy_unlock_turn_off_dialog',
'lock_screen_constants',
'lock_state_behavior',
'profile_info_browser_proxy',
'sync_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'profile_info_browser_proxy',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'lock_state_behavior',
'dependencies': [
'../compiled_resources2.gyp:route',
'<(EXTERNS_GYP):quick_unlock_private',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'lock_screen_constants',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'lock_screen',
'dependencies': [
'../compiled_resources2.gyp:route',
'lock_screen_constants',
'lock_state_behavior',
'password_prompt_dialog',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'setup_pin_dialog',
'dependencies': [
'../compiled_resources2.gyp:route',
'lock_screen_constants',
'password_prompt_dialog',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'sync_page',
'dependencies': [
'../compiled_resources2.gyp:route',
'../settings_page/compiled_resources2.gyp:settings_animated_pages',
'sync_browser_proxy',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'sync_browser_proxy',
'dependencies': [
'<(DEPTH)/third_party/closure_compiler/externs/compiled_resources2.gyp:metrics_private',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'user_list',
'dependencies': [
'../compiled_resources2.gyp:route',
'<(EXTERNS_GYP):settings_private',
'<(EXTERNS_GYP):users_private',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'users_add_user_dialog',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
'<(EXTERNS_GYP):users_private',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'users_page',
'dependencies': [
'user_list',
'users_add_user_dialog',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'import_data_dialog',
'dependencies': [
'../prefs/compiled_resources2.gyp:prefs_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior',
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:web_ui_listener_behavior',
'import_data_browser_proxy',
],
'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
],
}
|
"""
PERIODS
"""
numPeriods = 180
"""
STOPS
"""
numStations = 13
station_names = (
"Hamburg Hbf", # 0
"Landwehr", # 1
"Hasselbrook", # 2
"Wansbeker Chaussee*", # 3
"Friedrichsberg*", # 4
"Barmbek*", # 5
"Alte Woehr (Stadtpark)", # 6
"Ruebenkamp (City Nord)", # 7
"Ohlsdorf*", # 8
"Kornweg", # 9
"Hoheneichen", # 10
"Wellingsbuettel", # 11
"Poppenbuettel*", # 12
)
numStops = 26
stops_position = (
(0, 0), # Stop 0
(2, 0), # Stop 1
(3, 0), # Stop 2
(4, 0), # Stop 3
(5, 0), # Stop 4
(6, 0), # Stop 5
(7, 0), # Stop 6
(8, 0), # Stop 7
(9, 0), # Stop 8
(11, 0), # Stop 9
(13, 0), # Stop 10
(14, 0), # Stop 11
(15, 0), # Stop 12
(15, 1), # Stop 13
(15, 1), # Stop 14
(13, 1), # Stop 15
(12, 1), # Stop 16
(11, 1), # Stop 17
(10, 1), # Stop 18
(9, 1), # Stop 19
(8, 1), # Stop 20
(7, 1), # Stop 21
(6, 1), # Stop 22
(4, 1), # Stop 23
(2, 1), # Stop 24
(1, 1), # Stop 25
)
stops_distance = (
(0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 0
(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 1
(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 2
(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 3
(0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 4
(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 5
(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 6
(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 7
(0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 8
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 9
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 10
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 11
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 12
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 13
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 14
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 15
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 16
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0), # Stop 17
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), # Stop 18
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0), # Stop 19
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0), # Stop 20
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), # Stop 21
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0), # Stop 22
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0), # Stop 23
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2), # Stop 24
(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), # Stop 25
)
station_start = 0
"""
TRAMS
"""
numTrams = 18
tram_capacity = 514
tram_capacity_cargo = 304
tram_capacity_min_passenger = 208
tram_capacity_min_cargo = 0
tram_speed = 1
tram_headway = 1
tram_min_service = 1
tram_max_service = 10
min_time_next_tram = 0.333
tram_travel_deviation = 0.167
"""
PASSENGERS
"""
passenger_set = "pas-20210422-1717-int4e-1"
passenger_service_time_board = 0.0145
passenger_service_time_alight = 0.0145
"""
CARGO
"""
numCargo = 50
cargo_size = 4
cargo_station_destination = (
8, # 0
4, # 1
5, # 2
4, # 3
3, # 4
5, # 5
4, # 6
5, # 7
8, # 8
8, # 9
5, # 10
12, # 11
8, # 12
4, # 13
8, # 14
5, # 15
12, # 16
4, # 17
3, # 18
12, # 19
12, # 20
12, # 21
4, # 22
3, # 23
4, # 24
12, # 25
5, # 26
3, # 27
12, # 28
5, # 29
4, # 30
3, # 31
12, # 32
5, # 33
3, # 34
8, # 35
8, # 36
12, # 37
8, # 38
4, # 39
3, # 40
3, # 41
8, # 42
3, # 43
4, # 44
12, # 45
12, # 46
5, # 47
3, # 48
4, # 49
)
cargo_release = (
2, # 0
3, # 1
5, # 2
7, # 3
8, # 4
8, # 5
14, # 6
16, # 7
17, # 8
22, # 9
24, # 10
25, # 11
26, # 12
27, # 13
28, # 14
30, # 15
32, # 16
33, # 17
33, # 18
34, # 19
35, # 20
37, # 21
37, # 22
37, # 23
37, # 24
38, # 25
39, # 26
41, # 27
41, # 28
44, # 29
45, # 30
46, # 31
47, # 32
48, # 33
49, # 34
49, # 35
56, # 36
57, # 37
61, # 38
61, # 39
62, # 40
65, # 41
65, # 42
66, # 43
67, # 44
70, # 45
70, # 46
71, # 47
71, # 48
72, # 49
)
cargo_station_deadline = (
33, # 0
119, # 1
176, # 2
72, # 3
18, # 4
171, # 5
105, # 6
155, # 7
156, # 8
123, # 9
126, # 10
91, # 11
36, # 12
87, # 13
144, # 14
134, # 15
141, # 16
101, # 17
163, # 18
108, # 19
144, # 20
175, # 21
76, # 22
162, # 23
47, # 24
97, # 25
87, # 26
114, # 27
164, # 28
142, # 29
55, # 30
56, # 31
57, # 32
118, # 33
59, # 34
160, # 35
170, # 36
139, # 37
71, # 38
71, # 39
82, # 40
161, # 41
109, # 42
151, # 43
77, # 44
80, # 45
169, # 46
97, # 47
129, # 48
99, # 49
)
cargo_max_delay = 3
cargo_service_time_load = 0.3333333333333333
cargo_service_time_unload = 0.25
"""
parameters for reproducibiliy. More information: https://numpy.org/doc/stable/reference/random/parallel.html
"""
#initial entropy
entropy = 8991598675325360468762009371570610170
#index for seed sequence child
child_seed_index = (
0, # 0
)
"""
Results from timetabling
"""
scheme = "SV"
method = "timetabling_closed"
passengerData = "0-rep"
downstream_cargo = False
delivery_optional = True
assignment_method = "timetabling_closed"
operating = (
False, # 0
False, # 1
False, # 2
False, # 3
False, # 4
True, # 5
True, # 6
True, # 7
True, # 8
True, # 9
True, # 10
True, # 11
True, # 12
True, # 13
True, # 14
True, # 15
True, # 16
True, # 17
)
tram_tour = (
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 0
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 1
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 2
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 3
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 4
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 5
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 6
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 7
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 8
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 9
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 10
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 11
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 12
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 13
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 14
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 15
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 16
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25), # 17
)
tram_time_arrival = (
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 0
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 1
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 2
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 3
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), # 4
(10.0, 14.0, 16.0, 18.0, 22.0, 24.0, 27.0, 29.0, 31.0, 34.0, 37.0, 39.0, 41.0, 46.0, 57.0, 61.0, 69.0, 75.0, 77.0, 79.0, 82.0, 84.0, 89.0, 100.0, 111.0, 116.0), # 5
(29.0, 41.0, 43.0, 45.0, 47.0, 49.0, 51.0, 53.0, 55.0, 61.0, 64.0, 66.0, 73.0, 76.0, 82.0, 86.0, 94.0, 97.0, 101.0, 104.0, 106.0, 108.0, 112.0, 116.0, 126.0, 133.0), # 6
(54.0, 66.0, 68.0, 70.0, 72.0, 74.0, 76.0, 78.0, 80.0, 83.0, 86.0, 88.0, 90.0, 94.0, 96.0, 98.0, 103.0, 110.0, 113.0, 115.0, 117.0, 120.0, 131.0, 140.0, 146.0, 155.0), # 7
(65.0, 73.0, 75.0, 77.0, 79.0, 81.0, 83.0, 85.0, 88.0, 91.0, 94.0, 96.0, 98.0, 100.0, 108.0, 111.0, 115.0, 118.0, 126.0, 137.0, 139.0, 143.0, 145.0, 147.0, 157.0, 160.0), # 8
(72.0, 75.0, 82.0, 87.0, 89.0, 91.0, 100.0, 105.0, 112.0, 122.0, 129.0, 131.0, 133.0, 135.0, 137.0, 139.0, 142.0, 145.0, 147.0, 149.0, 151.0, 153.0, 155.0, 157.0, 159.0, 162.0), # 9
(84.0, 88.0, 94.0, 99.0, 110.0, 112.0, 114.0, 116.0, 122.0, 128.0, 131.0, 133.0, 135.0, 137.0, 139.0, 141.0, 144.0, 147.0, 149.0, 151.0, 153.0, 155.0, 157.0, 159.0, 161.0, 164.0), # 10
(102.0, 113.0, 115.0, 117.0, 119.0, 121.0, 123.0, 125.0, 127.0, 130.0, 133.0, 135.0, 137.0, 139.0, 141.0, 143.0, 146.0, 149.0, 151.0, 153.0, 155.0, 157.0, 159.0, 161.0, 163.0, 166.0), # 11
(112.0, 115.0, 117.0, 119.0, 121.0, 123.0, 125.0, 127.0, 129.0, 132.0, 135.0, 137.0, 139.0, 141.0, 143.0, 145.0, 148.0, 151.0, 153.0, 155.0, 157.0, 159.0, 161.0, 163.0, 165.0, 168.0), # 12
(114.0, 117.0, 119.0, 121.0, 123.0, 125.0, 127.0, 129.0, 131.0, 134.0, 137.0, 139.0, 141.0, 143.0, 145.0, 147.0, 150.0, 153.0, 155.0, 157.0, 159.0, 161.0, 163.0, 165.0, 167.0, 170.0), # 13
(116.0, 119.0, 121.0, 123.0, 125.0, 127.0, 129.0, 131.0, 133.0, 136.0, 139.0, 141.0, 143.0, 145.0, 147.0, 149.0, 152.0, 155.0, 157.0, 159.0, 161.0, 163.0, 165.0, 167.0, 169.0, 172.0), # 14
(118.0, 121.0, 123.0, 125.0, 127.0, 129.0, 131.0, 133.0, 135.0, 138.0, 141.0, 143.0, 145.0, 147.0, 149.0, 151.0, 154.0, 157.0, 159.0, 161.0, 163.0, 165.0, 167.0, 169.0, 171.0, 174.0), # 15
(120.0, 123.0, 125.0, 127.0, 129.0, 131.0, 133.0, 135.0, 137.0, 140.0, 143.0, 145.0, 147.0, 149.0, 151.0, 153.0, 156.0, 159.0, 161.0, 163.0, 165.0, 167.0, 169.0, 171.0, 173.0, 176.0), # 16
(122.0, 125.0, 127.0, 129.0, 131.0, 133.0, 135.0, 137.0, 139.0, 142.0, 145.0, 147.0, 149.0, 151.0, 153.0, 155.0, 158.0, 161.0, 163.0, 165.0, 167.0, 169.0, 171.0, 173.0, 175.0, 178.0), # 17
)
tram_time_departure = (
(-0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0), # 0
(-0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0), # 1
(-0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0), # 2
(-0.0, -0.0, -0.0, -0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, 0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0), # 3
(-0.0, -0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0, -0.0, 0.0, 0.0, -0.0, 0.0, -0.0, -0.0, -0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0), # 4
(12.0, 15.0, 17.0, 21.0, 23.0, 26.0, 28.0, 30.0, 32.0, 35.0, 38.0, 40.0, 45.0, 56.0, 60.0, 67.0, 73.0, 76.0, 78.0, 81.0, 83.0, 88.0, 99.0, 110.0, 114.0, 125.0), # 5
(39.0, 42.0, 44.0, 46.0, 48.0, 50.0, 52.0, 54.0, 59.0, 62.0, 65.0, 72.0, 75.0, 81.0, 85.0, 92.0, 95.0, 100.0, 103.0, 105.0, 107.0, 111.0, 115.0, 125.0, 131.0, 140.0), # 6
(64.0, 67.0, 69.0, 71.0, 73.0, 75.0, 77.0, 79.0, 81.0, 84.0, 87.0, 89.0, 93.0, 95.0, 97.0, 101.0, 108.0, 112.0, 114.0, 116.0, 119.0, 130.0, 139.0, 145.0, 153.0, 157.0), # 7
(71.0, 74.0, 76.0, 78.0, 80.0, 82.0, 84.0, 87.0, 89.0, 92.0, 95.0, 97.0, 99.0, 107.0, 110.0, 113.0, 116.0, 125.0, 136.0, 138.0, 142.0, 144.0, 146.0, 156.0, 158.0, 161.0), # 8
(73.0, 81.0, 86.0, 88.0, 90.0, 99.0, 104.0, 111.0, 120.0, 127.0, 130.0, 132.0, 134.0, 136.0, 138.0, 140.0, 143.0, 146.0, 148.0, 150.0, 152.0, 154.0, 156.0, 158.0, 160.0, 163.0), # 9
(86.0, 93.0, 98.0, 109.0, 111.0, 113.0, 115.0, 121.0, 126.0, 129.0, 132.0, 134.0, 136.0, 138.0, 140.0, 142.0, 145.0, 148.0, 150.0, 152.0, 154.0, 156.0, 158.0, 160.0, 162.0, 165.0), # 10
(111.0, 114.0, 116.0, 118.0, 120.0, 122.0, 124.0, 126.0, 128.0, 131.0, 134.0, 136.0, 138.0, 140.0, 142.0, 144.0, 147.0, 150.0, 152.0, 154.0, 156.0, 158.0, 160.0, 162.0, 164.0, 167.0), # 11
(113.0, 116.0, 118.0, 120.0, 122.0, 124.0, 126.0, 128.0, 130.0, 133.0, 136.0, 138.0, 140.0, 142.0, 144.0, 146.0, 149.0, 152.0, 154.0, 156.0, 158.0, 160.0, 162.0, 164.0, 166.0, 169.0), # 12
(115.0, 118.0, 120.0, 122.0, 124.0, 126.0, 128.0, 130.0, 132.0, 135.0, 138.0, 140.0, 142.0, 144.0, 146.0, 148.0, 151.0, 154.0, 156.0, 158.0, 160.0, 162.0, 164.0, 166.0, 168.0, 171.0), # 13
(117.0, 120.0, 122.0, 124.0, 126.0, 128.0, 130.0, 132.0, 134.0, 137.0, 140.0, 142.0, 144.0, 146.0, 148.0, 150.0, 153.0, 156.0, 158.0, 160.0, 162.0, 164.0, 166.0, 168.0, 170.0, 173.0), # 14
(119.0, 122.0, 124.0, 126.0, 128.0, 130.0, 132.0, 134.0, 136.0, 139.0, 142.0, 144.0, 146.0, 148.0, 150.0, 152.0, 155.0, 158.0, 160.0, 162.0, 164.0, 166.0, 168.0, 170.0, 172.0, 175.0), # 15
(121.0, 124.0, 126.0, 128.0, 130.0, 132.0, 134.0, 136.0, 138.0, 141.0, 144.0, 146.0, 148.0, 150.0, 152.0, 154.0, 157.0, 160.0, 162.0, 164.0, 166.0, 168.0, 170.0, 172.0, 174.0, 177.0), # 16
(123.0, 126.0, 128.0, 130.0, 132.0, 134.0, 136.0, 138.0, 140.0, 143.0, 146.0, 148.0, 150.0, 152.0, 154.0, 156.0, 159.0, 162.0, 164.0, 166.0, 168.0, 170.0, 172.0, 174.0, 176.0, 179.0), # 17
)
cargo_tram_assignment = (
5, # 0
5, # 1
5, # 2
5, # 3
5, # 4
13, # 5
6, # 6
6, # 7
14, # 8
7, # 9
7, # 10
6, # 11
6, # 12
7, # 13
6, # 14
17, # 15
11, # 16
6, # 17
6, # 18
7, # 19
11, # 20
17, # 21
7, # 22
6, # 23
6, # 24
6, # 25
7, # 26
7, # 27
10, # 28
7, # 29
7, # 30
7, # 31
7, # 32
7, # 33
7, # 34
7, # 35
11, # 36
11, # 37
7, # 38
7, # 39
7, # 40
14, # 41
8, # 42
9, # 43
8, # 44
8, # 45
17, # 46
9, # 47
15, # 48
9, # 49
)
|
print("Rock..Paper..Scissors..")
print("Type rock or paper or scissors")
player1 = input("player 1, Your move: ")
player2 = input("player 2, Your move: ")
if player1 == player2:
print("It's a draw!")
elif player1 == "rock":
if player2 == "scissors":
print("player1 wins!")
elif player2 == "paper":
print("player2 wins!")
elif player1 == "paper":
if player2 == "rock":
print("player1 wins!")
elif player2 == "scissors":
print("player2 wins!")
elif player1 == "scissors":
if player2 == "paper":
print("player1 wins!")
elif player2 == "rock":
print("player2 wins!")
else:
print("Check spelling")
|
ATTR_CODE = "auth_code"
CONF_MQTT_IN = "mqtt_in"
CONF_MQTT_OUT = "mqtt_out"
DATA_KEY = "media_player.hisense_tv"
DEFAULT_CLIENT_ID = "HomeAssistant"
DEFAULT_MQTT_PREFIX = "hisense"
DEFAULT_NAME = "Hisense TV"
DOMAIN = "hisense_tv"
|
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
first, second = len(word1), len(word2)
result = ""
for one, two in zip(word1, word2):
result += one + two
diff = first - second
if not diff:
return result
elif diff > 0:
result += word1[-diff:]
else:
result += word2[diff:]
return result
|
class Resource:
# 各种需要用到的页面
img_url = "http://210.42.121.241/servlet/GenImg" # 获取验证码的页面
login_url = "http://210.42.121.241/servlet/Login" # 登录页面
index_url = "http://210.42.121.241/stu/stu_index.jsp" # 登录之后的主页面,在这里获取令牌
gpa_url = "http://210.42.121.241/stu/stu_score_credit_statics.jsp" # 带日历的总分和成绩
lessons_url = "http://210.42.121.241/servlet/Svlt_QueryStuLsn?{}" # 课程的页面
scores_url = "http://210.42.121.241/servlet/Svlt_QueryStuScore?{}" # 成绩的页面
|
matches = 0
for line in open('2/input.txt'):
acceptable_range, letter, password = line.split(" ")
low, high = acceptable_range.split("-")
count = password.count(letter[0])
if count in range(int(low), int(high)+1):
matches += 1
print(matches)
|
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
count = 0
for row in grid:
for c in row:
if c < 0: count += 1
return count
|
class MyHashSet:
def __init__(self):
self.set = [False] * 1000001
def add(self, key: int) -> None:
self.set[key] = True
def remove(self, key: int) -> None:
self.set[key] = False
def contains(self, key: int) -> bool:
return self.set[key]
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
# pylint: disable=too-many-statements
# pylint: disable=too-many-lines
# pylint: disable=too-many-locals
# pylint: disable=unused-argument
def create_healthcareapis(cmd, client,
resource_group,
name,
kind,
location,
access_policies_object_id,
tags=None,
etag=None,
cosmos_db_offer_throughput=None,
authentication_authority=None,
authentication_audience=None,
authentication_smart_proxy_enabled=None,
cors_origins=None,
cors_headers=None,
cors_methods=None,
cors_max_age=None,
cors_allow_credentials=None):
service_description = {}
service_description['location'] = location
service_description['kind'] = kind
service_description['properties'] = {}
service_description['properties']['access_policies'] = []
for policy in access_policies_object_id.split(','):
service_description['properties']['access_policies'].append({'object_id': policy})
service_description['properties']['cors_configuration'] = {}
service_description['properties']['cors_configuration']['origins'] = None if cors_origins is None else cors_origins.split(',')
service_description['properties']['cors_configuration']['headers'] = None if cors_headers is None else cors_headers.split(',')
service_description['properties']['cors_configuration']['methods'] = None if cors_methods is None else cors_methods.split(',')
service_description['properties']['cors_configuration']['max_age'] = cors_max_age
service_description['properties']['cors_configuration']['allow_credentials'] = cors_allow_credentials
service_description['properties']['cosmos_db_configuration'] = {}
service_description['properties']['cosmos_db_configuration']['offer_throughput'] = cosmos_db_offer_throughput
service_description['authentication_configuration'] = {}
service_description['authentication_configuration']['authority'] = authentication_authority
service_description['authentication_configuration']['audience'] = authentication_audience
service_description['authentication_configuration']['smart_proxy_enabled'] = authentication_smart_proxy_enabled
return client.create_or_update(resource_group_name=resource_group, resource_name=name, service_description=service_description)
def update_healthcareapis(cmd, client,
resource_group,
name,
kind=None,
location=None,
access_policies_object_id=None,
tags=None,
etag=None,
cosmos_db_offer_throughput=None,
authentication_authority=None,
authentication_audience=None,
authentication_smart_proxy_enabled=None,
cors_origins=None,
cors_headers=None,
cors_methods=None,
cors_max_age=None,
cors_allow_credentials=None):
service_description = client.get(resource_group_name=resource_group, resource_name=name).as_dict()
if location is not None:
service_description['location'] = location
if kind is not None:
service_description['kind'] = kind
if access_policies_object_id is not None:
service_description['properties']['access_policies'] = []
for policy in access_policies_object_id.split(','):
service_description['properties']['access_policies'].append({'object_id': policy})
if service_description['properties'].get('cors_configuration') is None:
service_description['properties']['cors_configuration'] = {}
if cors_origins is not None:
service_description['properties']['cors_configuration']['origins'] = None if cors_origins is None else cors_origins.split(',')
if cors_headers is not None:
service_description['properties']['cors_configuration']['headers'] = None if cors_headers is None else cors_headers.split(',')
if cors_methods is not None:
service_description['properties']['cors_configuration']['methods'] = None if cors_methods is None else cors_methods.split(',')
if cors_max_age is not None:
service_description['properties']['cors_configuration']['max_age'] = cors_max_age
if cors_allow_credentials is not None:
service_description['properties']['cors_configuration']['allow_credentials'] = cors_allow_credentials
if service_description['properties'].get('cosmos_db_configuration') is None:
service_description['properties']['cosmos_db_configuration'] = {}
if cosmos_db_offer_throughput is not None:
service_description['properties']['cosmos_db_configuration']['offer_throughput'] = cosmos_db_offer_throughput
if service_description['properties'].get('authentication_configuration') is None:
service_description['authentication_configuration'] = {}
if authentication_authority is not None:
service_description['authentication_configuration']['authority'] = authentication_authority
if authentication_audience is not None:
service_description['authentication_configuration']['audience'] = authentication_audience
if authentication_smart_proxy_enabled is not None:
service_description['authentication_configuration']['smart_proxy_enabled'] = authentication_smart_proxy_enabled
return client.create_or_update(resource_group_name=resource_group, resource_name=name, service_description=service_description)
def list_healthcareapis(cmd, client,
resource_group=None):
if resource_group is not None:
return client.list_by_resource_group(resource_group_name=resource_group)
return client.list()
def show_healthcareapis(cmd, client,
resource_group,
name):
return client.get(resource_group_name=resource_group, resource_name=name)
def delete_healthcareapis(cmd, client,
resource_group,
name):
return client.delete(resource_group_name=resource_group, resource_name=name)
|
'''
import cachetools
from . import lang
enabled = True
maxsize = 1000
scriptures = {}
for each in lang.available:
scriptures[each] = cachetools.LRUCache(maxsize=maxsize)
'''
|
class Solution:
def mySqrt(self, x: int) -> int:
low=0
high=x
middle= (low+high)//2
while(high>middle and middle>low):
square=middle*middle
if (square==x):
return int(middle)
if (square>x):
high=middle
else:
low=middle
middle=(low+high)//2
if x<high*high: #check this condition for x=8 or x=1
return int(low)
else:
return int(high)
|
palavra_secreta = 'teste'
digitadas = []
chances = 3
while True:
if chances <= 0:
print('Você perdeu!!!')
break
letra = input('Digite uma letra: ')
if len(letra) > 1 or letra.isnumeric():
print('Ahh isso não vale digite apenas uma letra!')
continue
digitadas.append(letra)
if letra in palavra_secreta:
print(f'Uhuuull, a letra "{letra} existe na palavra secreta.')
else:
print(f'AFFzzz: a letra "{letra}" NÂO EXISTE na palavra secreta.')
digitadas.pop()
chances -= 1
secreta = ''
for le in palavra_secreta:
if le in digitadas:
secreta += le
else:
secreta += '*'
if secreta == palavra_secreta:
print(f'Que legal, VOCÊ GANHOU!!! A palavra era {secreta}')
break
else:
print(f'A palavra secreta está assim: {secreta}')
print(f'Você ainda tem {chances} chances.')
print()
|
# -*- coding:utf-8 -*-
'''
File: templates.py
File Created: Tuesday, 12th February 2019
Author: Hongzoeng Ng (kenecho@hku.hk)
-----
Last Modified: Tuesday, 12th February 2019
Modified By: Hongzoeng Ng (kenecho@hku.hk>)
-----
Copyright @ 2018 KenEcho
'''
moving_average_code = """# Moving average strategy
start = '%s'
end = '%s'
universe = %s
benchmark = "HS300"
freq = "d"
refresh_rate = 1
max_history_window = %s
accounts = {
"security_account": AccountConfig(
account_type="security",
capital_base=10000000,
commission=Commission(buycost=0.00, sellcost=0.00, unit="perValue"),
slippage=Slippage(value=0.00, unit="perValue")
)
}
def initialize(context):
context.asset_allocation = %s
def handle_data(context):
security_account = context.get_account("security_account")
current_universe = context.get_universe("stock", exclude_halt=False)
hist = context.get_attribute_history(
attribute="closePrice", time_range=max_history_window, style="sat"
)
for stk in current_universe:
short_ma = hist[stk][-%s:].mean()
long_ma = hist[stk][:].mean()
if (short_ma > long_ma) and (stk not in security_account.get_positions()):
security_account.order_pct_to(stk, context.asset_allocation[stk])
elif short_ma <= long_ma and (stk in security_account.get_positions()):
security_account.order_to(stk, 0)
"""
macd_code = """# MACD Strategy
import pandas as pd
import numpy as np
import talib
start = '%s'
end = '%s'
universe = %s
benchmark = 'HS300'
freq = 'd'
refresh_rate = 1
max_history_window = %s
accounts = {
'security_account': AccountConfig(
account_type='security',
capital_base=10000000,
commission = Commission(buycost=0.00, sellcost=0.00, unit='perValue'),
slippage = Slippage(value=0.00, unit='perValue')
)
}
def initialize(context):
context.asset_allocation = %s
context.short_win = %s # default to be 12
context.long_win = %s # default to be 26
context.macd_win = %s # default to be 9
def handle_data(context):
security_account = context.get_account('security_account')
current_universe = context.get_universe('stock', exclude_halt=False)
hist = context.get_attribute_history(
attribute='closePrice', time_range=max_history_window, style='sat'
)
for stk in current_universe:
prices = hist[stk].values
macd, signal, macdhist = talib.MACD(
prices,
fastperiod=context.short_win,
slowperiod=context.long_win,
signalperiod=context.macd_win
)
if (macd[-1] - signal[-1] > 0) and (stk not in security_account.get_positions()):
security_account.order_pct_to(stk, context.asset_allocation[stk])
elif (macd[-1] - signal[-1] < 0) and (stk in security_account.get_positions()):
security_account.order_to(stk, 0)
"""
stochastic_oscillator_code = """# Stochastic oscillator
import pandas as pd
import numpy as np
import talib as ta
start = '%s'
end = '%s'
universe = %s
benchmark = 'HS300'
freq = 'd'
refresh_rate = 1
max_history_window = %s
accounts = {
'security_account': AccountConfig(
account_type='security',
capital_base=10000000,
commission = Commission(buycost=0.00, sellcost=0.00, unit='perValue'),
slippage = Slippage(value=0.00, unit='perValue')
)
}
def initialize(context):
context.asset_allocation = %s
context.fastk = %s # default to be 14
context.slowk = %s # default to be 3
context.slowd = %s # default to be 3
def handle_data(context):
security_account = context.get_account('security_account')
current_universe = context.get_universe('stock', exclude_halt=False)
hist_close = context.get_attribute_history(
attribute='closePrice', time_range=max_history_window, style='sat'
)
hist_high = context.get_attribute_history(
attribute='highPrice', time_range=max_history_window, style='sat'
)
hist_low = context.get_attribute_history(
attribute='lowPrice', time_range=max_history_window, style='sat'
)
for stk in current_universe:
close = hist_close[stk].values
high = hist_high[stk].values
low = hist_low[stk].values
slowk, slowd = ta.STOCH(
high, low, close,
fastk_period=context.fastk,
slowk_period=context.slowk,
slowk_matype=0,
slowd_period=context.slowd,
slowd_matype=0
)
if (slowk[-1] > slowd[-1]) and (stk not in security_account.get_positions()):
security_account.order_pct_to(stk, context.asset_allocation[stk])
elif (slowk[-1] < slowd[-1]) and (stk in security_account.get_positions()):
security_account.order_to(stk, 0)
"""
buy_hold_code = """# Buy & Hold strategy
start = '%s'
end = '%s'
universe = %s
benchmark = "HS300"
freq = "d"
refresh_rate = 1
accounts = {
"security_account": AccountConfig(
account_type="security",
capital_base=10000000,
commission=Commission(buycost=0.00, sellcost=0.00, unit="perValue"),
slippage=Slippage(value=0.00, unit="perValue")
)
}
def initialize(context):
context.asset_allocation = %s
def handle_data(context):
security_account = context.get_account("security_account")
current_universe = context.get_universe("stock", exclude_halt=False)
for stk in current_universe:
if stk not in security_account.get_positions():
security_account.order_pct_to(stk, context.asset_allocation[stk])
"""
|
# 01_Faça um Programa que peça dois números e imprima o maior deles.
n1 = int(input('Digite primeiro número:'))
n2 = int(input('Digite segundo número:'))
if (n1 > n2):
print('O maior número digitado foi: ', n1)
else:
print('O menor número digitado foi: ', n2)
|
print("Podaj a:")
a = int(input())
print("Podaj b:")
b = int(input())
print("A") if a > b else print("=") if a == b else print("B")
|
def get_user_access_token():
"""Get the secret access token of the currently-logged-in Microsoft user, for use with the Microsoft REST API.
Requires this app to have its own Microsoft client ID and secret. """
pass
def get_user_email():
"""Get the email address of the currently-logged-in Microsoft user.To log in with Microsoft,
call anvil_microsoft.auth.login() from form code. """
pass
def get_user_refresh_token():
"""Get the secret refresh token of the currently-logged-in Microsoft user, for use with the Microsoft REST API.
Requires this app to have its own Microsoft client ID and secret. """
pass
def login():
"""Prompt the user to log in with their Microsoft account"""
pass
def refresh_access_token(refresh_token):
"""Get a new access token from a refresh token you have saved, for use with the Microsoft REST API. Requires this
app to have its own Microsoft client ID and secret. """
pass
|
class DB:
'''
Convience class for decibel scale. Other non-linear scales such as the richter scale could be handled similarly.
Usage:
dB = DB()
.
. (later)
.
gain = 15 * dB
'''
def __rmul__(self, val):
'''
Only allow multiplication from the right to avoid confusing situation
like: 15 * dB * 10
'''
return 10 ** (val / 10.)
def __test__():
dB = DB()
gain = 10 * dB
assert abs(gain - 10) < 1e-8
try:
gain2 = dB * 10
raise Exception('Should raise a type error!')
except TypeError:
pass
__test__()
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
Dogfood_RMEndpoint = 'https://api-dogfood.resources.windows-int.net/'
Helm_Environment_File_Fault_Type = 'helm-environment-file-error'
Invalid_Location_Fault_Type = 'location-validation-error'
Load_Kubeconfig_Fault_Type = 'kubeconfig-load-error'
Read_ConfigMap_Fault_Type = 'configmap-read-error'
Get_ResourceProvider_Fault_Type = 'resource-provider-fetch-error'
Get_ConnectedCluster_Fault_Type = 'connected-cluster-fetch-error'
Create_ConnectedCluster_Fault_Type = 'connected-cluster-create-error'
Delete_ConnectedCluster_Fault_Type = 'connected-cluster-delete-error'
Bad_DeleteRequest_Fault_Type = 'bad-delete-request-error'
Cluster_Already_Onboarded_Fault_Type = 'cluster-already-onboarded-error'
Resource_Already_Exists_Fault_Type = 'resource-already-exists-error'
Resource_Does_Not_Exist_Fault_Type = 'resource-does-not-exist-error'
Create_ResourceGroup_Fault_Type = 'resource-group-creation-error'
Add_HelmRepo_Fault_Type = 'helm-repo-add-error'
List_HelmRelease_Fault_Type = 'helm-list-release-error'
KeyPair_Generate_Fault_Type = 'keypair-generation-error'
PublicKey_Export_Fault_Type = 'publickey-export-error'
PrivateKey_Export_Fault_Type = 'privatekey-export-error'
Install_HelmRelease_Fault_Type = 'helm-release-install-error'
Delete_HelmRelease_Fault_Type = 'helm-release-delete-error'
Check_PodStatus_Fault_Type = 'check-pod-status-error'
Kubernetes_Connectivity_FaultType = 'kubernetes-cluster-connection-error'
Helm_Version_Fault_Type = 'helm-not-updated-error'
Check_HelmVersion_Fault_Type = 'helm-version-check-error'
Helm_Installation_Fault_Type = 'helm-not-installed-error'
Check_HelmInstallation_Fault_Type = 'check-helm-installed-error'
Get_HelmRegistery_Path_Fault_Type = 'helm-registry-path-fetch-error'
Pull_HelmChart_Fault_Type = 'helm-chart-pull-error'
Export_HelmChart_Fault_Type = 'helm-chart-export-error'
Get_Kubernetes_Version_Fault_Type = 'kubernetes-get-version-error'
Get_Kubernetes_Distro_Fault_Type = 'kubernetes-get-distribution-error'
Get_Kubernetes_Namespace_Fault_Type = 'kubernetes-get-namespace-error'
Update_Agent_Success = 'Agents for Connected Cluster {} have been updated successfully'
Update_Agent_Failure = 'Error while updating agents. Please run \"kubectl get pods -n azure-arc\" to check the pods in case of timeout error. Error: {}'
Cluster_Info_Not_Found_Type = 'Error while finding current cluster server details'
Kubeconfig_Failed_To_Load_Fault_Type = "failed-to-load-kubeconfig-file"
Proxy_Cert_Path_Does_Not_Exist_Fault_Type = 'proxy-cert-path-does-not-exist-error'
Proxy_Cert_Path_Does_Not_Exist_Error = 'Proxy cert path {} does not exist. Please check the path provided'
|
""" GOST R 34.10-20** digital signature implementation
This module implements Weierstrass elliptic curves (class elliptic_curve),
and GOST R 34.10-20** digital signature: generation, verification, test
and various supplemental stuff
"""
|
print("""This program will translate any string of text into "uwu" with
100 percent accuracy""")
text = input("Enter text to translate: ")
text = text.casefold()
text = text.replace("r", "w")
text = text.replace("l", "w")
text = text.replace("s", "th")
print("")
print("""translated: "{}" 乂❤‿❤乂""".format(text))
print("")
|
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n, res = len(prices), 0
if n < 2:
return 0
if k > n // 2:
for i in range(1, n):
if prices[i] > prices[i - 1]:
res += prices[i] - prices[i - 1]
return res
hold, sold = [float('-inf')] * (k + 1), [0] * (k + 1)
for price in prices:
for j in range(1, k + 1):
hold[j] = max(hold[j], sold[j - 1] - price)
sold[j] = max(sold[j], hold[j] + price)
return sold[k]
|
def proper_divisors_sum(n):
return sum(a for a in xrange(1, n) if not n % a)
def amicable_numbers(a, b):
return proper_divisors_sum(a) == b and proper_divisors_sum(b) == a
# def amicable_numbers(a, b):
# # this works after multiple submissions to get lucky on random inputs
# return sum(c for c in xrange(1, a) if not a % c) == b
|
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 4 11:19:30 2021
@author: Easin
"""
in1 = input().split()
list1 = []
for elem in range(len(in1)):
list1.append(int(in1[elem]))
#print(list1)
maxm = max(list1)
list2=[]
for val in range(len(list1)):
if list1[val] != maxm:
out = maxm - list1[val]
list2.append(out)
print(out)
|
def save_to_file(data: list, filename: str):
"""Save to file."""
with open(f"{filename}", "w") as f:
for item_ in data:
f.write("%s\n" % item_)
|
print('-=-=- Pintando Parede -=-=-')
#considerando 2m2 d parede = 1 litro de tinta
largura = float(input('Largura da parede: '))
altura = float(input('Altura da parede: '))
print(f'Sua parede tem a dimensão de [{largura}x{altura}] e sua área é de {largura*altura}m2')
print(f'Para pintar essa parede, você precisará de {(largura*altura)/2:.2f} litros de tinta')
|
MESSAGE_TIMESPAN = 2000
SIMULATED_DATA = False
I2C_ADDRESS = 0x77
GPIO_PIN_ADDRESS = 24
BLINK_TIMESPAN = 1000
|
sal = float(input('Digite o Sálario: R$ '))
por = float(input('Digite o Aumento: % '))
ns = sal + (sal * por / 100)
print('O Salário de R$ {:.2f} com Aumento de {}%, ficará com R$ {:.2f}'.format(sal, por, ns))
|
"""Meta variables for SkLite"""
__title__ = "sklite"
__version__ = "0.0.2"
__description__ = "Use Scikit Learn models in Flutter"
__url__ = "https://github.com/axegon/sklite"
__author__ = "Alexander Ejbekov"
__author_email__ = "alexander@kialo.ai"
__license__ = "MIT"
__compat__ = "0.0.1"
|
pkgname = "evolution-data-server"
pkgver = "3.44.0"
pkgrel = 0
build_style = "cmake"
# TODO: libgdata
configure_args = [
"-DENABLE_GOOGLE=OFF", "-DWITH_LIBDB=OFF",
"-DSYSCONF_INSTALL_DIR=/etc", "-DENABLE_INTROSPECTION=ON",
"-DENABLE_VALA_BINDINGS=ON",
]
hostmakedepends = [
"cmake", "ninja", "pkgconf", "flex", "glib-devel", "gperf",
"gobject-introspection", "gettext-tiny", "vala", "perl",
]
makedepends = [
"libglib-devel", "libcanberra-devel", "libical-devel", "heimdal-devel",
"webkitgtk-devel", "libsecret-devel", "gnome-online-accounts-devel",
"gcr-devel", "sqlite-devel", "libgweather-devel", "libsoup-devel",
"json-glib-devel", "nss-devel", "nspr-devel", "vala-devel",
"openldap-devel",
]
checkdepends = ["dbus"]
pkgdesc = "Centralized access to appointments and contacts"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.0-or-later"
url = "https://gitlab.gnome.org/GNOME/evolution-data-server"
source = f"$(GNOME_SITE)/{pkgname}/{pkgver[:-2]}/{pkgname}-{pkgver}.tar.xz"
sha256 = "0d8881b5c51e1b91761b1945db264a46aabf54a73eea1ca8f448b207815d582e"
# internally passes some stuff that only goes to linker
tool_flags = {"CFLAGS": ["-Wno-unused-command-line-argument"]}
options = ["!cross"]
def post_install(self):
self.rm(self.destdir / "usr/lib/systemd", recursive = True)
@subpackage("evolution-data-server-devel")
def _devel(self):
return self.default_devel()
|
budget = float(input())
name = "Hello, there!"
count = 0
diff_count = 0
fee = 0
while True:
name = input()
if name == "Stop":
print(f"You bought {count} products for {fee:.2f} leva.")
break
price = float(input())
diff_count += 1
if diff_count%3 == 0:
price = price / 2
if price > budget:
print(f"You don't have enough money!")
print (f"You need {price-budget:.2f} leva!")
break
budget -= price
fee += price
count += 1
|
'''Taking the input of CIPHERTEXT from the user and removing UNWANTED CHARACTERS and/or WHITESPACES'''
Input = input("Enter ciphertext:")
Input = Input.upper()
NotRecog = '''`~1234567890!@#$%^&*()-_=+[{]}\|'";:.>/?,< '''
for i in Input:
if i in NotRecog:
Input = Input.replace(i,'')
'''Taking the input of KEY from the user and removing UNWANTED CHARACTERS and/or WHITESPACES'''
Key = input("Enter key:")
Key = Key.upper()
NotRecog = '''`~1234567890!@#$%^&*()-_=+[{]}\|'";:.>/?,< '''
for i in Key:
if i in NotRecog:
Key = Key.replace(i,'')
'''Making the KEYWORD which will be used to decipher the ciphertext
Keyword is made on the basis of two things:
1) LENGTH of the Ciphertext = Keyword
2) The KEY is REPEATED again and again till the length is statisfied
Ex: Ciphertext: Aeeealuyel
Key: Hippo
Keyword:HippoHippo'''
Keyword = ''
for i in range(0,len(Input)):
if len(Keyword)<=len(Input):
if len(Input)==len(Key):
n = len(Input)
Keyword += Key[0:n]
elif len(Input)-len(Key)<=len(Input)-len(Keyword):
n = len(Input)-len(Key)
Keyword += Key[0:n]
else:
n = len(Input)-len(Keyword)
Keyword += Key[0:n]
if len(Keyword)==len(Input):
break
'''Deciphering the Ciphertext using the Keyword and TempLists
The AlphaList and TempLists are reversed,i.e.,A will be Z, B will be Y and so on, This is the main difference between
Vigenere and Beaufort Cipher'''
AlphaList = ['Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A']
Result = ''
'''Creation of TempLists:
TempLists(Required row of letters from vigenere grid) is made on the basis of Caesar shift.
A Beaufort Square has 26 Rows & Columns each labeled as a LETTER of the ALPHABET in ORDER.
Each row is shifted(Caesar Shift) according to the formula: Index/Number of Label Letter-1
Ex: Let the row be Z
Number of Label Letter: 26
Shift: 26-1=25
After Shifting the List is reversed on the basis explained above.
Deciphering:
Deciphering is done in 3 steps:
1) A letter of the Keyword is taken
2) Corresponding(Same index/number) Letter of Ciphertext is searched in the row of TempLists
3) After finding the Ciphertext Letter the Column Letter/Index(Check the letter at same index in original AlphaList) is
the Deciphered Letter
Ex: Ciphertext: Aeeealuyel
Key: Hippo
Keyword: Hippohippo
Let letter be H
Corresponding Letter in Ciphertext: A
TempList: ['H', 'G', 'F', 'E', 'D', 'C', 'B', 'A', 'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K', 'J', 'I']
Location of A in TempList: Index 7
In AlphaList at Index 7 is H
ColumnName/Index: H
Deciphered Letter: H'''
for i in range(0,len(Keyword)):
TempLi = ['Z','Y','X','W','V','U','T','S','R','Q','P','O','N','M','L','K','J','I','H','G','F','E','D','C','B','A']
if Keyword[i]=='A':
Result += Input[i]
else:
for j in range(0,AlphaList.index(Keyword[i])):
TempLi+=[TempLi.pop(0)]
L = Input[i]
n = TempLi.index(L)
Result += AlphaList[25-n]
print("Deciphered text:",Result)
|
class Geometric:
def Area(self, x, y):
return x * y
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#
"""
Legal content, should offer a lot of fun to write, this is not used so far
"""
__version__ = '4.0'
content = {
'classified_headline':(
'Commercial Rentals', 'Business Opportunities', 'Bed & Breakfast', 'Year Round Rentals',
'Winter Rentals', 'Apartments/Rooms', 'Vacation/Summer Rentals', 'Off-Island Rentals', 'Rentals Wanted',
'Articles For Sale', 'Yard Sales', 'Wanted', 'Music & Arts', 'Pets & Livestock', 'Help Wanted',
'Child Care Wanted', 'CareGiving Offered', 'Instruction', 'Services', 'Home Services',
'Landscaping & Gardening', 'Heating Supplies & Service', 'Announcements', 'Public Notices',
'Lost & Found', 'Legal Notices <#city#>', 'Bargain Box'),
}
|
# Python 的元组与列表类似,不同之处在于元组的元素不能修改。
#
# 元组使用小括号,列表使用方括号。
#
# 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
print(tup1)
print(tup2)
print(tup3)
print(tup1[2:])
#空元组
tup4 = ()
print(tup4)
#元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用
tup5 = (50)
print(type(tup5))
tup6 = (60,)
print(type(tup6))
#list 转元组
arr = ['Google', 'Runoob', 1997, 2000]
t = tuple(arr)
print(t, type(t))
|
def somar(a, b, c):
s = a + b + c
return s
def fatorial(n):
f = 1
for c in range(n, 0, -1):
f *= c
return f
# Programa Principal
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
n3 = int(input('Digite o último número: '))
print('A soma dos números é {}'.format(somar(n1, n2, n3)))
f1 = int(input('Digite um número: '))
print('O fatorial de {} é {}'.format(f1, fatorial(f1)))
|
# Solution to day 10 of AOC 2015, Elves Look, Elves Say
# https://adventofcode.com/2015/day/10
new_sequence = '1113222113'
for i in range(50):
print('i, len(new_sequence)', i, len(new_sequence))
sequence = new_sequence
run_digit = None
run_length = 0
new_sequence = ''
for head in sequence:
if run_digit is not None and run_digit != head: # Time to add to new_sequence.
new_sequence = new_sequence + str(run_length) + run_digit
# Start new run.
run_length = 1
else:
run_length += 1
run_digit = head
new_sequence = new_sequence + str(run_length) + run_digit # Time to add to new_sequence.
# print('sequence, new_sequence:', new_sequence)
print('Solution:', len(new_sequence))
|
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
#
# Symbol Value
# I 1
# V 5
# X 10
# L 50
# C 100
# D 500
# M 1000
# For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
#
# Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
#
# I can be placed before V (5) and X (10) to make 4 and 9.
# X can be placed before L (50) and C (100) to make 40 and 90.
# C can be placed before D (500) and M (1000) to make 400 and 900.
# Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
#
# Example 1:
#
# Input: 3
# Output: "III"
# Example 2:
#
# Input: 4
# Output: "IV"
# Example 3:
#
# Input: 9
# Output: "IX"
# Example 4:
#
# Input: 58
# Output: "LVIII"
# Explanation: C = 100, L = 50, XXX = 30 and III = 3.
# Example 5:
#
# Input: 1994
# Output: "MCMXCIV"
# Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
total = ''
while num >= 1000:
total += "M"
num -= 1000
if 899 < num <= 999:
total += "CM"
num -= 900
if 500 <= num < 900:
total += "D"
num -= 500
if 399 < num <= 499:
total += "CD"
num -= 400
while num > 99:
total += "C"
num -= 100
if 89 < num <= 99:
total += "XC"
num -= 90
if 50 <= num < 90:
total += "L"
num -= 50
if 39 < num <= 49:
total += "XL"
num -= 40
while num > 9:
total += "X"
num -= 10
if num == 9:
total += "IX"
num = 0
if 5 <= num < 9:
total += "V"
num -= 5
if num == 4:
total += "IV"
num = 0
while num > 0:
total += "I"
num -= 1
return total
|
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
head = list1
for i in range(a - 1):
list1 = list1.next
a_1 = list1
for i in range(b - a + 1):
list1 = list1.next
b_1 = list1.next
list1.next = None
a_1.next = list2
while list2.next:
list2 = list2.next
list2.next = b_1
return head
|
# coding: utf-8
# # CS 196 Spring 2017 Homework 3
# # Table of Contents
# ---
# 1. [Count Cycles](#Count-Cycles)
# 2. [Zip Dictionary](#Zip-Dictionary)
# 3. [List Intersections](#List-Intersections)
# 4. [Find Duplicates](#Find-Duplicates)
# 5. [Sum of the Product of Key and Value](#Sum-of-the-Product-of-Key-and-Value)
# 6. [String Permutation is Palindrome](#String-Permutation-is-Palindrome)
# 7. [Letter Histogram](#Letter-Histograms)
# 8. [Reverse Dictionary](#Reverse-Dictionary)
# # Count Cycles
# ---
# Given an array of integers, find how many cycles are contained. Each element of the array indicates which index of the array should be visited next.
# For example, the array `[1,3,0,0]` contains one cycle, since element at index 0 points to index 1, which points to index 3, which points back to index 0.
#
# ## Restriction(s):
# ---
# * Input array `arr` contains fewer than 1000 elements and at least one.
# * An element which points to its own index is considered a cycle and should be counted.
# * Each element in the array will be an integer within `[0, n-1]`, where n is the length of the array.
#
# ## Example(s):
# ---
# * Example 1:
# * Input:
# * `arr`: `[0,2,4,1,0]`
#
# * Output:
# * `1` There is exactly one cycle in this array, the length-1 cycle at index 0
#
# * Example 2:
# * Input:
# * `arr`: `[1,3,5,4,0,2,7,6]`
#
# * Output:
# * `3` The cycles here are the indices $0 \rightarrow 1 \rightarrow 3 \rightarrow 4$, $2 \rightarrow 5$, and $6 \rightarrow 7$
#
# ## Parameters
# -----------
# * `list` : `arr`
# - An array of integers from 0 to the length of `arr` indicating which index to visit next
#
#
# ## Returns
# -------
# * `int`: Number of cycles
#
# In[393]:
def count_cycles(arr):
index=0
j=[]
count=0
i=0
for i in range(len(arr)):
index=i
times=0
while True:
if arr[index]==i and index not in j:
a=i
for b in range(len(arr)):
j.append(a)
a=arr[a]
count += 1
break
if times>len(arr):
break
times += 1
index=arr[index]
return count
pass
# In[394]:
def test_count_cycles():
assert count_cycles([0,2,4,1,0])==1
assert count_cycles([1,3,5,4,0,2,7,6])==3
assert count_cycles([3,0,0,0])==1
# # Zip Dictionary
# ---
# Given two arrays, named `keys` and `values`, create a dictionary with keys from `keys` and values from `values`. If there are keys that are matched with more than one value, change the value linked to that key to a list of all of distinct values given by the list of values. That is, if the same key-value pair is included twice in the input, it should be included in the dictionary only once.
#
# ## Restriction(s):
# ---
# * Both arrays will be non-empty and will have the same length.
# * The keys in `keys` are not necessarily unique. Keys may be of different types.
# * The total number of entries in the correct dictionary will be no greater than 1,000.
#
# ## Example(s):
# ---
# * Example 1:
# * Input:
# * `keys`: `["Pupper","Doggo","Bork","Doge","Shiba"]`
# * `values`: `[2,7,5,5,3]`
#
# * Output:
# * `{"Pupper":2,"Doggo":7,"Bork":5,"Doge":5,"Shiba":3}`
#
# * Example 2:
# * Input:
# * `keys`: `["Google","Apple","Microsoft","Oracle","Amazon","Cisco","Google","Yahoo"]`
# * `values`: `[(0,0),(1,3),(3,4),(1,4),(2,-1),(1,6),(5,4),(3,9)]`
#
# * Output:
# * `{"Google":[(0,0),(5,4)],"Apple":(1,3),"Microsoft":(3,4),"Oracle":(2,-1),"Amazon":(1,6),"Yahoo":(3,9)}`
# * Note that since `"Google"` has two values, they are placed in an array
# * Example 3:
# * Input:
# * `keys`: `[100,100,100,200,200,300,300]`
# * `values`: `[125,125,173,225,233,374,374]`
# * Output:
# * `{100:[125,173],200:[225,233],300:374}`
# * The duplicate values of 125 and 374 have been removed
#
# ## Parameters
# -----------
# * `list` : `keys`
# - An array of (not necessarily unique) keys for the dictionary
# * `list` : `values`
# - An array of (not necessarily unique) values for the dictionary
#
#
# ## Returns
# -------
# * `dict`: Dictionary of key-value pairs generated from the `keys` and `values`
#
# In[395]:
def zip_dictionary(keys, values):
dictionary={}
for i in range(len(keys)):
if keys[i] not in dictionary:
dictionary[keys[i]] = values[i]
else:
if isinstance(dictionary[keys[i]],(list,tuple)):
dictionary[keys[i]].append(values[i])
else:
dictionary[keys[i]]=[dictionary[keys[i]]]
dictionary[keys[i]].append(values[i])
return dictionary
pass
# In[396]:
def test_zip_dictionary():
assert zip_dictionary(["Pupper","Doggo","Bork","Doge","Shiba"],[2,7,5,5,3])=={"Pupper":2,"Doggo":7,"Bork":5,"Doge":5,"Shiba":3}
assert zip_dictionary(["Google","Apple","Microsoft","Oracle","Amazon","Cisco","Google","Yahoo"],[(0,0),(1,3),(3,4),(1,4),(2,-1),(1,6),(5,4),(3,9)])=={'Google': [(0, 0), (5, 4)], 'Cisco': (1, 6), 'Apple': (1, 3), 'Yahoo': (3, 9), 'Amazon': (2, -1), 'Oracle': (1, 4), 'Microsoft': (3, 4)}
assert zip_dictionary([100,100,100,200,200,300,300],[125,125,173,225,233,374,374])=={100:[125,173],200:[225,233],300:374}
# # List Intersections
# ---
# Write a function that given two list of integers, RETURNS a list of their unique intersection. That is find A ∩ B, given list A and list B.
#
# ## Restriction(s):
# ---
# * Your solution should not use sets or set operations.
#
# ## Example(s):
# ---
# * Example 1:
# * Input:
# * `[1,2,3]`
# * `[3,2,0]`
#
# * Output:
# * `[2, 3]`
#
# * Example 2:
# * Input:
# * `[]`
# * `[1]`
#
# * Output:
# * `[]`
#
#
# ## Parameters
# -----------
# * `ar1` : `List[int]`
# * `A list of integers.`
# * `ar2` : `List[int]`
# * `A list of integers.`
#
#
# ## Returns
# -------
# * `List[int]`:
# * `Returns a list that represents the unique intersection of the two lists.`
# In[397]:
def list_intersection(ar1, ar2):
intersection=[]
ar1proper=[]
for i in range(len(ar1)):
if not ar1[i] in ar1proper:
ar1proper.append(ar1[i])
for i in range(len(ar1proper)):
if ar1proper[i] in ar2:
intersection.append(ar1proper[i])
return intersection
pass
# In[398]:
def test_list_intersection():
assert list_intersection([1,2,3], [3,2,0]) == [2, 3]
assert list_intersection([], [1]) == []
assert list_intersection([1, 1, 2], [1, 2]) == [1,2]
# # Find Duplicates
# ---
# Write a function a list of integers, RETURNS a list of all of its duplicates.
#
# ## Restriction(s):
# ---
# * Your solution should not use sets or set operations.
#
# ## Example(s):
# ---
# * Example 1:
# * Input:
# * `[1,2]`
#
# * Output:
# * `[]`
#
# * Example 2:
# * Input:
# * `[1,2,1]`
#
# * Output:
# * `[1]`
#
#
# ## Parameters
# -----------
# * `ar` : `List[int]`
# * `A list of integers.`
#
#
# ## Returns
# -------
# * `List[int]`:
# * `Returns a list that represents all the duplicates in the given list.`
# In[399]:
def find_duplicates(ar):
duplicates=[]
for i in range(len(ar)):
for j in range(len(ar)):
if i!=j and ar[i]==ar[j]:
if not ar[i] in duplicates:
duplicates.append(ar[i])
return duplicates
pass
# In[400]:
def test_find_duplicates():
assert find_duplicates([1,2]) == []
assert find_duplicates([1,2,1]) == [1]
assert find_duplicates([]) == []
# # Sum of the Product of Key and Value
# ---
# Given a dictionary, RETURN the sum of the products of each key-value pair.
#
#
# ## Example(s):
# ---
# * Example 1:
# * Input:
# * `{1: 2, 3: 4, 5: 6}`
#
# * Output:
# * `44`
#
# * Example 2:
# * Input:
# * `{0: 1, 0: 57, 1: 0, 1: 1}`
#
# * Output:
# * `1`
#
#
# ## Parameters
# -----------
# * `num_dict` : `Dictionary`
# * `A dictionary with keys and values that are both integers`
#
#
# ## Returns
# -------
# * `int`:
# * `Returns the resulting sum`
# In[401]:
def sum_of_product_of_key_and_value(num_dict):
sum=0
for key in num_dict:
if isinstance(key, int) and isinstance(num_dict[key], int):
sum += key*num_dict[key]
return sum
pass
# In[402]:
def test_sum_of_product_of_key_and_value():
assert (sum_of_product_of_key_and_value({1: 2, 3: 4, 5: 6}) == 44)
assert (sum_of_product_of_key_and_value({0: 1, 0: 57, 1: 0, 1: 1}) == 1)
assert (sum_of_product_of_key_and_value({0:0}) == 0)
# # String Permutation is Palindrome
# ---
# Given a string, determine whether or not any arangement of the characters would produce a palindrome.
#
# ## Restriction(s):
# ---
# * Your solution should only consider alpha-numeric characters (a-z, A-Z, 0-9) and should treat lowercase and uppercase characters as being different (A =/= a).
#
# ## Example(s):
# ---
# * Example 1:
# * Input:
# * `abab`
#
# * Output:
# * `true`
#
# * Example 2:
# * Input:
# * `CS 196`
#
# * Output:
# * `false`
#
#
# ## Parameters
# -----------
# * `input` : `string`
# * `A list of integers.`
#
#
# ## Returns
# -------
# * `boolean`:
# * `Returns a boolean value. True if a permutation of the String can be a palindrome, false otherwise.`
# In[403]:
def string_permutation_is_palindrome(input):
dictionary={}
for i in range(len(input)):
if not input[i].isalnum():
continue
if input[i] in dictionary:
dictionary[input[i]]+=1
else:
dictionary[input[i]]=1
oddCount=0
for key in dictionary:
if dictionary[key]%2==1:
oddCount+=1
return oddCount<=1
pass
# In[404]:
def test_string_permutation_is_palindrome():
assert (string_permutation_is_palindrome("abab"))
assert not (string_permutation_is_palindrome("CS 196"))
assert not string_permutation_is_palindrome("Abab")
assert (string_permutation_is_palindrome("race car"))
# # Letter Histograms
# ---
# Write a function that, given a string, returns a dictionary of all of the letter frequencies of the letters present in the string!
# ## Restrictions:
# ---
#
# * E̯̟͈̔͝v͇e̫̜͈̱͆ͣr̨̡͓̔͂ͯy̵̹̟̓҉̠̙̈̚t̴̖͓ͯh̺͇̖͡i̱̪͊ͤņ̦ģ̺ ̆i̶̖̦ͫ̐͠s͏̖̍̕ ̪̱̣̌́ͪ͐͛̌͊̽̉f̟̣́̀̀͑ͭâͧí̸̭͘r̸͉̓̄̉̎ͫ͢ ̓g̸̲̝̝̫̘̅ͦa͓m͓̙̀̕ͅe̱̳͍̟ͤͬ̎̏̎͞.̩̣̅ͣ ̼̫̮̤̫̾̊ͦ̄̚҉D̹̀̾̋̊͘oņ͓̮̅͠'̥t̻ ̱̩̪̭̍ͤͩ͢͡e͎̿x͉ͣ̍̔p̙͖̽ͭ̀̔́ḛ̻҉ͫ̍ct̔ ̹̐̄̇ͅt͍̘̜̉̍͐̀͗̇̄̃h̟̳͔̏͊͘i̠̤͔͊̏s͐̈́̀̀̂̀̊ ̤̽ṭ̶͠o͊͏̣͈̃ ͗͝b̶͖͎ͫ͑͞e̞̺ͨ͆ ͋ḛa̜̬͛̐̀ͥ͘ͅs̞̭͖̼̮̚͘͟y.̳͎͂͂̊́̅͋̓͐̆
# * Everything is fair game.
# * Capitalization matters
# * Spaces matter
# * All utf-8 characters matter
# * All other characters also matter.
# * Order of the keys in your dictionary don't matter.
# * **No Imports**. You don't need them. Seriously.
#
# # Example(s):
# ---
# Example 1:
# * Input: `'this is a really neat method, drake!'`
# * Output: `{'a': 4, ' ': 6, 'e': 4, 'd': 2, 'i': 2, 'h': 2, 'k': 1, 'm': 1, 'l': 2, 'o': 1, 'n': 1, 's': 2, 'r': 2, '!': 1, 't': 3, 'y': 1, ',': 1}`
#
#
# ## Parameters:
# ---
# * st: `string`:
# * There are no real restrictions on this string.
# * This string will not be larger than the largest unsigned integer in python. Probably.
#
# ## Returns:
# ---
# * dic: `dict`<`String`, `int`>
# * Order of keys does not matter.
# * No Value should be less than 1.
# In[405]:
def letter_hist(st):
dictionary={}
for c in st:
if c in dictionary:
dictionary[c]+=1
else:
dictionary[c]=1
return dictionary
# In[406]:
def test_letter_hist():
assert letter_hist("Seems like the homework team is having a little too much fun here.") == {' ': 12, '.': 1, 'S': 1, 'a': 3, 'c': 1, 'e': 9, 'f': 1,
'g': 1, 'h': 5, 'i': 4, 'k': 2, 'l': 3, 'm': 4, 'n': 2, 'o': 4,
'r': 2, 's': 2, 't': 5, 'u': 2, 'v': 1, 'w': 1}
assert letter_hist('n00t n00t! ;)') == {'!': 1, ' ': 2, ')': 1, 'n': 2, '0': 4, 't': 2, ';': 1}
assert letter_hist('Are you ready for test case #3? I know I am!') == {'!': 1, ' ': 10, '#': 1, '3': 1, '?': 1, 'A': 1, 'I': 2, 'a': 3, 'c': 1, 'e': 4, 'd': 1, 'f': 1, 'k': 1, 'm': 1, 'o': 3, 'n': 1, 's': 2, 'r': 3, 'u': 1, 't': 2, 'w': 1, 'y': 2}
assert letter_hist("""Chief Justice Roberts, President Carter, President Clinton, President Bush, President Obama, fellow A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ns, and people of the world: thank you.
We, the citizens of A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢, are now joined in a great national effort to rebuild our country and to restore its promise for all of our people.
Together, we will determine the course of A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ and the world for years to come.
We will face challenges. We will confront hardships. But we will get the job done.
Every four years, we gather on these steps to carry out the orderly and peaceful transfer of power, and we are grateful to President Obama and First Lady Michelle Obama for their gracious aid throughout this transition. They have been magnificent.
Today’s ceremony, however, has very special meaning. Because today we are not merely transferring power from one Administration to another, or from one party to another – but we are transferring power from Washington, D.C. and giving it back to you, the A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n People.
For too long, a small group in our nation’s Capital has reaped the rewards of government while the people have borne the cost.
Washington flourished – but the people did not share in its wealth.
Politicians prospered – but the jobs left, and the factories closed.
The establishment protected itself, but not the citizens of our country.
Their victories have not been your victories; their triumphs have not been your triumphs; and while they celebrated in our nation’s Capital, there was little to celebrate for struggling families all across our land.
That all changes – starting right here, and right now, because this moment is your moment: it belongs to you.
It belongs to everyone gathered here today and everyone watching all across A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢.
This is your day. This is your celebration.
And this, the United States of A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢, is your country.
What truly matters is not which party controls our government, but whether our government is controlled by the people.
January 20th 2017, will be remembered as the day the people became the rulers of this nation again.
The forgotten men and women of our country will be forgotten no longer.
Everyone is listening to you now.
You came by the tens of millions to become part of a historic movement the likes of which the world has never seen before.
At the center of this movement is a crucial conviction: that a nation exists to serve its citizens.
A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ns want great schools for their children, safe neighborhoods for their families, and good jobs for themselves.
These are the just and reasonable demands of a righteous public.
But for too many of our citizens, a different reality exists: Mothers and children trapped in poverty in our inner cities; rusted-out factories scattered like tombstones across the landscape of our nation; an education system, flush with cash, but which leaves our young and beautiful students deprived of knowledge; and the crime and gangs and drugs that have stolen too many lives and robbed our country of so much unrealized potential.
This A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n carnage stops right here and stops right now.
We are one nation – and their pain is our pain. Their dreams are our dreams; and their success will be our success. We share one heart, one home, and one glorious destiny.
The oath of office I take today is an oath of allegiance to all A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ns.
For many decades, we’ve enriched foreign industry at the expense of A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n industry;
Subsidized the armies of other countries while allowing for the very sad depletion of our military;
We've defended other nation’s borders while refusing to defend our own;
And spent trillions of dollars overseas while A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢'s infrastructure has fallen into disrepair and decay.
We’ve made other countries rich while the wealth, strength, and confidence of our country has disappeared over the horizon.
One by one, the factories shuttered and left our shores, with not even a thought about the millions upon millions of A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n workers left behind.
The wealth of our middle class has been ripped from their homes and then redistributed across the entire world.
But that is the past. And now we are looking only to the future.
We assembled here today are issuing a new decree to be heard in every city, in every foreign capital, and in every hall of power.
From this day forward, a new vision will govern our land.
From this moment on, it’s going to be A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ First.
Every decision on trade, on taxes, on immigration, on foreign affairs, will be made to benefit A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n workers and A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n families.
We must protect our borders from the ravages of other countries making our products, stealing our companies, and destroying our jobs. Protection will lead to great prosperity and strength.
I will fight for you with every breath in my body – and I will never, ever let you down.
A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ will start winning again, winning like never before.
We will bring back our jobs. We will bring back our borders. We will bring back our wealth. And we will bring back our dreams.
We will build new roads, and highways, and bridges, and airports, and tunnels, and railways all across our wonderful nation.
We will get our people off of welfare and back to work – rebuilding our country with A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n hands and A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n labor.
We will follow two simple rules: Buy A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n and Hire A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n.
We will seek friendship and goodwill with the nations of the world – but we do so with the understanding that it is the right of all nations to put their own interests first.
We do not seek to impose our way of life on anyone, but rather to let it shine as an example for everyone to follow.
We will reinforce old alliances and form new ones – and unite the civilized world against Radical Islamic Terrorism, which we will eradicate completely from the face of the Earth.
At the bedrock of our politics will be a total allegiance to the United States of A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢, and through our loyalty to our country, we will rediscover our loyalty to each other.
When you open your heart to patriotism, there is no room for prejudice.
The Bible tells us, “how good and pleasant it is when God’s people live together in unity.”
We must speak our minds openly, debate our disagreements honestly, but always pursue solidarity.
When A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ is united, A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ is totally unstoppable.
There should be no fear – we are protected, and we will always be protected.
We will be protected by the great men and women of our military and law enforcement and, most importantly, we are protected by God.
Finally, we must think big and dream even bigger.
In A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢, we understand that a nation is only living as long as it is striving.
We will no longer accept politicians who are all talk and no action – constantly complaining but never doing anything about it.
The time for empty talk is over.
Now arrives the hour of action.
Do not let anyone tell you it cannot be done. No challenge can match the heart and fight and spirit of A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢.
We will not fail. Our country will thrive and prosper again.
We stand at the birth of a new millennium, ready to unlock the mysteries of space, to free the Earth from the miseries of disease, and to harness the energies, industries and technologies of tomorrow.
A new national pride will stir our souls, lift our sights, and heal our divisions.
It is time to remember that old wisdom our soldiers will never forget: that whether we are black or brown or white, we all bleed the same red blood of patriots, we all enjoy the same glorious freedoms, and we all salute the same great A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n Flag.
And whether a child is born in the urban sprawl of Detroit or the windswept plains of Nebraska, they look up at the same night sky, they fill their heart with the same dreams, and they are infused with the breath of life by the same almighty Creator.
So to all A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ns, in every city near and far, small and large, from mountain to mountain, and from ocean to ocean, hear these words:
You will never be ignored again.
Your voice, your hopes, and your dreams, will define our A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢n destiny. And your courage and goodness and love will forever guide us along the way.
Together, We Will Make A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ Strong Again.
We Will Make A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ Wealthy Again.
We Will Make A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ Proud Again.
We Will Make A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ Safe Again.
And, Yes, Together, We Will Make A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢ Great Again. Thank you, God Bless You, And God Bless A̶̰̯̬͙̰͙̘̲͌͋̎ͫ̒̉̔̄̆ͧ͘͝m̶̶͍̫̤̖͛̐̕͟e̶̶̟͙̯̤͕͋ͨ̔͋ͩ́́͒́ͫ͛ͩr̶̴̡̝̦̩̫͇͚̥̯̞̉ͮͦ͊̇ͤ͂ͣ̃ͤ̈́̚͝i̶̵͕͉̼͈̞̽͋́̀̒͂́ͧ̈̀͢c̶̛͖̖̓ͯ̍ͧ͗ͬ͞a̶̛̲͎̯̺̥̻ͧ̽̂ͧ̈́͢.""") == {'\n': 148,
' ': 1377,
"'": 2,
',': 95,
'-': 1,
'.': 89,
'0': 2,
'1': 1,
'2': 2,
'7': 1,
':': 7,
';': 9,
'A': 51,
'B': 9,
'C': 7,
'D': 3,
'E': 5,
'F': 8,
'G': 5,
'H': 1,
'I': 7,
'J': 2,
'L': 1,
'M': 7,
'N': 3,
'O': 5,
'P': 9,
'R': 2,
'S': 6,
'T': 21,
'U': 2,
'W': 39,
'Y': 5,
'a': 486,
'b': 104,
'c': 179,
'd': 248,
'e': 807,
'f': 147,
'g': 129,
'h': 271,
'i': 474,
'j': 9,
'k': 35,
'l': 326,
'm': 159,
'n': 467,
'o': 557,
'p': 102,
'r': 506,
's': 354,
't': 532,
'u': 189,
'v': 63,
'w': 146,
'x': 5,
'y': 123,
'z': 8,
'̀': 68,
'́': 34,
'̂': 34,
'̃': 34,
'̄': 34,
'̆': 34,
'̇': 34,
'̈': 34,
'̉': 68,
'̍': 34,
'̎': 34,
'̐': 34,
'̒': 68,
'̓': 34,
'̔': 68,
'̕': 34,
'̖': 68,
'̘': 34,
'̚': 34,
'̛': 68,
'̝': 34,
'̞': 68,
'̟': 34,
'̡': 34,
'̤': 68,
'̥': 68,
'̦': 34,
'̩': 34,
'̫': 68,
'̬': 34,
'̯': 136,
'̰': 68,
'̲': 68,
'̴': 34,
'̵': 34,
'̶': 306,
'̺': 34,
'̻': 34,
'̼': 34,
'̽': 68,
'́': 136,
'͂': 68,
'̈́': 68,
'͇': 34,
'͈': 34,
'͉': 34,
'͊': 34,
'͋': 136,
'͌': 34,
'͍': 34,
'͎': 34,
'͒': 34,
'͕': 68,
'͖': 34,
'͗': 34,
'͘': 34,
'͙': 102,
'͚': 34,
'͛': 68,
'͝': 68,
'͞': 34,
'͟': 34,
'͢': 68,
'ͣ': 34,
'ͤ': 68,
'ͦ': 34,
'ͧ': 170,
'ͨ': 34,
'ͩ': 68,
'ͫ': 68,
'ͬ': 34,
'ͮ': 34,
'ͯ': 34,
'–': 11,
'’': 8,
'“': 1,
'”': 1}
# # Reverse Dictionary
# ---
# For this method, given any dictionary, you need to reverse the keys and values. Since there can be multiple keys that map to the same value, have all values on a given key be stored in a set in the dictionary you return.
#
# ## Example(s):
# ---
# Example 1:
# * `{'a':'b', 'c':'b', 'd': 'x'}`
# * `{'b': set(['a', 'c']), 'x':set(['d'])}`.
# This can also be represented as `{'b':{'a','c'}, 'x':{'d'}}` depending on where you're running your code.
#
# ## Restriction(s):
# ---
# * **No Imports**. You still don't need them. Seriously.
# * Everything that will be in a dictionary that is given to you will be hashable. No bamboozle.
# * You can expect somewhat less than 9223372036854775807 key-value pairs.
#
# ## Parameters:
# ---
# * dic: `{A: B}`
# * Where `A` and `B` are hashable types.
#
# ## Output:
# ---
# * out_dic: `{A: set([B])}`
# * Where `A` and `B` are the same types as the input.
# In[407]:
def reverse_dict(dic):
dic2={}
for key in dic:
if dic[key] in dic2:
dic2[dic[key]].add(key)
else:
dic2[dic[key]]=set(key)
return dic2
pass
# In[413]:
def test_reverse_dict():
assert reverse_dict({'a':'b', 'b':'b', 'c':'d'}) == {'b': {'a', 'b'}, 'd': {'c'}}
assert reverse_dict({'a':'b', 'b':'c', 'c':'d', 'd':'e','e':'f'}) == {'b': {'a'}, 'c': {'b'}, 'd': {'c'}, 'e': {'d'}, 'f': {'e'}}
# In[414]:
def test_all():
# Add your test case here. This should be at the very end
test_count_cycles()
test_list_intersection()
test_find_duplicates()
test_sum_of_product_of_key_and_value()
test_string_permutation_is_palindrome()
test_letter_hist()
test_reverse_dict()
# In[415]:
test_all()
|
# problem3.py
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
number = 600851475143
divider = 2
while number != 1:
if number % divider == 0:
number = number / divider
print(divider)
else:
divider += 1
|
class Solution:
# Accumulator List (Accepted), O(n) time and space
def waysToMakeFair(self, nums: List[int]) -> int:
acc = []
is_even = True
n = len(nums)
for i in range(n):
even, odd = acc[i-1] if i > 0 else (0, 0)
if is_even:
even += nums[i]
else:
odd += nums[i]
is_even = not is_even
acc.append((even, odd))
res = 0
for i in range(n):
even = odd = 0
if i > 0:
even += acc[i-1][0]
odd += acc[i-1][1]
if i < n-1:
even += acc[n-1][1] - acc[i][1]
odd += acc[n-1][0] - acc[i][0]
if even == odd:
res += 1
return res
# Two Sum Pairs for even and odd (Top Voted), O(n) time, O(1) space
def waysToMakeFair(self, A: List[int]) -> int:
s1, s2 = [0, 0], [sum(A[0::2]), sum(A[1::2])]
res = 0
for i, a in enumerate(A):
s2[i % 2] -= a
res += s1[0] + s2[1] == s1[1] + s2[0]
s1[i % 2] += a
return res
|
#!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
idx = 0
results = []
error = None
while list_division and idx < list_length:
try:
results.append(my_list_1[idx] / my_list_2[idx])
except ZeroDivisionError:
error = "division by 0"
results.append(0)
except(TypeError, ValueError):
error = "wrong type"
results.append(0)
except IndexError:
error = "out of range"
results.append(0)
finally:
if error is not None:
print(error)
error = None
idx += 1
return results
|
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
length = len(prices)
if length == 0:
return 0
max_profit, low = 0, prices[0]
for i in range(1, length):
if low > prices[i]:
low = prices[i]
else:
temp = prices[i] - low
if temp > max_profit:
max_profit = temp
return max_profit
|
frutas = open('frutas.txt', 'r')
numeros= open('numeros.txt','r')
lista_frutas= [] #Llenar las lista con los datos del archivo frutas.txt
lista_numeros= []#Llenar las lista con los datos del archivo numeros.txt
for i in frutas:
lista_frutas.append(i)
frutas.close()
for i in numeros:
lista_numeros.append(i)
numeros.close()
#Realizar una funcion que elimine un caracter de todos los elementos de la lista
"""
Entradas:
lista->list->lista
elemento->str->elemento
Salidas:
lista->list->lista
"""
"""
def eliminar_un_caracter_de_toda_la_lista(lista:list,elemento:str)-> list:
auxiliar=[]
for i in lista:
a=i.replace(elemento,"")
auxiliar.append(a)
return auxiliar
if __name__ == "__main__":
#print(lista_frutas)
lista_frutas_dos=eliminar_un_caracter_de_toda_la_lista(lista_frutas,"\n")
lista_frutas_sin_m= eliminar_un_caracter_de_toda_la_lista(lista_frutas_dos,"m")
print(lista_frutas_sin_m)
"""
#Realizar una funcion que retorne la copia de una funcion que pasa por parametro
"""
Entradas:
lista->list->lista
Salidas:
lista->list->lista
"""
"""
def copia_lista(lista:list)-> list:
return lista.copy()
if __name__ == "__main__":
copia=copia_lista(lista_numeros)
lista_nueva= eliminar_un_caracter_de_toda_la_lista(copia,"\n")
print (copia_lista(lista_numeros))
"""
#numeros enteros
"""
Entradas:
lista->list->lista
Salidas:
lista->list->lista
"""
"""
def numeros_enteros(lista:list):
auxiliar=[]
auxiliar_dos=[]
for i in lista:
auxiliar.append(float(i))
for i in auxiliar:
auxiliar_dos.append(int(i))
return auxiliar_dos
def copia_lista(lista:list)-> list:
return lista.copy()
def eliminar_un_caracter_de_toda_la_lista(lista:list,elemento:str)-> list:
auxiliar=[]
for i in lista:
a=i.replace(elemento,"")
auxiliar.append(a)
return auxiliar
if __name__=="__main__":
copia=(copia_lista(lista_numeros))
lista_nueva_2= eliminar_un_caracter_de_toda_la_lista(copia,"\n")
print(numeros_enteros(lista_nueva_2))
"""
#Realizar una funcion que elimine un elemento de una lista
"""
Entradas:
lista.>list->lista
elemento->str->elemento
Salidas:
lista->list->lista
"""
"""
def elimina_elemento_lista(lista:list,elemento:str)->list:
auxiliar=[]
for i in lista:
a=i.replace(elemento,"")
auxiliar.append(a)
return auxiliar
if __name__ == "__main__":
#print(lista_frutas)
lista_frutas_dos=elimina_elemento_lista(lista_frutas,"\n")
lista_frutas_sin_fresa=elimina_elemento_lista(lista_frutas_dos,"Fresa")
print(lista_frutas_sin_fresa)
"""
#Retorna una lista con las palabras iniciales con la letra que pasa por parametro
"""
Entradas:
letra->str->letra
lista->list->lista
Salidas:
lista->list->lista
"""
"""
def letra(letra:str,lista:list)->list:
auxiliar=[]
for i in lista:
if i [0]== letra:
auxiliar.append(i)
return(auxiliar)
if __name__ == "__main__":
lista_inicial=letra("M",lista_frutas)
print(lista_inicial)
"""
#Realizar una funcion que retorne el tamaño de una lista
"""
Entradas:
lista->list->lista
Salidas
lista->list->lista
"""
"""
def tamano_lista(lista:list):
auxiliar=[]
tamano= len(lista)
for i in lista:
auxiliar.count(i==0)
return tamano
if __name__=="__main__":
print(tamano_lista(lista_numeros))
"""
#RetornaUnEntero
#Retorna el tamaño de la lista y que tipo de datos estan dentro de la lista
"""
Entradas:
lista->list->lista
Salidas:
lista->list->lista
"""
"""
def informacion_lista(lista:list):
tamaño=len(lista)
auxiliar=[]
for i in lista:
if (auxiliar.count(i)==0):
auxiliar.append(type(i))
return tamaño,auxiliar
print(informacion_lista(lista_frutas))
"""
#Retornar una lista con los numero negativos
"""
Entradas:
lista->list->lista
elemento->str-elemento
Salidas:
lista->list->lista
"""
"""
def numeros_negativos(lista:list):
auxiliar=[]
auxiliar_dos=[]
for i in lista:
auxiliar.append(float(i))
for i in auxiliar:
if(i<0):
auxiliar_dos.append(int(i))
return auxiliar_dos
def copia_lista(lista:list)-> list:
return lista.copy()
def eliminar_un_caracter_de_toda_la_lista(lista:list,elemento:str)-> list:
auxiliar=[]
for i in lista:
a=i.replace(elemento,"")
auxiliar.append(a)
return auxiliar
if __name__=="__main__":
copia=(copia_lista(lista_numeros))
lista_nueva_2= eliminar_un_caracter_de_toda_la_lista(copia,"\n")
print(numeros_negativos(lista_nueva_2))
"""
#realizar una funcion que retorne la posicion de un elemento que pasa por parametro
"""
def posicion_elemento(lista:list,elemento:str):
auxiliar=[]
for i in lista:
if (str(i) == str(elemento)+"\n"):
auxiliar.append(lista.index(i))
return auxiliar
if __name__=="__main__":
print(posicion_elemento(lista_frutas,"Fresa"))
"""
#realizar una funcion que agregue al final de archivo frutas una fruta
"""
def frutas_nuevo(elemento):
frutas = open('frutas.txt', 'r')
for i in frutas:
lista_frutas.append(i)
frutas.close()
frutas = open('frutas.txt', 'w')
for i in lista_frutas:
frutas.write(i)
frutas.write("\n"+str(elemento))
frutas.close()
"""
#Realizar una funcion que cuente el numero de veces que se repite un elemento
"""
def repetir(elemento):
auxiliar=[]
for i in elemento:
for ii in auxiliar:
if i == ii:
c = 0
auxiliar.append(c)
c = "c" + i
return c
"""
"""
if __name__ == "__main__":
lista=[1,2,3,4,4]
copy=copia_lista(lista)
print(copy)
"""
|
# Section 6.2.5 snippets
country_capitals1 = {'Belgium': 'Brussels',
'Haiti': 'Port-au-Prince'}
country_capitals2 = {'Nepal': 'Kathmandu',
'Uruguay': 'Montevideo'}
country_capitals3 = {'Haiti': 'Port-au-Prince',
'Belgium': 'Brussels'}
country_capitals1 == country_capitals2
country_capitals1 == country_capitals3
country_capitals1 != country_capitals2
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. and #
# Pearson Education, Inc. All Rights Reserved. #
# #
# DISCLAIMER: The authors and publisher of this book have used their #
# best efforts in preparing the book. These efforts include the #
# development, research, and testing of the theories and programs #
# to determine their effectiveness. The authors and publisher make #
# no warranty of any kind, expressed or implied, with regard to these #
# programs or to the documentation contained in these books. The authors #
# and publisher shall not be liable in any event for incidental or #
# consequential damages in connection with, or arising out of, the #
# furnishing, performance, or use of these programs. #
##########################################################################
|
class BitmexDataIterator():
def __init__(self,data):
self._data = data
self._index = 0
def __next__(self):
pass
class BitmexDataStructure():
"""
Data Object for Bitmex data manipulation
"""
def __init__(self,symbol,use_compression=False):
self._symbol = symbol
self._header = None
self._data = None
self._size = None
self._use_compression = use_compression
def add_data(self,data):
if self._data:
self._ensure_correct_data_format(data)
pass
else:
pass
def save_data(self):
if self._use_compression:
pass
else:
pass
def _ensure_correct_data_format(self,data_to_compare):
pass
def __iter__(self):
return BitmexDataIterator(self)
|
N = int(input())
Y = 0
for _ in range(N):
t = input().split()
x = float(t[0])
u = t[1]
if u == 'JPY':
Y += x
elif u == 'BTC':
Y += x * 380000.0
print(Y)
|
def reverse(x: int) -> int:
neg = x < 0
if neg:
x *= -1
result = 0
while x:
result = result * 10 + x % 10
x //= 10
return result if not neg else -1 * result
assert reverse(123) == 321
assert reverse(-123) == -321
|
class ParenthesizePropertyNameAttribute(Attribute,_Attribute):
"""
Indicates whether the name of the associated property is displayed with parentheses in the Properties window. This class cannot be inherited.
ParenthesizePropertyNameAttribute()
ParenthesizePropertyNameAttribute(needParenthesis: bool)
"""
def Equals(self,o):
"""
Equals(self: ParenthesizePropertyNameAttribute,o: object) -> bool
Compares the specified object to this object and tests for equality.
o: The object to be compared.
Returns: true if equal; otherwise,false.
"""
pass
def GetHashCode(self):
"""
GetHashCode(self: ParenthesizePropertyNameAttribute) -> int
Gets the hash code for this object.
Returns: The hash code for the object the attribute belongs to.
"""
pass
def IsDefaultAttribute(self):
"""
IsDefaultAttribute(self: ParenthesizePropertyNameAttribute) -> bool
Gets a value indicating whether the current value of the attribute is the
default value for the attribute.
Returns: true if the current value of the attribute is the default value of the
attribute; otherwise,false.
"""
pass
def __eq__(self,*args):
""" x.__eq__(y) <==> x==y """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,needParenthesis=None):
"""
__new__(cls: type)
__new__(cls: type,needParenthesis: bool)
"""
pass
def __ne__(self,*args):
pass
NeedParenthesis=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the Properties window displays the name of the property in parentheses in the Properties window.
Get: NeedParenthesis(self: ParenthesizePropertyNameAttribute) -> bool
"""
Default=None
|
matriz = [[], [], []]
for i in range(0, 3):
matriz[0].append(int(input(f'Digite um valor para [{0}, {i}]: ')))
for i in range(0, 3):
matriz[1].append(int(input(f'Digite um valor para [{1}, {i}]: ')))
for i in range(0, 3):
matriz[2].append(int(input(f'Digite um valor para [{2}, {i}]: ')))
print(f'{matriz[0]}\n{matriz[1]}\n{matriz[2]}')
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
for c in range(0, 3):
matriz[[l][c]] = int(input(f'Digite um valor para [{l}, {c}]: '))
print('-=' * 30)
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matriz[l] [c]}]', end='')
print()
|
r"""Psuedo-spectral implementations of some useful equations
In PsDNS, equations are represented as class objects that implement a
:meth:`rhs` method. The :meth:`rhs` method takes one argument,
*uhat*, which is the solution vector, normally in spectral space
expressed as a :class:`~psdns.bases.SpectralArray`, and it returns the
right-hand side vector. That is, for the PDE
.. math::
\frac{\partial}{\partial t} \boldsymbol{U}(t)
= \boldsymbol{F}[\boldsymbol{U}]
the :meth:`rhs` method takes :math:`\boldsymbol{U}` and returns
:math:`\boldsymbol{F}[\boldsymbol{U}]`.
Since normally only a single equation is needed in a given script,
no equations are imported by default when importing :mod:`psdns`.
Users can also implement their own equations. There is no need to
subclass from any specific base class, any class that implements a
:meth:`rhs` method can be used as an equation.
The :mod:`~psdns.equations` sub-module also includes some functions
that return initial conditions for certain canonical problems, either
in the form of stand-alone functions, or class methods.
"""
|
#!/usr/bin/env python
"""
Provides custom messages.
"""
ADD_RECORD_NOT_ALLOWED = 'Adding record is not allowed.'
SUCCESSFULL_RESPONSE_MESSAGE = 'You have successfully completed this operation.'
FAILED_RESPONSE_MESSAGE = 'Error: you have attempted wrong operation.'
VENDING_MACHINE_COINS_VALID_MESSAGE = f'users with a “buyer” role can only deposit 5, 10, 20, 50 and 100 cent coins into their vending machine account.'
|
class Solution:
def __init__(self):
self.map = {}
def cloneGraph(self, node):
if node is None:
return None
next = UndirectedGraphNode(node.label)
self.map[str(node.label)] = next
for tmp in node.neighbors:
if str(tmp.label) in self.map:
next.neighbors.append(self.map.get(str(tmp.label)))
else:
next.neighbors.append(self.cloneGraph(tmp))
return self.map.get(str(node.label))
|
#Metodo Format substitui as variáveis passadas
# \' aspas simples
# \"" aspas duplas
# \n quebra de linha
# \r retorno de carga = ENTER
# \t tabulação
# \b backspace apaga o caractere anterior
cidade = "Sao Paulo"
dia = 15
mes = "Setembro"
ano = 2021
canal = "CFB Cursos"
data = "{}, {} de {} de {} \n \"{}\"" #formato de exibição <\n quebra linha> | <\"{}\" coloca entre aspas>
print(data.format(cidade,dia,mes,ano,canal))#forma de impressão
|
"""
Package used by tests.
"""
C = 3
|
#!/usr/bin/env python3
"""
Copyright (c) 2017-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
"""
PREFIX = "__osc_"
OUTFILE_TABLE = "__osc_tbl_"
OUTFILE_EXCLUDE_ID = "__osc_ex_"
OUTFILE_INCLUDE_ID = "__osc_in_"
NEW_TABLE_PREFIX = "__osc_new_"
DELTA_TABLE_PREFIX = "__osc_chg_"
RENAMED_TABLE_PREFIX = "__osc_old_"
INSERT_TRIGGER_PREFIX = "__osc_ins_"
UPDATE_TRIGGER_PREFIX = "__osc_upd_"
DELETE_TRIGGER_PREFIX = "__osc_del_"
# tables with 64 character length names need a generic place-holder name
GENERIC_TABLE_NAME = "online_schema_change_temp_tbl"
# Special prefixes for tables that have longer table names
SHORT_NEW_TABLE_PREFIX = "n!"
SHORT_DELTA_TABLE_PREFIX = "c!"
SHORT_RENAMED_TABLE_PREFIX = "o!"
SHORT_INSERT_TRIGGER_PREFIX = "i!"
SHORT_UPDATE_TRIGGER_PREFIX = "u!"
SHORT_DELETE_TRIGGER_PREFIX = "d!"
OSC_LOCK_NAME = "OnlineSchemaChange"
CHUNK_BYTES = 2 * 1024 * 1024
REPLAY_DEFAULT_TIMEOUT = 5 # replay until we can finish in 5 seconds
DEFAULT_BATCH_SIZE = 500
DEFAULT_REPLAY_ATTEMPT = 10
DEFAULT_RESERVED_SPACE_PERCENT = 1
LONG_TRX_TIME = 30
MAX_RUNNING_BEFORE_DDL = 200
DDL_GUARD_ATTEMPTS = 600
LOCK_MAX_ATTEMPTS = 3
LOCK_MAX_WAIT_BEFORE_KILL_SECONDS = 0.5
SESSION_TIMEOUT = 600
DEFAULT_REPLAY_GROUP_SIZE = 200
PK_COVERAGE_SIZE_THRESHOLD = 500 * 1024 * 1024
MAX_WAIT_FOR_SLOW_QUERY = 100
MAX_TABLE_LENGTH = 64
MAX_REPLAY_BATCH_SIZE = 500000
MAX_REPLAY_CHANGES = 2146483647
|
with open('input.txt') as f:
octopus = list(map(lambda line: list(map(int, line.strip())), f.readlines()))
def print_grid(grid):
for line in grid:
print(''.join(map(str, line)))
def update(grid):
flash_count = 0
# increase all
flashed = set()
to_updates = []
for row in range(len(grid)):
for col in range(len(grid[0])):
grid[row][col] += 1
if grid[row][col] >= 10:
flashed.add((row, col))
to_updates.extend(
list(filter(
lambda x: x[0] >= 0 and x[0] < len(grid) and x[1] >= 0 and x[1] < len(grid[0]),
[(row + delta_row, col + delta_col) for delta_row in range(-1, 2) for delta_col in range(-1, 2)]
))
)
# loop update
while len(to_updates) > 0:
row, col = to_updates.pop()
if (row, col) in flashed: continue
grid[row][col] += 1
if grid[row][col] >= 10:
flashed.add((row, col))
to_updates.extend(
list(filter(
lambda x: x[0] >= 0 and x[0] < len(grid) and x[1] >= 0 and x[1] < len(grid[0]),
[(row + delta_row, col + delta_col) for delta_row in range(-1, 2) for delta_col in range(-1, 2)]
))
)
# clear
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] >= 10:
grid[row][col] = 0
flash_count += 1
def check_all_flash(grid):
return all(map(lambda line: sum(line) == 0, grid))
res = 0
while True:
update(octopus)
res += 1
if check_all_flash(octopus):
break
print(res)
|
#
# PySNMP MIB module CISCO-FIPS-STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-FIPS-STATS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:41:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
NotificationType, Bits, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32, IpAddress, iso, Gauge32, MibIdentifier, ModuleIdentity, Unsigned32, ObjectIdentity, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Bits", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Integer32", "IpAddress", "iso", "Gauge32", "MibIdentifier", "ModuleIdentity", "Unsigned32", "ObjectIdentity", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
ciscoFipsStatsMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 999999))
ciscoFipsStatsMIB.setRevisions(('2003-03-10 00:00',))
if mibBuilder.loadTexts: ciscoFipsStatsMIB.setLastUpdated('200303100000Z')
if mibBuilder.loadTexts: ciscoFipsStatsMIB.setOrganization('Cisco Systems, Inc.')
ciscoFipsStatsMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 0))
ciscoFipsStatsMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1))
ciscoFipsStatsMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2))
cfipsStats = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1))
cfipsStatsGlobal = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1, 1))
cfipsPostStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 999999, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("running", 1), ("passed", 2), ("failed", 3), ("notAvailable", 4))).clone('notAvailable')).setMaxAccess("readonly")
if mibBuilder.loadTexts: cfipsPostStatus.setStatus('current')
ciscoFipsStatsMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 1))
ciscoFipsStatsMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 2))
ciscoFipsStatsMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 1, 1)).setObjects(("CISCO-FIPS-STATS-MIB", "ciscoFipsStatsMIBGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoFipsStatsMIBCompliance = ciscoFipsStatsMIBCompliance.setStatus('current')
ciscoFipsStatsMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 999999, 2, 2, 1)).setObjects(("CISCO-FIPS-STATS-MIB", "cfipsPostStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoFipsStatsMIBGroup = ciscoFipsStatsMIBGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-FIPS-STATS-MIB", PYSNMP_MODULE_ID=ciscoFipsStatsMIB, ciscoFipsStatsMIBObjects=ciscoFipsStatsMIBObjects, ciscoFipsStatsMIB=ciscoFipsStatsMIB, ciscoFipsStatsMIBNotifs=ciscoFipsStatsMIBNotifs, ciscoFipsStatsMIBGroup=ciscoFipsStatsMIBGroup, cfipsPostStatus=cfipsPostStatus, ciscoFipsStatsMIBCompliance=ciscoFipsStatsMIBCompliance, ciscoFipsStatsMIBGroups=ciscoFipsStatsMIBGroups, ciscoFipsStatsMIBConform=ciscoFipsStatsMIBConform, ciscoFipsStatsMIBCompliances=ciscoFipsStatsMIBCompliances, cfipsStats=cfipsStats, cfipsStatsGlobal=cfipsStatsGlobal)
|
N = int(input())
a = list(map(int, input().split()))
s = float("inf")
for i in range(min(a), max(a) + 1):
t = 0
for j in a:
t += (j - i) ** 2
s = min(s, t)
print(s)
|
n_temperaturas = int(input("Quantidade de temperaturas que irá digitar: "))
temperaturas = []
n_temperatura = 1
for i in range(n_temperaturas):
print("Temperatura n° ", n_temperatura)
temperatura = temperaturas.append(float(input("Digite a temperatura: ")))
n_temperatura += 1
print("Maior temperatura = ", max(temperaturas))
print("Menor temperatura = ", min(temperaturas))
print("Média = ", round(sum(temperaturas) / len(temperaturas), 2))
|
class LoginBase():
freeTimeExpires = -1
def __init__(self, cr):
self.cr = cr
def sendLoginMsg(self, loginName, password, createFlag):
pass
def getErrorCode(self):
return 0
def needToSetParentPassword(self):
return 0
|
class RequiredClass:
pass
def main():
required = RequiredClass()
print(required)
if __name__ == '__main__':
main()
|
def join_topic(part1: str, part2: str):
p1 = part1.rstrip('/')
p2 = part2.rstrip('/')
return p1 + '/' + p2
|
# encoding: utf-8
class DropShadowFilter(object):
def __init__(self, distance=4.0, angle=45.0, color=0, alpha=1.0,
blurX=4.0, blurY=4.0, strength=1.0, quality=1,
inner=False, knockout=False, hideObject=False):
self._type = 'DropShadowFilter'
self.distance = distance
self.angle = angle
self.color = color
self.alpha = alpha
self.blurX = blurX
self.blurY = blurY
self.strength = strength
self.quality = quality
self.inner = inner
self.knockout = knockout
self.hideObject = hideObject
def clone(self):
return DropShadowFilter(self.distance, self.angle, self.color,
self.alpha, self.blurX, self.blurY,
self.strength, self.quality,
self.inner, self.knockout,
self.hideObject)
|
class Red_Black_Tree(object):
class __Node(object):
def __init__(self, key, value=None, color=None, parent=None, left=None, right=None):
self.key = key
self.value = value
self.color = color # black = 0 red = 1
self.parent = parent
self.left = left
self.right = right
def __init__(self):
self.__NIL = self.__Node('NIL')
self.__NIL.color = 0
self.__NIL.value = None
self.__NIL.left = self.__NIL.right = self.__NIL
self.__root = self.__Node(None)
self.__root.color = 0
self.__root.left = self.__NIL
self.__root.right = self.__NIL
self.__root.parent = self.__NIL
def __find_node(self, key):
# return key's uplvl
node = self.__root
while True:
if key < node.key:
flow = 'left'
else:
flow = 'right'
next_node = getattr(node, flow)
if next_node is self.__NIL or next_node.key == key:
return (node, flow)
else:
node = next_node
def get(self, key):
node, flow = self.__find_node(key)
node = getattr(node, flow)
if node is self.__NIL:
val = 'Non-Existent'
else:
val = node.value
return val
# def __node_switch(self, node, node_link, target, target_link):
# '''
# link [node]'s [nlink] to [target]'s [target link]
# :param node: change node
# :param node_link: left or right or parent
# :param target: link to where
# :param target_link: left or right or parent
# :return: None
# '''
# # change parent
# if node_link == 'parent':
# current_p = node.parent
# # parent unlink
# if current_p.left == node:
# current_p.left = None
# else:
# current_p.right =None
# # link to new parent
# setattr(target, target_link, node)
# setattr(node, node_link, target)
# # change left child
# if node_link in ['left','right']:
# # clean old child's parent
# getattr(node, node_link).parent = None
# # link new child
# setattr(node, node_link, target)
# setattr(target, target_link, node)
def __left_rotate(self, node):
y = node.right
y.parent = node.parent
if node.parent == self.__NIL:
self.__root = y
else:
if node.parent.left == node:
node.parent.left = y
else:
node.parent.right = y
node.parent = y
node.right = y.left
y.left = node
return
def __right_rotate(self, node):
x = node.left
x.parent = node.parent
if node.parent == self.__NIL:
self.__root = x
else:
if node.parent.left == node:
node.parent.left = x
else:
node.parent.right = x
node.parent = x
node.left = x.right
x.right = node
return
def __recolor(self, node):
'''
# case 1
# node and parent is red 1 -> 0
# node's uncle is red 1 -> 0
# parent parent is black 0 -> 1
:param node: conflict node
:return: node's grandparent
'''
node.parent.parent.color = 1
node.parent.parent.left.color = 0
node.parent.parent.right.color = 0
return node.parent.parent
def __insert_fix_up(self, insert_node):
conflict = insert_node
while conflict.parent.color == 1:
if conflict.parent.parent.left == conflict.parent:
# insert_node is a right node
# position = 'right'
y = conflict.parent.parent.right
if y.color == 1:
# case 1
conflict = self.__recolor(conflict)
else:
if conflict.parent.right == conflict:
# case 2
conflict = conflict.parent
self.__left_rotate(conflict)
# case 3
conflict.parent.color = 0
conflict.parent.parent.color = 1
self.__right_rotate(conflict.parent.parent)
else:
# insert_node is a left node
# position = 'left'
y = conflict.parent.parent.left
if y.color == 1:
# case 1
conflict = self.__recolor(conflict)
else:
if conflict.parent.left == conflict:
# case 2
self.__right_rotate(conflict.parent)
# case 3
conflict.parent.color = 0
conflict.parent.parent.color = 1
self.__left_rotate(conflict.parent.parent)
# y = getattr(conflict.parent.parent, position)
# case_2 = {'right':'__left_rotate', 'left':'__right_rotate'}
# case_3 = {'left': '__left_rotate', 'right': '__right_rotate'}
# if y.color == 1:
# # case 1
# conflict = self.__recolor(conflict)
# else:
# if getattr(conflict.parent, position) == conflict:
# # case 2
# getattr(self,case_2[position])(conflict.parent)
# # case 3
# conflict.parent.color = 0
# conflict.parent.parent.color = 1
# getattr(self, case_3[position])(conflict.parent.parent)
self.__root.color = 0 # root is black
return
def insert(self, key, value = None):
# key,value可以为可迭代对象
if self.__root.key is None:
new_node = self.__root
else:
new_node = self.__Node(key)
parent, flow = self.__find_node(key)
setattr(parent, flow, new_node)
new_node.parent = parent
new_node.key = key
new_node.value = value
new_node.color = 1 # RED
new_node.left = self.__NIL
new_node.right = self.__NIL
self.__insert_fix_up(new_node)
return
def dins(self, key_value):
# key_value 是一个 键为key 值为value的字典
for key in key_value:
self.insert(key, key_value[key])
return
def max(self, node):
while node.right is not self.__NIL:
node = node.right
return node
def min(self, node):
while node.left is not self.__NIL:
node = node.left
return node
def __delete_fix_up(self, node):
# node = delnode.child when del delnode delnode's subtree height -1
# if node is red then color node to black --> subtree height +1 --> OK
# if node is black 3 condition
# condition 1: node.p = black node.p.other child = black
# condition 2:node.p = black node.p.other child = red
# condition 3: node.p = red node.p.other child = black (actually same as condition 1)
# case 1 sol(condition 2 sol): node.p -> red; node.p.another child -> black; LR(node.p); turn to case 2\3\4
# condition 1\3: case 2: node.p.other child.child both black
# case 3: node.p.other child.left red, right black
# case 4: node.p.other child.right red, left whatever
# case 2 sol: node.p.another child --> red then node.p subtree height both -1 so node.p should--> black
# if node.p = red then node.p -> black, height +1; FINISH else _delete_fix_up(node.p(double black))
# case 3 sol: node.p.other child -> red; node.p.other child.left -> black; RR(node.p.other child) turn to case 4
# case 4 sol: node.p --> black; node.p.other child --> red; node.p.other child.right --> black;LR(node.p); FINISH
while node is not self.__root and node.color == 0:
if node is node.parent.left:
other_child = node.parent.right
if node.parent.color == 0 and other_child.color == 1:
# case 1
node.parent.color = 1
other_child.color = 0
self.__left_rotate(node.parent)
other_child = node.parent.right
if other_child.left.color == 0 and other_child.right.color == 0:
# case 2
other_child.color = 1
node = node.parent
else:
if other_child.left.color == 1 and other_child.right.color == 0:
# case 3
other_child.color = 1
other_child.left.color = 0
self.__right_rotate(other_child)
# case 4
node.parent.color = 0
other_child.color = 1
other_child.right.color = 0
self.__left_rotate(node.parent)
node = self.__root
else:
other_child = node.parent.left
if node.parent.color == 0 and other_child.color == 1:
# case 1
node.parent.color = 1
other_child.color = 0
self.__right_rotate(node.parent)
other_child = node.parent.right
if other_child.left.color == 0 and other_child.right.color == 0:
# case 2
other_child.color = 1
node = node.parent
else:
if other_child.right.color == 1 and other_child.left.color == 0:
# case 3
other_child.color = 1
other_child.right.color = 0
self.__left_rotate(other_child)
# case 4
node.parent.color = 0
other_child.color = 1
other_child.left.color = 0
self.__right_rotate(node.parent)
node = self.__root
node.color = 0 # for condition 2 and case 2-1
return
def delete(self, key):
# 叶子节点
node = self.__getnode(key)
# 如果是叶子节点 删除node 如果是只有左或者只有右 删除node 将子节点接上node的父节点 如果有左有由 将后继的key放入node 删除后继
delnode = node if node.left is self.__NIL or node.right is self.__NIL else self.min(node.right) # 后继:右子树中的最小值
delnode_child = delnode.left if delnode.left is not self.__NIL else delnode.right # 子树,如果是叶子 左=右=nil
delnode_child.parent = delnode.parent # 将子树的父改为删除节点的父
if delnode.parent is self.__NIL:
# 判断是否是根节点
self.__root = delnode_child
else:
if delnode == delnode.parent.left:
#删除的节点是其父的左
delnode.parent.left = delnode_child
else:
# 删除的节点是其父的右
delnode.parent.right = delnode_child
if delnode is not node:
# 如果删除的是后继 将后继的key覆盖node的key
node.key = delnode.key
if delnode.color == 0:
#如果删除的是一个黑节点将违反黑节点高度原则 进行修复
self.__delete_fix_up(delnode_child)
return
# 中序遍历
# 二叉树可视化打印
def visual(self):
return
RBT = Red_Black_Tree()
# RBT.insert(11)
# RBT.insert(2)
# RBT.insert(14)
# RBT.insert(1)
# RBT.insert(7)
# RBT.insert(15)
# RBT.insert(5)
# RBT.insert(8)
# RBT.insert(4)
a = dict(zip([11,2,14,1,7,15,5,8,4],[11,2,14,1,7,15,5,8,4]))
RBT.dins(a)
print(RBT.get(1))
print(RBT.get(3))
print()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 12 13:38:30 2022
@author: mlols
"""
def hk_modes(hier_num):
"""
Generate modes in the HK hierarchy.
Parameters
----------
hier_num : int
Number in the HK hierarchy (hier_num = n means the nth model).
Returns
-------
p_modes : list
List of psi modes, represented as tuples.
Each tuple contains the horizontal and vertical wavenumbers.
t_modes : list
List of theta modes, represented as tuples.
Examples
--------
>>> p_modes, t_modes = hk_modes(1)
>>> print(p_modes)
[(0, 1), (1, 1)]
>>> print(t_modes)
[(0, 2), (1,1)]
>>> p_modes, t_modes = hk_modes(2)
>>> print(p_modes)
[(0, 1), (0, 3), (1, 1), (1, 2)]
>>> print(t_modes)
[(0, 2), (0, 4), (1,1), (1, 2)]
"""
p_modes = [(0,1), (1,1)] #Base model
t_modes = [(0,2), (1,1)]
current_pair = (1,1) #
#Add pairs of modes. Fills shells of constant L1 norm by increasing norm.
#Within shell, fills modes in descending lexicographical order.
#When starting new shell, add modes of zero horiz wavenumber.
for i in range(1, hier_num):
if current_pair[1] == 1:
level = current_pair[0]+1
current_pair = (1, level)
p_modes.append((0, level*2-1))
t_modes.append((0, level*2))
else:
current_pair = (current_pair[0]+1, current_pair[1]-1)
p_modes.append(current_pair)
t_modes.append(current_pair)
p_modes.sort()
t_modes.sort()
return p_modes, t_modes
|
#!/usr/bin/env python3
class Solution:
def setZeroes(self, matrix):
nrow, ncol = len(matrix), len(matrix[0])
for i in range(nrow):
for j in range(ncol):
if matrix[i][j] == 0:
matrix[i][j] = 'X'
for k in range(ncol):
if matrix[i][k] != 0:
matrix[i][k] = 'X'
for k in range(nrow):
if matrix[k][j] != 0:
matrix[k][j] = 'X'
for i in range(nrow):
for j in range(ncol):
if matrix[i][j] == 'X':
matrix[i][j] = 0
for i in range(nrow):
print(matrix[i])
matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
matrix = [[1,1,1],[1,0,1],[1,1,1]]
sol = Solution()
sol.setZeroes(matrix)
|
""" Class description goes here. """
"""Exceptions classes used in dataclay."""
__author__ = 'Alex Barcelo <alex.barcelo@bsc.es>'
__copyright__ = '2015 Barcelona Supercomputing Center (BSC-CNS)'
|
# Parameters
BEHAVIORS = 'behaviors'
STIMULUS_ELEMENTS = 'stimulus_elements'
MECHANISM_NAME = 'mechanism'
START_V = 'start_v'
START_VSS = 'start_vss'
START_W = 'start_w'
ALPHA_V = 'alpha_v'
ALPHA_VSS = 'alpha_vss'
ALPHA_W = 'alpha_w'
BETA = 'beta'
MU = 'mu'
DISCOUNT = 'discount'
TRACE = 'trace'
BEHAVIOR_COST = 'behavior_cost'
U = 'u'
LAMBDA = 'lambda'
RESPONSE_REQUIREMENTS = 'response_requirements'
BIND_TRIALS = 'bind_trials'
N_SUBJECTS = 'n_subjects'
TITLE = 'title'
SUBPLOTTITLE = 'subplottitle'
RUNLABEL = 'runlabel'
SUBJECT = 'subject'
XSCALE = 'xscale'
XSCALE_MATCH = 'xscale_match'
PHASES = 'phases'
CUMULATIVE = 'cumulative'
MATCH = 'match'
FILENAME = 'filename'
# Commands
RUN = '@run'
VARIABLES = '@variables'
PHASE = '@phase'
FIGURE = '@figure'
SUBPLOT = '@subplot'
LEGEND = '@legend'
VPLOT = '@vplot'
VSSPLOT = '@vssplot'
WPLOT = '@wplot'
PPLOT = '@pplot'
NPLOT = '@nplot'
VEXPORT = '@vexport'
WEXPORT = '@wexport'
PEXPORT = '@pexport'
NEXPORT = '@nexport'
HEXPORT = '@hexport'
VSSEXPORT = '@vssexport'
# Other
DEFAULT = 'default'
RAND = 'rand'
CHOICE = 'choice'
COUNT = 'count'
COUNT_LINE = 'count_line'
KEYWORDS = (BEHAVIORS,
STIMULUS_ELEMENTS,
MECHANISM_NAME,
START_V,
START_VSS,
START_W,
ALPHA_V,
ALPHA_VSS,
ALPHA_W,
BETA,
MU,
DISCOUNT,
TRACE,
BEHAVIOR_COST,
U,
LAMBDA,
RESPONSE_REQUIREMENTS,
BIND_TRIALS,
N_SUBJECTS,
TITLE,
SUBPLOTTITLE,
RUNLABEL,
SUBJECT,
XSCALE,
XSCALE_MATCH,
PHASES,
CUMULATIVE,
MATCH,
FILENAME,
VARIABLES,
PHASE,
RUN,
FIGURE,
SUBPLOT,
LEGEND,
VPLOT,
VSSPLOT,
WPLOT,
PPLOT,
NPLOT,
VEXPORT,
WEXPORT,
PEXPORT,
NEXPORT,
DEFAULT,
RAND,
COUNT,
COUNT_LINE)
PHASEDIV = '|'
# Properties for evaluation
EVAL_SUBJECT = "subject"
EVAL_RUNLABEL = "runlabel"
# EVAL_EXACTSTEPS = "exact_steps"
EVAL_EXACT = "exact"
# EVAL_EXACTN = "exact_n"
EVAL_CUMULATIVE = "cumulative"
EVAL_PHASES = "phases"
EVAL_FILENAME = "filename"
# Property values for evaluation
EVAL_AVERAGE = "average"
EVAL_ON = "on"
EVAL_OFF = "off"
EVAL_ALL = "all"
|
nums_str = []
with open("dane/dane.txt") as f:
lines = []
for line in f:
sline = line.strip()
num = int(sline, 8)
num_str = str(num)
nums_str.append(num_str)
count = 0
for num_str in nums_str:
if num_str[0] == num_str[-1]:
count += 1
print(f"{count=}")
|
'''
Provides utility functions for encoding and decoding linestrings using the
Google encoded polyline algorithm.
'''
def encode_coords(coords):
'''
Encodes a polyline using Google's polyline algorithm
See http://code.google.com/apis/maps/documentation/polylinealgorithm.html
for more information.
:param coords: list of Point objects
:type coords: list
:returns: Google-encoded polyline string.
:rtype: string
'''
result = []
prev_lat = 0
prev_lng = 0
for item in coords:
lat, lng = int(item.lat * 1e5), int(item.lng * 1e5)
d_lat = _encode_value(lat - prev_lat)
d_lng = _encode_value(lng - prev_lng)
prev_lat, prev_lng = lat, lng
result.append(d_lat)
result.append(d_lng)
return ''.join(c for r in result for c in r)
def _split_into_chunks(value):
while value >= 32: #2^5, while there are at least 5 bits
# first & with 2^5-1, zeros out all the bits other than the first five
# then OR with 0x20 if another bit chunk follows
yield (value & 31) | 0x20
value >>= 5
yield value
def _encode_value(value):
# Step 2 & 4
value = ~(value << 1) if value < 0 else (value << 1)
# Step 5 - 8
chunks = _split_into_chunks(value)
# Step 9-10
return (chr(chunk + 63) for chunk in chunks)
def decode(point_str):
'''Decodes a polyline that has been encoded using Google's algorithm
http://code.google.com/apis/maps/documentation/polylinealgorithm.html
This is a generic method that returns a list of (latitude, longitude)
tuples.
:param point_str: Encoded polyline string.
:type point_str: string
:returns: List of 2-tuples where each tuple is (latitude, longitude)
:rtype: list
'''
# sone coordinate offset is represented by 4 to 5 binary chunks
coord_chunks = [[]]
for char in point_str:
# convert each character to decimal from ascii
value = ord(char) - 63
# values that have a chunk following have an extra 1 on the left
split_after = not (value & 0x20)
value &= 0x1F
coord_chunks[-1].append(value)
if split_after:
coord_chunks.append([])
del coord_chunks[-1]
coords = []
for coord_chunk in coord_chunks:
coord = 0
for i, chunk in enumerate(coord_chunk):
coord |= chunk << (i * 5)
#there is a 1 on the right if the coord is negative
if coord & 0x1:
coord = ~coord #invert
coord >>= 1
coord /= 100000.0
coords.append(coord)
# convert the 1 dimensional list to a 2 dimensional list and offsets to
# actual values
points = []
prev_x = 0
prev_y = 0
for i in xrange(0, len(coords) - 1, 2):
if coords[i] == 0 and coords[i + 1] == 0:
continue
prev_x += coords[i + 1]
prev_y += coords[i]
# a round to 6 digits ensures that the floats are the same as when
# they were encoded
points.append((round(prev_x, 6), round(prev_y, 6)))
return points
|
router = {"host":"192.168.56.1",
"port":"830",
"username":"cisco",
"password":"cisco123!",
"hostkey_verify":"False"
}
|
"""
======================================
Classifier (:mod:`classifier` package)
======================================
This package provides supervised machine learning classifiers.
The decision forest module (:mod:`classifier.decision_forest`)
--------------------------------------------------------------
.. automodule:: classifier.decision_forest
:members:
"""
|
class InstascrapeError(Exception):
"""Base exception class for all of the exceptions raised by Instascrape."""
class ExtractionError(InstascrapeError):
"""Raised when Instascrape fails to extract specified data from HTTP response."""
def __init__(self, message: str):
super().__init__("Failed to extract data from response. (message: '{0}')".format(message))
class PrivateAccessError(InstascrapeError):
"""Raised when user does not have permission to access specified data, i.e. private profile which the user is not following."""
def __init__(self):
super().__init__("The user profile is private and not being followed by you.")
class RateLimitedError(InstascrapeError):
"""Raised when Instascrape receives a 429 TooManyRequests from Instagram."""
def __init__(self):
super().__init__("(429) Too many requests. Failed to query data. Rate limited by Instagram.")
class NotFoundError(InstascrapeError):
"""Raised when Instascrape receives a 404 Not Found from Instagram."""
def __init__(self, message: str = None):
super().__init__(message or "(404) Nothing found.")
class ConnectionError(InstascrapeError):
"""Raised when Instascrape fails to connect to Instagram server."""
def __init__(self, url: str):
super().__init__("Failed to connect to '{0}'.".format(url))
class LoginError(InstascrapeError):
"""Raised when Instascrape fails to perform authentication, e.g. wrong credentials."""
def __init__(self, message: str):
super().__init__("Failed to log into Instagram. (message: '{0}')".format(message))
class TwoFactorAuthRequired(LoginError):
"""Raised when Instascrape fails to perform authentication due to two-factor authenticattion."""
def __init__(self):
super().__init__("two-factor authentication is required")
class CheckpointChallengeRequired(LoginError):
"""Raised when Instascrape fails to perform authentication due to checkpoint challenge."""
def __init__(self):
super().__init__("checkpoint challenge solving is required")
class AuthenticationRequired(InstascrapeError):
"""Raised when anonymous/unauthenticated (guest) user tries to perform actions that require authentication."""
def __init__(self):
super().__init__("Login is required in order to perform this action.")
class DownloadError(InstascrapeError):
"""Raised when Instascrape fails to download data from Instagram server."""
def __init__(self, message: str, url: str):
super().__init__("Download Failed -> {0} (url: '{1}')".format(message, url))
|
class Proxy:
def __init__(self, host, port):
self.host=host
self.port=port
self.succeed=0
self.fail=0
def markSucceed(self):
self.succeed +=1
def markFail(self):
self.fail +=1
def __str__(self):
return f'http://{self.host}:{self.port}'
|
lineitem_scheme = ["l_orderkey","l_partkey","l_suppkey","l_linenumber","l_quantity","l_extendedprice",
"l_discount","l_tax","l_returnflag","l_linestatus","l_shipdate","l_commitdate","l_receiptdate","l_shipinstruct",
"l_shipmode","l_comment", "null"]
order_scheme = ["o_orderkey", "o_custkey","o_orderstatus","o_totalprice","o_orderdate","o_orderpriority","o_clerk",
"o_shippriority","o_comment", "null"]
customer_scheme = ["c_custkey","c_name","c_address","c_nationkey","c_phone","c_acctbal","c_mktsegment","c_comment", "null"]
part_scheme = ["p_partkey","p_name","p_mfgr","p_brand","p_type","p_size","p_container","p_retailprice","p_comment","null"]
supplier_scheme = ["s_suppkey","s_name","s_address","s_nationkey","s_phone","s_acctbal","s_comment","null"]
partsupp_scheme = ["ps_partkey","ps_suppkey","ps_availqty","ps_supplycost","ps_comment","null"]
nation_scheme = ["n_nationkey","n_name","n_regionkey","n_comment","null"]
region_scheme = ["r_regionkey" ,"r_name","r_comment","null"]
schema_quotes = ["time","symbol","seq","bid","ask","bsize","asize","is_nbbo"]
schema_trades = ["time","symbol","size","price"]
|
#!/usr/bin/env python3
# Daniel Nicolas Gisolfi
class UserCommand:
""" The users input that will be translated into a shell command """
def __init__(self, cmd:str, args:list):
self.command = cmd
self.args = args
|
# https://github.com/adamsaparudin/python-datascience
# if (kondisi)
# if ("adam" == "adam") # True / False
# Task 1
# FIZZBUZZ
# print FIZZ jika bisa dibagi 3,
# print BUZZ jika bisa dibagi 5,
# print FIZZBUZZ jika bisa dibagi 15,
# print angka nya sendiri jika tidak bisa dibagi 3 atau 5
# input 6
# FIZZ
# input 10
# BUZZ
# input 30
# FIZZBUZZ
def print_fizzbuzz(numb):
if (numb % 15) == 0:
return "FIZZBUZZ"
elif (numb % 3) == 0:
print("FIZZ")
elif (numb % 5) == 0:
print("BUZZ")
else:
print( numb)
def tambahan(a, b):
return a + b
def main():
while True:
numb = int(input("Input bilangan bulat: "))
fizz = print_fizzbuzz(numb)
print(fizz)
main()
|
def parse_list_ranges(s,sep='-'):
r = []
x = s.split(',')
for y in x:
z = y.split(sep)
if len(z)==1:
r += [int(z[0])]
else:
r += range(int(z[0]),int(z[1])+1)
return list(r)
def parse_list_floats(s):
x = s.split(',')
return list(map(float, x))
|
class LayoutRuleFixedNumber(LayoutRule, IDisposable):
"""
This class indicate the layout rule of a Beam System is Fixed-Number.
LayoutRuleFixedNumber(numberOfLines: int)
"""
def Dispose(self):
""" Dispose(self: LayoutRuleFixedNumber,A_0: bool) """
pass
def ReleaseManagedResources(self, *args):
""" ReleaseManagedResources(self: APIObject) """
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: APIObject) """
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, numberOfLines):
""" __new__(cls: type,numberOfLines: int) """
pass
NumberOfLines = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Get or set the number of the beams in a beam system.
Get: NumberOfLines(self: LayoutRuleFixedNumber) -> int
Set: NumberOfLines(self: LayoutRuleFixedNumber)=value
"""
|
def print_tree(mcts_obj, root_node):
fifo = []
for child_node in root_node.children:
q = 0
if mcts_obj.visits[child_node] > 0:
q = mcts_obj.Q[child_node] / mcts_obj.visits[child_node]
print(
child_node,
mcts_obj.Q[child_node],
mcts_obj.visits[child_node],
q
)
fifo.append(child_node)
print("-")
while fifo:
root_node = fifo.pop()
print("(", root_node, ")")
for child_node in root_node.children:
q = 0
if mcts_obj.visits[child_node] > 0:
q = mcts_obj.Q[child_node] / mcts_obj.visits[child_node]
print(
child_node,
mcts_obj.Q[child_node],
mcts_obj.visits[child_node],
q
)
fifo.append(child_node)
if root_node.children:
print(" ")
def gen_tree_graph(root_node, G):
fifo = []
root_id = str(root_node)
G.add_node(root_id)
for child_node in root_node.children:
child_id = str(child_node)
G.add_node(child_id)
G.add_edge(root_id, child_id)
fifo.append(child_node)
while fifo:
root_node = fifo.pop()
root_id = str(root_node)
for child_node in root_node.children:
child_id = str(child_node)
G.add_node(child_id)
G.add_edge(root_id, child_id)
fifo.append(child_node)
|
class DataStructure(object):
def __init__(self):
self.name2id = {}
self.id2item = {}
def add_item(self, item_name, item_id, item):
self.name2id[item_name] = item_id
self.id2item[item_id] = item
def search_by_name(self, target_name):
target_id = self.name2id[target_name]
target_item = self.id2item[target_id]
return target_item
def search_by_id(self, target_id):
target_item = self.id2item[target_id]
return target_item
|
# © https://sudipghimire.com.np
# %% [markdown]
"""
# Inheritance
- This concept is exactly similar to biological inheritance where child inherits the feature of parent.
- in inheritance, there exists a parent class and child classes which inherits parent's behaviors.
- The base class will be the parent class and the class that is derived from the base class will
be treated as a child class.
Basic Structure
class Parent:
<attributes>
<methods>
class Child(Parent):
<attributes>
<methods>
Rectangle
attributes:
- width
- height
methods:
- perimeter
- area
variants:
square
Animal
attributes:
- legs: 4
- tail
variants:
- Pet
- Wild
- Herbivorous
- Carnivorous
"""
# %% Example Rectangle
class Rectangle:
width: float = 0
height: float = 0
def __init__(self, width, height):
self.width = width
self.height = height
def perimeter(self):
return 2 * (self.width + self.height)
def area(self):
return self.width * self.height
def diagonal_length(self):
return (self.width ** 2 + self.height ** 2) ** (1 / 2)
# %% child
class Square(Rectangle):
def __init__(self, width):
super().__init__(width=width, height=width)
def diagonal_length(self):
return self.width * (2 ** .5)
# %%
room_1 = Rectangle(5, 10)
print(f'Area of room 1: {room_1.area()}')
print(f'Perimeter of room 1: {room_1.perimeter()}')
print(f'Diagonal length of room 1: {room_1.diagonal_length()}')
# %%
room_2 = Square(5)
print(f'Area of room 2: {room_2.area()}')
print(f'Perimeter of room 2: {room_2.perimeter()}')
print(f'Diagonal length of room 2: {room_2.diagonal_length()}')
# %% builtin functions
# isinstance
print(isinstance(room_2, Square))
print(isinstance(room_1, Rectangle))
print(isinstance(room_1, Square))
print(isinstance(room_2, Rectangle))
# %% issubclass
print(issubclass(Square, Rectangle))
print(issubclass(Rectangle, Square))
print(issubclass(Rectangle, object))
|
class Calendar:
def __init__(self, day, month, year):
print("Clase Base - Calendar")
self.day = day
self.month = month
self.year = year
def __str__(self):
return "{}-{}-{}".format(self.day,
self.month,
self.year)
|
#My favorite song described
#Genre, Artists and Album
Genre = "Bollywood Romance"
Composer = "Amit Trivedi"
Lyricist = "Amitabh Bhattacharya"
Singer_male = "Arijit Singh"
Singer_female = "Nikhita Gandhi"
Album = "Kedarnath"
#YearReleased
YearReleased = 2018
#Duration
DurationInSeconds = 351
print("My favorite song is from the Album " + Album + " and in the genre " + Genre)
print("The artists of this song are :")
print("Composer: " + Composer)
print("Lyricist: " + Lyricist)
print("Singer(Male): " + Singer_male)
print("Singer(Female): " + Singer_female)
print("It was released in the year" , YearReleased , "and has a duration of", DurationInSeconds , "seconds")
|
#!/bin/python
#If player is X, I'm the first player.
#If player is O, I'm the second player.
player = raw_input()
#Read the board now. The board is a 3x3 array filled with X, O or _.
board = []
for i in xrange(0, 3):
board.append(raw_input())
#Proceed with processing and print 2 integers separated by a single space.
#Example: print random.randint(0, 2), random.randint(0, 2)
|
#kullanıcıdan alınan bir sayının tek mi ya da çift mi olduğunu bulan kodu yazınız
sayi = int(input("Bir Sayı Giriniz : "))
if sayi%2==0:
print(" Sayısı Çift Sayıdır. ",sayi)
else:
print(" Sayısı Tek Sayıdır. ",sayi )
|
A = 1.0
N = 1.0
α = 0.33
β = 0.96
δ = 0.05
def r_to_w(r):
"""
Equilibrium wages associated with a given interest rate r.
"""
return A * (1 - α) * (A * α / (r + δ))**(α / (1 - α))
def rd(K):
"""
Inverse demand curve for capital. The interest rate associated with a
given demand for capital K.
"""
return A * α * (N / K)**(1 - α) - δ
def prices_to_capital_stock(am, r):
"""
Map prices to the induced level of capital stock.
Parameters:
----------
am : Household
An instance of an aiyagari_household.Household
r : float
The interest rate
"""
w = r_to_w(r)
am.set_prices(r, w)
aiyagari_ddp = DiscreteDP(am.R, am.Q, β)
# Compute the optimal policy
results = aiyagari_ddp.solve(method='policy_iteration')
# Compute the stationary distribution
stationary_probs = results.mc.stationary_distributions[0]
# Extract the marginal distribution for assets
asset_probs = asset_marginal(stationary_probs, am.a_size, am.z_size)
# Return K
return np.sum(asset_probs * am.a_vals)
# Create an instance of Household
am = Household(a_max=20)
# Use the instance to build a discrete dynamic program
am_ddp = DiscreteDP(am.R, am.Q, am.β)
# Create a grid of r values at which to compute demand and supply of capital
num_points = 20
r_vals = np.linspace(0.005, 0.04, num_points)
# Compute supply of capital
k_vals = np.empty(num_points)
for i, r in enumerate(r_vals):
k_vals[i] = prices_to_capital_stock(am, r)
# Plot against demand for capital by firms
fig, ax = plt.subplots(figsize=(11, 8))
ax.plot(k_vals, r_vals, lw=2, alpha=0.6, label='supply of capital')
ax.plot(k_vals, rd(k_vals), lw=2, alpha=0.6, label='demand for capital')
ax.grid()
ax.set_xlabel('capital')
ax.set_ylabel('interest rate')
ax.legend(loc='upper right')
plt.show()
|
DEFAULT_ENV_NAME = "CartPole-v1"
DEFAULT_ALGORITHM = "random"
DEFAULT_MAX_EPISODES = 1000
DEFAULT_LEARNING_RATE = 0.001
DEFAULT_GAMMA = 0.95
DEFAULT_UPDATE_FREQUENCY = 20
|
def initials(name):
parts = name.split(' ')
letters = ''
for part in parts:
letters += part[0]
return letters
|
LISTA = [['add', ['adicionar'], 'added', 'added'], ['arise', ['erguer', 'levantar'], 'arose', 'arisen'],
['awake', ['acordar', 'despertar'], 'awoke', 'awoken'], ['answer', ['responder'], 'answered', 'answered'],
['ask', ['perguntar'], 'asked', 'asked'], ['be', ['ser', 'estar'], 'was-were', 'been'],
['bear', ['suportar', 'aguentar'], 'bore', 'borne'], ['beat', ['bater', 'espancar', 'superar', 'vibrar', 'palpitar'], 'beat', 'beaten'],
['become', ['tornar-se'], 'became', 'become'], ['begin', ['comecar', 'iniciar'], 'began', 'begun'],
['bend', ['curvar', 'entortar'], 'bent', 'bent'], ['bet', ['apostar'], 'bet', 'bet'],
['bite', ['morder', 'engolir-a-isca'], 'bit', 'bitten'], ['bring', ['trazer', 'servir'], 'brought', 'brought'],
['bleed', ['sangrar'], 'bled', 'bled'], ['blow', ['soprar', 'assobiar'], 'blew', 'blown'],
['break', ['quebrar', 'romper'], 'broke', 'broken'], ['build', ['construir', 'fabricar'], 'built', 'built'],
['burn', ['queimar', 'incendiar'], 'burnt', 'burnt'], ['buy', ['comprar'], 'bought', 'bought'],
['call', ['chamar', 'ligar'], 'called', 'called'], ['can', ['poder'], 'could', ''],
['cast', ['arremessar', 'jogar'], 'cast', 'cast'], ['carry', ['carregar'], 'carried', 'carried'],
['catch', ['pegar', 'adquirir'], 'caught', 'caught'], ['change', ['mudar'], 'changed', 'changed'],
['choose', ['escolher', 'selecionar'], 'chose', 'chosen'], ['close', ['fechar'], 'closed', 'closed'],
#
['come', ['vir'], 'came', 'come'], ['cost', ['custar'], 'cost', 'cost'],
['cover', ['cobrir'], 'covered', 'covered'], ['cry', ['chorar'], 'cried', 'cried'],
['cut', ['cortar'], 'cut', 'cut'], ['deal', ['distribuir', 'negociar'], 'dealt', 'dealt'],
['dig', ['cavar', 'escavar'], 'dug', 'dug'], ['do', ['fazer'], 'did', 'done'],
['draw', ['desenhar', 'extrair'], 'drew', 'drawn'], ['drink', ['beber'], 'drank', 'drunk'],
['drive', ['dirigir'], 'drove', 'driven'], ['dry', ['secar'], 'dried', 'dried'],
['eat', ['comer'], 'ate', 'eaten'], ['end', ['acabar'], 'ended', 'ended'],
['explain', ['explicar'], 'explained', 'explained'], ['fall', ['cair', 'diminuir', 'decrescer'], 'fell', 'fallen'],
['feel', ['sentir', 'notar'], 'felt', 'felt'], ['fight', ['lutar', 'brigar'], 'fought', 'fought'],
['fill', ['encher', 'preencher'], 'filled', 'filled'], ['find', ['encontrar', 'achar'], 'found', 'found'],
['fly', ['voar'], 'flew', 'flown'], ['follow', ['seguir'], 'followed', 'followed'],
['forbid', ['proibir'], 'forbade', 'forbidden'], ['forget', ['esquecer-se'], 'forgot', 'forgotten'],
['forgive', ['perdoar'], 'forgave', 'forgiven'], ['forsake', ['abandonar', 'deserdar'], 'forsook', 'forsaken'],
['freeze', ['congelar'], 'froze', 'frozen'], ['get', ['pegar', 'obter', 'conseguir'], 'got', 'got'],
['give', ['dar'], 'gave', 'given'], ['go', ['ir'], 'went', 'gone'],
['feed', ['alimentar', 'nutrir'], 'fed', 'fed'],
#
['grow', ['crescer', 'florescer'], 'grew', 'grown'],
['hang', ['pendurar', 'suspender'], 'hung', 'hung'], ['happen', ['acontecer'], 'happened', 'happened'],
['have', ['ter'], 'had', 'had'], ['hear', ['ouvir', 'escutar'], 'heard', 'heard'],
['help', ['ajudar'], 'helped', 'helped'], ['hide', ['esconder-se', 'ocultar'], 'hid', 'hidden'],
['hit', ['bater', 'chocar-se'], 'hit', 'hit'], ['hold', ['segurar', 'agarrar'], 'held', 'held'],
['hurt', ['machucar'], 'hurt', 'hurt'], ['keep', ['manter', 'preservar'], 'kept', 'kept'],
['kneel', ['ajoelhar-se'], 'knelt', 'knelt'], ['knit', ['tricotar'], 'knit', 'knit'],
['know', ['saber', 'conhecer'], 'knew', 'known'], ['lay', ['por', 'colocar', 'deitar'], 'laid', 'laid'],
['lead', ['conduzir', 'liderar'], 'led', 'led'], ['leap', ['saltar', 'pular'], 'leapt', 'leapt'],
['learn', ['aprender'], 'learnt', 'learnt'], ['leave', ['deixar', 'partir'], 'left', 'left'],
['lend', ['emprestar'], 'lent', 'lent'], ['let', ['deixar', 'permitir'], 'let', 'let'],
['lie', ['deitar'], 'lay', 'lain'], ['light', ['acender', 'iluminar'], 'lit', 'lit'],
['like', ['gostar'], 'liked', 'liked'], ['listen', ['escutar'], 'listened', 'listened'],
['live', ['viver'], 'lived', 'lived'], ['look', ['olhar'], 'looked', 'looked'],
['lose', ['perder'], 'lost', 'lost'], ['love', ['amar'], 'loved', 'loved'],
['make', ['fazer', 'produzir'], 'made', 'made'],
#
['may', ['poder'], 'might', ''],
['mean', ['significar'], 'meant', 'meant'], ['meet', ['encontrar', 'reunir'], 'met', 'met'],
['move', ['mover'], 'moved', 'moved'], ['need', ['precisar'], 'needed', 'needed'],
['open', ['abrir'], 'opened', 'opened'], ['pay', ['pagar'], 'paid', 'paid'],
['plan', ['planejar'], 'planned', 'planned'], ['play', ['jogar', 'tocar', 'brincar'], 'played', 'played'],
['pull', ['puxar'], 'pulled', 'pulled'], ['put', ['colocar'], 'put', 'put'],
['quit', ['desistir', 'abandonar'], 'quit', 'quit'], ['read', ['ler'], 'read', 'read'],
['remember', ['lembrar'], 'remembered', 'remembered'], ['ride', ['cavalgar', 'andar-de-bike', 'andar-de-carro'], 'rode', 'ridden'],
['ring', ['soar', 'tocar-campainha'], 'rang', 'rung'], ['rise', ['erguer-se', 'levantar-se'], 'rose', 'risen'],
['run', ['correr'], 'ran', 'run'], ['saw', ['serrar'], 'sawed', 'sawn'],
['say', ['dizer'], 'said', 'said'], ['see', ['ver'], 'saw', 'seen'],
['seem', ['parecer'], 'seemed', 'seemed'], ['seek', ['procurar', 'pedir', 'almejar'], 'sought', 'sought'],
['sell', ['vender'], 'sold', 'sold'], ['set', ['por', 'ajustar'], 'set', 'set'],
['sew', ['costurar'], 'sewed', 'sewn'], ['shake', ['sacudir', 'agitar', 'apertar-a-mao'], 'shook', 'shaken'],
['shave', ['barbear'], 'shaved', 'shaved'], ['shine', ['brilhar'], 'shone', 'shone'],
['shoot', ['atirar', 'ferir-com-tiro'], 'shot', 'shot'],
#
['show', ['mostrar', 'atirar'], 'showed', 'show'],
['shred', ['picar', 'retalhar', 'rasgar', 'cortar-em-pedacos'], 'shred', 'shred'], ['shrink', ['contrair', 'encolher'], 'shrank', 'shrunk'],
['shut', ['tampar', 'cerrar', 'fechar'], 'shut', 'shut'], ['sing', ['cantar'], 'sang', 'sung'],
['sink', ['afundar'], 'sank', 'sunk'], ['sit', ['sentar-se'], 'sat', 'sat'],
['slay', ['matar', 'assassinar', 'arruinar', 'destruir'], 'slew', 'slain'], ['sleep', ['dormir'], 'slept', 'slept'],
['slide', ['deslizar', 'escorregar'], 'slid', 'slid'], ['smell', ['cheirar'], 'smelt', 'smelt'],
['sow', ['semear'], 'sowed', 'sown'], ['speak', ['falar', '(mododefalar)'], 'spoke', 'spoken'],
['spell', ['soletrar'], 'spelt', 'spelt'], ['spend', ['gastar-dinheiro', 'gastar-tempo'], 'spent', 'spent'],
['spill', ['derramar'], 'spilt', 'spilt'], ['spin', ['girar'], 'spun', 'spun'],
['spoil', ['estragar', 'destruir', 'mimar'], 'spoilt', 'spoilt'], ['spread', ['espalhar', 'estender'], 'spread', 'spread'],
['spring', ['saltar', 'lancar-se'], 'sprang', 'sprung'], ['stand', ['por-se-de-pe'], 'stood', 'stood'],
['start', ['comecar'], 'started', 'started'], ['stay', ['ficar'], 'stayed', 'stayed'],
['steal', ['roubar'], 'stole', 'stolen'], ['stick', ['fincar', 'cravar'], 'stuck', 'stuck'],
['sting', ['picar', 'ferroar'], 'stung', 'stung'], ['stink', ['enjoar', 'feder'], 'stank', 'stunk'],
['stop', ['parar'], 'stopped', 'stopped'], ['strick', ['bater', 'golpear'], 'struck', 'struck'],
#
['string', ['amarrar', 'pendurar', 'enfiar'], 'strung', 'strung'], ['strive', ['aspirar', 'tentar', 'esforcar'], 'strove', 'striven'],
['study', ['estudar'], 'studied', 'studied'], ['swear', ['jurar'], 'swore', 'sworn'],
['sweat', ['suar'], 'sweat', 'sweat'], ['sweep', ['varrer'], 'swept', 'swept'],
['swell', ['inchar', 'crescer', 'encher-pneus'], 'swelled', 'swollen'], ['swin', ['nadar'], 'swan', 'swun'],
['swing', ['balancar'], 'swang', 'swung'], ['take', ['pegar', 'levar', 'tomar'], 'toke', 'taken'],
['talk', ['conversar'], 'talked', 'talked'], ['teach', ['ensinar'], 'taught', 'taught'],
['tear', ['lacrimejar'], 'tore', 'torn'], ['tell', ['contar'], 'told', 'told'],
['think', ['achar', 'pensar'], 'thought', 'thought'], ['thrive', ['ter-sucesso'], 'throve', 'thriven'],
['throw', ['lancar', 'atirar'], 'threw', 'thrown'], ['thrust', ['empurrar'], 'thrust', 'thrust'],
['travel', ['viajar'], 'traveled', 'traveled'], ['try', ['tentar'], 'tried', 'tried'],
['turn', ['girar'], 'turned', 'turned'], ['understand', ['entender', 'compreender'], 'understood', 'understood'],
['use', ['usar'], 'used', 'used'], ['wait', ['esperar'], 'waited', 'waited'],
['wake', ['acordar'], 'woke', 'woken'], ['walk', ['andar', 'caminhar'], 'walked', 'walked'],
['want', ['querer'], 'wanted', 'wanted'], ['watch', ['assistir'], 'watched', 'watched'],
['wear', ['vestir', 'usar', 'trajar'], 'wore', 'worn'], ['weave', ['lancar', 'tecer'], 'wove', 'woven'],
#
['win', ['ganhar', 'vencer'], 'won', 'won'], ['wind', ['girar', 'enrolar-se'], 'wound', 'wound'],
['work', ['trabalhar'], 'worked', 'worked'], ['write', ['ecrever'], 'wrote', 'written'],
['wring', ['torcer'], 'wrung', 'wrung'],] # PASTE YOUR LIST HERE
# 0 = palavra 1 = traduções 2 = passado 3 = particípio
def get():
return LISTA
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.